Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create HTTP response errors and timeouts for testing? [closed]
I suspect a counter outside scope could be used to do this. Does anyone know if there is a particular convention or interceptor to do the same? I’ll be using Flask or Django frameworks. -
Test a model property in django using Pytest
I want to test the output of a model property in django using pytest[pytest-django]. models.py: class TravelFriend(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name="travel_friends") name = models.CharField(max_length=100) birthdate = models.DateField() def __str__(self): return self.name @property def age(self): days_in_year = 365.2425 age = int((date.today() - self.birthdate).days / days_in_year) if age >= 18: return "18+" else: return age basically the property return the age in years or the string '18+' if the age is more than 18 test_models.py: class TestTravelFriend: def test_travelfriend(self): """The family member is connected to a user and have valid attributes""" travel_friend = TravelFriendFactory() assert travel_friend is not None assert str(travel_friend) == travel_friend.name assert travel_friend.user is not None assert travel_friend.name is not None assert travel_friend.birthdate is not None assert travel_friend.age is not None factories.py: class TravelFriendFactory(factory.django.DjangoModelFactory): class Meta: model = "accounts.TravelFriend" user = factory.SubFactory("accounts.tests.factories.CustomUserFactory") birthdate = factory.Faker( "date_of_birth", maximum_age=25, ) I want to test that the output of the property is correct but if i put an if statement in the test like this year = -int(travel_friend.birthdate.year - date.today().year) if year < 18: assert travel_friend.age == year else: assert travel_friend.age == "18+" but in order to have 100% coverage I need to test this last part of code which I don't … -
how to create a server-side datatable that displays my data from by database
i need the views and the url and the js i tried alot but didnt work the data is displayed but the datatable stops working this is for my views def get_data_for_datatable(request): employees = Users.objects.all() data = [] for employee in employees: data.append({ "Name": employee.Name, "Gender": employee.Gender, "Email": employee.Email, "Department": employee.Department, "Salary": employee.Salary, }) return JsonResponse({ "data": data, }) this is for my js what s the problem $(document).ready(function() { $("#example").DataTable({ "ajax": "json/", "columns": [ {"data": "Name"}, {"data": "Gender"}, {"data": "Email"}, {"data": "Department"}, {"data": "Salary"}, ], processing: true, serverSide:true, paging: true, pageLength: 10, lengthChange: true, autoWidth: true, searching: true, bInfo: true, bSort: true, }) }) -
Adding fields to ModelForm programatically not showing in django admin
I have a usecase where I want to add fields to a modelform in django admin, but when trying to add them in the __init__function like this: class PackageFileInlineForm(forms.ModelForm): class Meta: model = File fields = '__all__' def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.fields['test'] = forms.CharField(max_length=100) Nothing shows up in the form. However if I do the form like this: class PackageFileInlineForm(forms.ModelForm): test = forms.CharField(max_length=100) class Meta: model = File fields = '__all__' Why does the init version not work? -
Django Multiple User's Authentication, SignUp Serializer and Views
I'm practicing creating multiple user types of authentication (in this scenario, Client and Driver like Uber) along with JWT. Currently, I am trying to write the SignUp Serializer for each corresponding user type (or if there is any more elegant way to do this), after signing up, I would love the user to have a Token. Please have a look at my code and teach me how or what could I do. This is my models from django.db import models from django.utils import timezone from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): email = models.EmailField(unique=True) # vars to check whether user is client or driver is_client = models.BooleanField(default=False) is_driver = models.BooleanField(default=False) class Client(models.Model): is_staff = False user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) def __str__(self): return self.user.username class Driver(models.Model): is_staff = False user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) def __str__(self): return self.user.username My serializers.py (kinda messy) from rest_framework import serializers from base.models import User, Customer, Technician from rest_framework_simplejwt.tokens import RefreshToken # Serialize data from db class UserSerializer(serializers.ModelSerializer): name = serializers.SerializerMethodField(read_only=True) _id = serializers.SerializerMethodField(read_only=True) isAdmin = serializers.SerializerMethodField(read_only=True) class Meta: model = User fields = ['id', '_id', 'username', 'email', 'name', 'isAdmin'] def get__id(self, obj): return obj.id def get_isAdmin(self, obj): return obj.is_staff def … -
KeyError 'django' occured after adding "rest_framework" to settings.py
I'm working on a django project and trying to use rest_framework. I'm running the project through docker desktop engine. Everything is fine until I add "rest_framework" to my project's settings.py in INSTALLED_APPS. I'm getting errors as below: 2023-07-28 15:08:59 Traceback (most recent call last): 2023-07-28 15:08:59 File "/usr/local/lib/python3.11/site-packages/django/template/utils.py", line 66, in __getitem__ 2023-07-28 15:08:59 return self._engines[alias] 2023-07-28 15:08:59 ~~~~~~~~~~~~~^^^^^^^ 2023-07-28 15:08:59 KeyError: 'django' 2023-07-28 15:08:59 2023-07-28 15:08:59 During handling of the above exception, another exception occurred: 2023-07-28 15:08:59 2023-07-28 15:08:59 Traceback (most recent call last): 2023-07-28 15:08:59 File "/code/manage.py", line 15, in <module> 2023-07-28 15:08:59 execute_from_command_line(sys.argv) 2023-07-28 15:08:59 File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line 2023-07-28 15:08:59 utility.execute() 2023-07-28 15:08:59 File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 413, in execute 2023-07-28 15:08:59 self.fetch_command(subcommand).run_from_argv(self.argv) 2023-07-28 15:08:59 File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 354, in run_from_argv 2023-07-28 15:08:59 self.execute(*args, **cmd_options) 2023-07-28 15:08:59 File "/usr/local/lib/python3.11/site-packages/django/core/management/commands/runserver.py", line 61, in execute 2023-07-28 15:08:59 super().execute(*args, **options) 2023-07-28 15:08:59 File "/usr/local/lib/python3.11/site-packages/django/core/management/base.py", line 398, in execute 2023-07-28 15:08:59 output = self.handle(*args, **options) 2023-07-28 15:08:59 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2023-07-28 15:08:59 File "/usr/local/lib/python3.11/site-packages/django/core/management/commands/runserver.py", line 96, in handle 2023-07-28 15:08:59 self.run(**options) 2023-07-28 15:08:59 File "/usr/local/lib/python3.11/site-packages/django/core/management/commands/runserver.py", line 103, in run 2023-07-28 15:08:59 autoreload.run_with_reloader(self.inner_run, **options) 2023-07-28 15:08:59 File "/usr/local/lib/python3.11/site-packages/django/utils/autoreload.py", line 637, in run_with_reloader 2023-07-28 15:08:59 start_django(reloader, main_func, *args, **kwargs) 2023-07-28 15:08:59 File "/usr/local/lib/python3.11/site-packages/django/utils/autoreload.py", … -
Django IntegrityError: duplicate key value violates unique constraint ... DETAIL: Key ... already exists
In a Django app with Postgres db i have a model named Block. It is used in other models as ForeignKey class Block(models.Model): name = TranslatedField(models.CharField(max_length=200),) color = models.IntegerField(choices=BLOCKCOLOR_CHOICES, null=True, blank=True) blocktype = models.CharField(max_length=20, choices=BLOCKTYPE_CHOICES, default="break") def save(self, *args, **kwargs): self.name = self.name.capitalize() return super().save(self, *args, **kwargs) def __str__(self): return f"{self.name} ({self.blocktype})" I use django-translated-fields to translate the name in 4 languages. These are the relevant lines in admin: class BlockAdmin(TranslatedFieldAdmin, admin.ModelAdmin): pass admin.site.register(Block, BlockAdmin) I can create a new instance of Block in the admin interface and also in the view. When I edit the model and try to save I get the above mentioned error. It happens in the admin interface and in the view as well. I can manually delete the model and create a new one, it gets a new id. It doesn't matter if the model is already bound via ForeignKey to another model or if it's standalone. Can somebody give me an advice? Thank you in advance! I have tried manipulating the id in the database, as a final solution I have also deleted the database completely. It happens again. I have a feeling that it has something to do with the django-translated-fields package. … -
ORA-00955 error with django migrate but no tables in Oracle database
I'm trying to deploy a Django application on an Apache webserver and Oracle DB. When I get to trying to create the database tables using manage.py migrate I get an error ORA-00955: name is already used by an existing object. It doesn't tell me what the object is (which is frustrating). Looking at the database I don't have any tables in my schema. I have run migrate more than once due to an earlier failure, but there's nothing there that I can see (I'm looking at the database in DBeaver). I've tried SELECT table_name FROM all_tables WHERE owner = 'MYUSERNAME'; but that doesn't return anything. Is there some way to find out what the blocking object is? Is there some way to make migrate force its way through? What am I missing that means I can't see the tables that the database sees? -
Dynamic class selection before object detection
I have a set of predefined classes to be detected in my object detection code. I want to choose the classes dynamically before the detection starts. Is this possible? I am selecting only the classes that I have trained the model for I have to detect only the selected classes -
Nginx is showing the default page instead of Django application (Ubuntu 22.04)
I am trying to host django project with ubuntu, gunicorn and postgresql, also I use docker for development. As I don't have an IP-address for server I am just trying to host to standard django localhost in order to practise with Nginx (I used the guidline on DigitalOcean) as I am new to it. I've already tried a lot, but my problem persists. Here is my Dockerfile: FROM python:3.11.1 SHELL ["/bin/bash", "-c"] ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONBUFFERED=1 EXPOSE 8000 WORKDIR /cycle_proj RUN pip install --upgrade pip RUN mkdir /cycle_proj/static && mkdir /cycle_proj/media RUN apt update && apt -qy install gcc libjpeg-dev libxslt-dev \ libpq-dev libmariadb-dev libmariadb-dev-compat gettext cron \ openssh-client flake8 python3-venv python3-dev locales \ postgresql postgresql-contrib nginx curl COPY . . COPY requirements.txt requirements.txt RUN pip3 install -r requirements.txt CMD ["gunicorn","-b","0.0.0.0:8001","core.wsgi:application"] Here is docker-compose: version: "3.9" services: # Django web: build: . volumes: - .:/cycle_proj - static_volume:/cycle_proj/static - media_volume:/cycle_proj/media ports: - '8000:8000' env_file: - web.env image: cycle_proj container_name: django_cycle_api command: > bash -c "./manage.py collectstatic --noinput && ./manage.py migrate && gunicorn -b 0.0.0.0:8000 core.wsgi:application" depends_on: - db # PostgreSQL db: image: postgres:14.1-alpine restart: always env_file: - web.env ports: - '5432:5432' volumes: - db:/var/lib/postgresql/data nginx: image: nginx depends_on: - web ports: … -
Django Python not redirecting to login page after clicking sign up button
This is my first Django project and I am trying to get users to be redirected to a login page after they fill out a sign up form and click on the sign up button; however, instead my sign up form just reloads and I am still in my signup.html page. I am not sure why this is happening and any help would be greatly appreciated.(note -idk whether this will be relevant or not- that my html files are in a templates folder, .js and .css files are in a static folder, both separate and at the same level as my app folder) (relevant) signup.html: <form class="form" action="{% url 'signup' %}" method="POST"> {% csrf_token %} <div class="form_button_container"> <button class ="form_button" type="submit">Sign Up</button> </div> <p class="form_text"> <a href="{% url 'login' %}">Already have an account? Log in</a> </p> views.py: def login(request): if request.method == "POST": email = request.POST["email"] password = request.POST["password1"] user = authenticate(email=email, password=password) if user is not None: login(request, user) return redirect('mainpg') else: return render(request, 'login.html', {"error": "Invalid username or password."}) return render(request, 'login.html') def signup(request): if request.method == "POST": try: username = request.POST['username'] except MultiValueDictKeyError as e: messages.error(request, 'Please enter a username.') return redirect('signup') name = request.POST['name'] email = … -
Django - How to improve performance when model contains a large JSONField?
I am working on trying to figure out how to enhance performance when filtering on a queryset that has a JSONField with large data (thousands of lines). Even when querying and returning an estimated 100 objects, the return is extremely slow. 10-20 seconds. I have come to realize that the issue is the JSONfield, and the fact that large datasets are being stored in this field. I was reading about Djangos .only() and .defer() methods, because I don't need any data in this JSONField, but the performance seems to be the exact same without using these methods. I am just looking for some guidance on how to improve some performance here. -
Getting NaN from pandas DataFrame to go into PostgreSQL via Django
Parsing CSV files that have lots of blanks in float fields which pandas is treating as NaN. Using Django as the backend, I'm trying to import these CSV files into PostgreSQL. The error I get when it goes to do this import is: [celery] The above exception was the direct cause of the following exception: [celery] [celery] Traceback (most recent call last): [celery] File "/opt/pysetup/.venv/lib/python3.9/site-packages/celery/app/trace.py", line 451, in trace_task [celery] R = retval = fun(*args, **kwargs) [celery] File "/opt/pysetup/.venv/lib/python3.9/site-packages/celery/app/trace.py", line 734, in __protected_call__ [celery] return self.run(*args, **kwargs) [celery] File "/app/src/surveys/tasks.py", line 156, in create_model [celery] create_db_table(model, df, db ) [celery] File "/app/src/surveys/tasks.py", line 132, in create_db_table [celery] cursor.execute(statement) [celery] File "/opt/pysetup/.venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 99, in execute [celery] return super().execute(sql, params) [celery] File "/opt/pysetup/.venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 67, in execute [celery] return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) [celery] File "/opt/pysetup/.venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers [celery] return executor(sql, params, many, context) [celery] File "/opt/pysetup/.venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 85, in _execute [celery] return self.cursor.execute(sql, params) [celery] File "/opt/pysetup/.venv/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__ [celery] raise dj_exc_value.with_traceback(traceback) from exc_value [celery] File "/opt/pysetup/.venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 83, in _execute [celery] return self.cursor.execute(sql) [celery] django.db.utils.ProgrammingError: column "nan" does not exist [celery] LINE 1: ...609000.0,609000.0,750000.0,750000.0,1200000.0,0.0,nan,nan,na... [celery] ^ I can resolve the error by doing something like … -
Warning - Certain functionality requires requests_html, which is not installed
when I run my django server everything works fine. However right before the normal prompt that comes from running the server, I get this message Warning - Certain functionality requires requests_html, which is not installed. Install using: pip install requests_html After installation, you may have to restart your Python session. Warning - Certain functionality requires requests_html, which is not installed. Install using: pip install requests_html After installation, you may have to restart your Python session. And then my django server goes on and runs fine. I'm worried that when I deploy my website this error will be a problem. Btw I know where this is coming from. I'm using yahoo_fin and requests_html is a dependency, however I'm not using and won't use the yahoo_fin methods that require this dependency, so I guess what I'm asking is for a way to ignore this random Warning. I've tried installing the requests_html library but I still get the same error, even after I restart my Python session like the message says. -
Django can not access the url specified throwing Not found 404
I'm getting Not Found: 404 error when trying to access http://127.0.0.1:8000/notes/ or http://127.0.0.1:8000/notes. My server is running and I can access the http://127.0.0.1:8000/admin but not the notes page. The app is registered in INSTALLED_APPS as well as its named Notes. Im using Python 3.9 and Django 4.2.2 Notes\urls.py from django.urls import path from . import views urlpatterns = [ path('notes/', views.notes_initiator, name='notes'), ] Notes\views.py from django.shortcuts import render from django.http import HttpResponse def notes_initiator(request): return HttpResponse("Hello, world. You're at the notes index.") Project\urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('notes/', include('Notes.urls')), path('admin/', admin.site.urls), ] I looked at similar problems with Django Not Found errors but they don't have solution that would work for me. I want to see the message "Hello, world. You're at the notes index." when accessing http://127.0.0.1:8000/notes/ -
Django Template Error: KeyError: "'test'=='test'" (string == string)
This one has even stumped Chat GPT who thinks there is nothing wrong with my code. I will slowly dissect my code till I get to the bottom of what is happening but given how bizarre it is, I wanted to document it here. I am building using Django and have a Django template. The main template calls a second template and it's on that second template the issue is happening: {% include "kb/select_file_dialog.html" %} {% if 'test'=='test' %} <script> var dialog = document.getElementById('my_modal_2'); dialog.showModal(); </script> This gives me the error: KeyError: "'test'=='test'" I have no idea why it thinks it's working with a dictionary. Without the problematic line {% if 'test'=='test' %} the code runs fine. -
Django + svelte + ngrok: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote
I am working on Django + Svelte platform and each one of them is hosted on the local server the local hosts work fine with no errors when I tried to use ngrok tunnels to be able to allow my friends to test the platform I got this error Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://452c-102-159-49-36.ngrok-free.app/api/courses/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200 this is the API call from the svelte component: async function fetchCourseOptions() { try { const response = await fetch( "https://452c-102-159-49-36.ngrok-free.app/api/courses/" ); const data = await response.json(); courseSelected = true; return data.courses; } catch (error) { console.error("Error while fetching course options:", error); return []; } } this is the tunnels config in ngrok tunnels: django: proto: http addr: 127.0.0.1:8000 svelte: proto: http addr: 5173 and these are the domains: Forwarding https://25fc-102-159-49-36.ngrok-free.app -> http://localhost:5173 Forwarding https://452c-102-159-49-36.ngrok-free.app -> http://127.0.0.1:8000 I tried adding the addresses to the cors allowed origins and allowed hosts in Django settings.py ALLOWED_HOSTS = ["452c-102-159-49-36.ngrok-free.app", "localhost"] # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "profikapp.apps.ProfikappConfig", "smart_selects", "api.apps.ApiConfig", "corsheaders", ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "corsheaders.middleware.CorsMiddleware", ] ROOT_URLCONF = "profik.urls" … -
cannot import name '..' from partially initialized module '..models' (most likely due to a circular import)
Error while running the program _call_with_frames_removed File "E:\python\khayyam\khayyam.ir\product\models.py", line 5, in from member.models import Receive File "E:\python\khayyam\khayyam.ir\member\models.py", line 6, in from product.models import Factor, Product ImportError: cannot import name 'Factor' from partially initialized module 'product.models' (most likely due to a circular import) (E:\python\khayyam\khayyam.ir\product\models.py) ---------------------------product/models.py----------------------------- from levelgroup.models import Sath from member.models import Receive from term.models import Term from user.models import Profile from django.db.models import Sum class Product(models.Model): barcode = models.CharField(max_length=150, verbose_name='بارکد', default='---') name = models.CharField(max_length=150, verbose_name='نام کالا/خدمات') class Factor(models.Model): student = models.ForeignKey(Profile, on_delete=models.CASCADE, verbose_name='زبان آموز', null=True) term = models.ForeignKey(Term, on_delete=models.CASCADE, verbose_name='ترم', null=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name='محصول') count = models.IntegerField(verbose_name='تعداد', default='1') price = models.IntegerField(verbose_name='مبلغ') discount = models.IntegerField(verbose_name='تخفیف', null=True, default='0') maleiat = models.IntegerField(verbose_name='مالیات', null=True, default='0') created_at = models.DateTimeField(auto_now_add=True, null=True) description = models.TextField(verbose_name='توضیحات', null=True) def get_pardakhti(self): receive = Receive.objects.filter(factor=self.id, student=self.student).aggregate(Sum('price')) return receive['price__sum'] ---------------------------member/models.py----------------------------- from django.db import models from django.shortcuts import get_object_or_404 from django.db.models import Sum from classes.models import Classes, Grades from product.models import Factor, Product from term.models import Term form user.models import Profile, Branch class Receive(models.Model): student = models.ForeignKey(Profile, on_delete=models.CASCADE, verbose_name='زبان آموز', related_name='receives') leson = models.ForeignKey(Classes, on_delete=models.CASCADE, verbose_name='درس', null=True, blank=True) factor = models.ForeignKey(Factor, on_delete=models.CASCADE, verbose_name='فاکتور', null=True, blank=True) term = models.ForeignKey(Term, on_delete=models.CASCADE, verbose_name='سال') -
Problems with Django login authentication in my code. It's always going to the else condition and outputs 'You have incorrect Username or password'
I am facing an issue with the user authentication implementation in my Django application. Even when providing the correct username and password, the system consistently displays an error message stating "You have incorrect Username or password." I have thoroughly followed the authentication procedures, ensured the correct user model. please help me to solve this problem. This is view.py file from django.shortcuts import render,HttpResponse,redirect from .models import registration from django.contrib.auth import authenticate,login def home(request): return render(request,'home.html') def log_in(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, check) return redirect('home') else: return HttpResponse("You have incorrect Username or password") return render(request, 'log_in.html') def sign_up(request): if request.method == 'POST': name = request.POST.get('fullname') username = request.POST.get('username') email = request.POST.get('email') pass1 = request.POST.get('password') pass2 = request.POST.get('confirm_password') if pass1 != pass2: return HttpResponse("Password not matched") else: db = registration() db.Name = name db.username = username db.Email = email db.Password = pass1 db.save() return redirect('log_in') return render(request,'sign_up.html') This is models.py for sqlite database from django.db import models class registration(models.Model): Name = models.CharField(max_length=100) username = models.CharField(max_length=100) Email = models.CharField(max_length=100) Password = models.CharField(max_length=100) -
How to create a submit button with multiple options that can alter a csv file and post it back
I'm trying to create a submit button that lists files for a particular user that has actions associated to each drop down. I can download the csv file and alter it, save it as a new file but I can not seem to repost the file and add it to the list. I am stuck how to add the newFile.csv to the request.method == 'POST': models.py class Document(models.Model): user = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE) description = models.CharField(max_length=255, blank=False) document = models.FileField(upload_to=fileLocation) uploaded_at = models.DateTimeField(auto_now_add=True) forms.py class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ('description', 'document') html {% for file in files %} <form id="file" action= "{% url 'process' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <select name="selectedOption"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <input type="submit" value="Submit" class="btn btn-sm"> </form> {% endfor %} views.py def process(request): selected_option = request.POST.get('selectedOption') form = DocumentForm(request.POST, request.FILES) current_client = request.user files = Document.objects.filter(user=current_client) fileResponse = s3_client.get_object(Bucket=settings.AWS_STORAGE_BUCKET_NAME, Key=document) df = pd.read_csv(fileResponse.get("Body"), encoding='utf-8', dtype=str) df.to_csv('temp/temp.csv', index=False, header=True, encoding='utf-8-sig') newFile = 'temp/temp.csv' if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() return redirect('/filelist') else: form = DocumentForm() return render(request, 'accounts/filelist.html', {'selected_option':selected_option, 'form': form, 'files': files}) -
Django - How to write a custom permission mixin?
There's a view that gets a parameter. class MyView(View): def get(self, request, pk): # ... ^^ To decide whether the user is allowed or not, that parameter is needed. Is it possible to write a custom permission mixin to take care of it? -
Django project deployment on Versel
I was deploying my Django Project where I got error 500, how can I resolve this error and is there any better platform to deploy Django project. I expected that project would be easily deployed but it gave error 500 on vercel. -
relation "account_emailaddress" does not exist
I am trying to make a Google Sign In for my app but when I try to migrate it gives me the error: **django.db.utils.ProgrammingError: relation "account_emailaddress" does not exist ** Here is My Settings.py: ``INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'rest_framework', 'rest_framework_simplejwt', 'videos', 'embed_video', 'users', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ]` `SOCIALACCOUNT_PROVIDERS = { 'google': { "SCOPE":[ 'profile', 'email' ], 'AUTH_PARAMS': {'access_type': 'online'} } }` `TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR.joinpath('templates') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', # Required by allauth template tags "django.core.context_processors.request", # allauth specific context processors "allauth.account.context_processors.account", "allauth.socialaccount.context_processors.socialaccount", ], }, }, ]` `AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend' )` `LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/' I saw this and tried doing this : I figured out what the problem was. the allauth uses account app which doesn't support migrations as yet. Initially I had run python manage.py migrate allauth.socialaccount python manage.py migrate allauth.socialaccount.providers.facebook Along with this we need to run the syncdb to complete the puzzle. But it did not work and it gave me another error. CommandError: No installed app with label 'allauth.socialaccount.providers.google'. Did you mean 'google'? this error so when I do that it … -
Python - Cannot Reach Module With Relative Import
I have a file called views.py that imports a class from another file stored in the same folder. The other file is called models.py and the needed class is called Docgen. I'm using the following code to import. from .models import Docgen But I keep getting the following error. ImportError: attempted relative import with no known parent package No error is shown when I write the line from .models import Docgen but it still won't work for some reason I can't figure out. -
Google Cloud Storage Authentication Issue with Django using google-auth
I am facing an authentication issue while trying to use Google Cloud Storage with Django. I have set up my Django project to use google-auth library for authentication with other Google APIs, but when I try to use Google Cloud Storage, I get the following error: This library only supports credentials from google-auth-library-python. See https://google-auth.readthedocs.io/en/latest/ for help on authentication with this library. Steps Taken: I have set up my Django project with the necessary configurations, including installing google-auth library. I have defined the GS_CREDENTIALS variable in my Django settings to store the path to the service account JSON file. I am using the storages.backends.gcloud.GoogleCloudStorage storage backend in Django settings to handle media and static files storage on Google Cloud Storage. Django settings.py GS_CREDENTIALS = os.environ.get('GOOGLE_APPLICATION_CREDENTIALS') STATICFILES_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' Expected Behavior: I expect the google-auth library to handle the authentication with Google Cloud Storage, just as it does with other Google APIs in my Django project. Actual Behavior: When trying to use Google Cloud Storage, the mentioned error is raised, indicating that the library only supports credentials from google-auth-library-python, even though I have google-auth installed and working correctly with other APIs. Additional Information: I have verified that google-auth …