Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
no such table Django
I have a problem with Django. I got the Error Message: no such table: tablename. I already defined the model and now I want to safe Data in this model. But it cannot find the table. I hope you can help me. #my models.py class ImageUpload(models.Model): image = models.FileField(upload_to= user_directory_path) camera = models.CharField(max_length=100) ... #my view.py if request.method == 'POST': form = ImageUploadForm(request.POST, request.FILES) if form.is_valid(): image = form.cleaned_data['image'] camera = form.cleaned_data['camera'] uploaded_file = ImageUpload( image=image, camera=camera, ) uploaded_file.save() -
Please enter the correct email and password for a staff account
I created super user using python manage.py createsuperuser and i am sure that is_staff = True, is_superuser = True, is_active = True. I used custom user, here is models.py: from django.db import models from django.contrib.auth.hashers import make_password from django.contrib.auth.models import AbstractUser, Group, Permission, UserManager class CustomUserManager(UserManager): def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self.create_user(email, password, **extra_fields) def _create_user(self, email, password, **extra_fields): email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.password = make_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) class User(AbstractUser): email = models.EmailField(max_length=254, unique=True) username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() # use the custom manager def __str__(self): return self.email why can't login into the admin panal? -
Wagtail hook for richtext editor
I created a wagtail hook for adding a code block from the Richtext editor. The hook is working but I have the problem. The hook supposed to work like as follows, <div class="code"> content line one content line two </div> But when I apply the block from editor , it is applying each line with the code like, <div class="code">content line one </div> <div class="code">content line two </div> This was supposed to be one line, The wagtail editor is applying multiple divs for each of the lines instead of one div for the selected block My hook code is as follows, @hooks.register('register_rich_text_features') def register_py_code_block_feature(features): """ Registering for adding python code block """ feature_name = 'py-code-block' type_ = 'py-code-block' control = { 'type': type_, 'label': 'PY', 'description': 'Python Code Block', # Optionally, we can tell Draftail what element to use when displaying those blocks in the editor. 'element': 'div', 'style': { "display": "block", }, } db_conversion = { 'from_database_format': {'div': BlockElementHandler(type_)}, 'to_database_format': {'block_map': {type_: { 'element': 'div', 'props': { 'class': 'code blog_code language-python' } } } }, } features.register_editor_plugin('draftail', feature_name, draftail_features.BlockFeature(control)) features.register_converter_rule('contentstate', feature_name, db_conversion) features.default_features.append('py-code-block') Can some one point me the right direction -
How to connect local database with .env file?
I have a django docker container. And I have two .env files: one for local and one for production. And I am using Azure for the database service. So if I connect the env file with the Azure database it works. But when I try it the .env file for the local datbase. I get am error. so docker-compose file looks like: version: "3.9" services: app: build: context: . args: - DEV=true ports: - "8000:8000" volumes: - ./Welzijn:/app command: > sh -c "python ./manage.py migrate && python ./manage.py runserver 0:8000" environment: - DEBUG=1 env_file: - ./.env.sample and the local env file looks like: DEBUG=True SECRET_KEY="%@967xvpdnf7go%r#d%lgl^c9ah%!_08l@%x=s4e4&+(u" DATABASE_NAME="zijn" DATABASE_USER="zijn" DATABASE_PASSWORD="password" DATABASE_HOST="127.0.0.1" DATABASE_PORT="" So when I do a:docker-compose up --build I get this error: dwl_backend-app-1 | django.db.utils.OperationalError: could not connect to server: Connection refused dwl_backend-app-1 | Is the server running on host "127.0.0.1" and accepting dwl_backend-app-1 | TCP/IP connections on port 5432? But I also have a production env file: DEBUG=False SECRET_KEY="+)d)&d0^&0xda+s%1o(&r3+24)x#i^bk8p8r)@jl_q2=%usxw=" DATABASE_NAME="zijn" DATABASE_USER="zijn" DATABASE_PASSWORD="85jLGTj{v?s38_Jr" DATABASE_HOST="db-zijn.postgres.database.azure.com" DATABASE_PORT="" And that is working if I do a docker-compose up --build Question: How to connect with the local database with the .env file? -
How to create a REST API with Django and implement SSL, token authentication?
So, I need provide an API endpoint for my app. The one who requests this kinda link /api/thing/?thing_id=abc123 would get a JSON data. I am done with this part but cannot figure it out how make auth token implementation and I think I am mixing terms with SSL. So, it would be really appreciated, if someone explains! -
How does django manual user log in authentication works?
I am learning Django. I defined a database then signup and login views and templates accordingly. signup works fine but log in not working. Actually it does not do anything while entering email and password. Would you please help me? -
Django: Trouble importing updated form
learning Django for the first time and I'm getting my first error here. Saying it "cannot import 'UserRegisterForm' from 'users.forms'". I'm following a tutorial and I haven't skipped any steps. Not too sure what to try next...thanks for any suggestions. Tutorial Video (33:15): https://www.youtube.com/watch?v=q4jPR-M0TAQ&t=1959s views.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('blog-home') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] Folder Directory -
Heroku H13 desc="Connection closed without response" for file (pdf) upload
I have a use case where the user can upload a pdf book and I process a summary for that book. For a 250-page book, for example, the summary process takes around 2-3 minutes and it works great on local. However, in Heroku, for that 250-page book, I get the error below. When I try the 20-page book, it's okay. I run Heroku using professional dynos. I have 3 dynos. I have also shared my views on how files are processed. There you will see libraries that I use as well. I read a bit that Heroku has a hard cap of 30 seconds, ie if 30 seconds passed and the summary is not done, boom, error. Is that true? How can I avoid that? Thank you in advance for your help. error: error in server: 2023-08-15T09:12:55.850512+00:00 app[web.1]: [2023-08-15 09:12:55 +0000] [98] [INFO] Worker exiting (pid: 98) 2023-08-15T09:12:55.848850+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=POST path="/file_processing/upload/" host=someendpoint request_id=b8045e24-a33f-4446-869e-e22a27fbef32 fwd="109.245.202.232,141.101.96.16" dyno=web.1 connect=0ms service=30471ms status=503 bytes=0 protocol=https Procfile web: gunicorn backend.wsgi views.py from django.http import JsonResponse from rest_framework.views import APIView from rest_framework.parsers import MultiPartParser, FormParser from .serializers import DocumentSerializer from docx import Document as DocxDocument from pdfminer.high_level import extract_text import pytesseract … -
Trying to send HTML form field value in JSON POST call to API but getting syntax err showing that whole HTML page code is being sent as JSON
I am building a Single Page App using Django and JavaScript. In Django app in the views.py I have the following function acting as add-post API endpoint: def post_add(request): ''' API endpoint for creating a new post ''' # save data submitted by the user if request.method != "POST": return JsonResponse({"error": "POST request required."}, status=400) else: form = PostForm(request.POST) # check if form is valid server-side if form.is_valid(): post = form.save(commit=False) # save without commit as we have to associate some variables that were not in the form post.author = request.user post.save() return JsonResponse({"message": "Post added successfully."}, status=201) else: # return JsonResponse({"message": "Errors in the form."}, status=400) In JavaScript I have added event listener after the whole document has been loaded and within it an event listener on the submit button that removes the default submit action and triggers my add_post() function: document.addEventListener('DOMContentLoaded', function() { // add function call on add post form submission document.querySelector("#create-post").addEventListener('submit', function(event) { event.preventDefault(); // cancels default form submission action on clicking the submit button in the form add_post(); }); }); And here is the add_post() function in JavaScript that sends data for the new post (1 field in the form) and calls the API endpoint: … -
How can I see the body of the request that Django's test client makes
I am writing automated tests in Django and started writing tests for an API endpoint that supports the put method. I am making my put request like so: response = self.client.put(path, data=json.dumps({"key": "value"}) print(response.request) As you see, I'm trying to see the details of the request that is being sent. I am particularly interested in seeing what goes into the body of the request. But the object returned by response.request is a dictionary that does not contain the "body" key or anything similar. I think this is a weird feature for the testing framework not to have, seeing as how it could come in handy in many different scenarios. Is there any way I can access the body of the request that I have not yet discovered? Or does the feature really not exist? -
Performance issues with gunicorn + gevent Django
I'm encountering performance issues with gunicorn+genevent that is consuming a significant amount of RAM after conducting a high-load test. Even when I return an empty view with just a "hello world" message, the RAM usage continues to remain high, causing other requests to get stuck. I suspect that there might be a cache-related issue causing this behavior. Is there a way for gunicorn to clean up its cache automatically to return resources to normal levels after a high-load situation? I've configured gunicorn to use the formula NUM_WORKERS = NUM_CORES * 2 and performed tests with both 1 worker and more workers, but the results were the same. Here's the command I'm using to run gunicorn: gunicorn config.wsgi:application \ --workers $NUM_WORKERS \ --timeout $TIMEOUT \ --keep-alive 2 \ --bind 0.0.0.0:8000 \ --log-level=debug \ --log-file=- \ -k gevent Could this issue possibly be unrelated to gunicorn? If so, how can I go about testing for memory leaks? Your assistance is greatly appreciated. -
Why are emails sent successfully from my Django project using the Gmail SMTP server on localhost but not on AWS?
I use the Gmail SMTP server for my Django project, which I have deployed on AWS. The emails are sent and work locally on localhost, but they are not working from AWS. I have 2 step verification enabled on gmail and generated app password wich i use in two different .env files, one locally and one in the cloud. I use the same password (if that matters). Additionally, I have added port 587 to the inbound rules of the Security Groups but still not working. enter image description here -
dj-rest-auth TemplateResponseMixin requires either a definition of 'template_name' or an implementation of 'get_template_names()'
I'm using dj_rest_auth for authentication and when I click on the verify email link, this error comes out How do I fix this error? -
Dockerise django app for production, failed to solve: process "/bin/sh -c pip install
I try to dockerise a django container for production. So I have my dockerfile: FROM python:3.8-alpine ENV PATH="/scripts:${PATH}" COPY ./requirements.txt /requirements.txt RUN apk add --update --no-cache --virtual .tmp gcc libc-dev linux-headers RUN pip install -r /requirements.txt RUN apk del .tmp RUN mkdir /app COPY ./Welzijn /app WORKDIR /app COPY ./scripts /scripts RUN chmod +x /scripts/* RUN mkdir -p /vol/web/media RUN mkdir -p /vol/web/static RUN adduser -D user RUN chown -R user:user /vol RUN chmod -R 755 /vol/web USER user CMD ["entrypoint.sh"] and the docker-compose file: version: "3.9" services: app: build: context: . ports: - "8000:8000" volumes: - ./Welzijn:/app command: > sh -c "python ./manage.py migrate && python ./manage.py runserver 0:8000" environment: - DEBUG=1 env_file: - ./.env and requirements.txt file: Django>=4.0.4 uWSGI>=2.0.18,<2.1 djangorestframework>=3.13.1 psycopg2>=2.9.3 drf-spectacular>=0.22.1 Pillow>=9.1.0 drf-yasg==1.20.0 django-cors-headers==3.10.1 django-dotenv But when I execute docker-compose up --build I get this errors: If you prefer to avoid building psycopg2 from source, please install the PyPI 3.686 'psycopg2-binary' package instead. 3.686 3.686 For further information please check the 'doc/src/install.rst' file (also at 3.686 <https://www.psycopg.org/docs/install.html>). 3.686 3.686 [end of output] 3.686 3.686 note: This error originates from a subprocess, and is likely not a problem with pip. 3.690 error: metadata-generation-failed 3.690 3.690 × Encountered error … -
django.db.utils.IntegrityError: UNIQUE constraint failed: accounts_profile.user_id
I'm having issues with registering a user in my project. I have a custom serializer that inherits from the RegisterView of dj_rest_auth. My code is: views.py class ProfileDetail(APIView): def get_object(self, pk): try: return Profile.objects.get(pk=pk) except Profile.DoesNotExist: raise Http404 def get(self, request, pk, format=None): profile = self.get_object(pk) serializer = ProfileSerializer(profile) return Response(serializer.data) class CustomRegisterView(RegisterView): serializer_class = CustomRegisterSerializer serializer.py class CustomRegisterSerializer(RegisterSerializer): user_type = serializers.ChoiceField(choices=[('seeker', 'Seeker'), ('recruiter', 'Recruiter')]) class Meta: model = User fields = "__all__" def get_cleaned_data(self): data = super().get_cleaned_data() data['user_type'] = self.validated_data.get('user_type', '') return data def save(self, request): user = super().save(request) user_type = self.validated_data.get('user_type') Profile.objects.create(user=user, user_type=user_type) return user models.py class Profile(models.Model): class Type(models.TextChoices): seeker = "Seeker" recruiter = "Recruiter" base_type = Type.seeker user = models.OneToOneField(User, on_delete=models.CASCADE) user_type = models.CharField(choices=Type.choices, default=base_type, max_length=20) I expect the code to return a 200 after I perform a POST request. -
Protection from cross-site-scripting Django Rest Framework
I am creating API for forum web-site with DRF and want to protect it from XSS. For example if someone sends a request with a text included in html tags(button, form, script etc.) it is saved in database. I wan't to protect it somehow. I heard that I can do it through serailizer escape method or I can solve the problem on the middleware level by checking if there are any prohibited tags and if so, raise an error or just parse the row text from html and save it. Also in some ednpoints I do really need to save data (including html) in the TextField , as I want my frontend client to be allowed to format text with HTML (basic markup), but in these case the idea of special middleware does not seem appropriate because it won't allow to send request with HTML text. Or I just should create a middleware to check if there are for example form or button tags and in this way raise error (if it is something like HTML lists, headlines, span tags don't raise error). What solution works better? Or are there any other ways? Maybe it is up to frontend developer … -
Use threading.Event() to send SSE event in Django project after receiving message from RabbitMQ
I have a Django map application that displays real-time markers with either red or green color based on the marker's state, which is updated when a new message arrives. Currently, I'm periodically updating the page every 3 seconds, but I want to achieve a more efficient approach by updating the page only after a change in the database. I have this sse function in my views.py: from threading import Event marker_update_event = Event() marker_update_event_list = {0: marker_update_event} #print("Marker update event created", marker_update_event_list[0]) def sse(request): def event_stream(): while True: marker_data = [] all_markers = Marker.objects.all() for marker in all_markers: latest_message = marker.get_latest_message() marker_data.append({ 'name': marker.get_name(), 'latitude': marker.get_latitude(), 'longitude': marker.get_longitude(), 'error_type': latest_message.get_error_type() if latest_message else 'No error type', 'message': latest_message.get_message() if latest_message else 'No messages', 'state': marker.get_state(), 'id': marker.id, }) if marker_update_event_list[0].is_set(): print('marker_update_event is set') yield 'event: marker_data\ndata: %s\n\n' % json.dumps(marker_data) marker_update_event_list[0].clear() marker_update_event_list[0].wait() return StreamingHttpResponse(event_stream(), content_type="text/event-stream") I'm also consuming messages from RabbitMQ using a consumer.py script at the root directory: import json import pika import django # Django environment setup from markers.models import Message from markers.views import marker_update_event_list connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() channel.queue_declare(queue='messages') def callback(ch, method, properties, body): data = json.loads(body) if properties.content_type == 'message_created': message = Message.objects.create(error_type=data['error_type'], message=data['message'], date=data['date'], … -
When load the data error rise Object of type Item is not JSON serializable
Model.py class Item(models.Model): status_type = ( ('a','Active'), ('d','Deactive') ) code = models.CharField(max_length=100, null=True, blank=True, unique=True) name = models.CharField(max_length=100) status = models.CharField(max_length=1, choices=status_type, default = 'a') create_at = models.DateField(auto_now_add=True) update_at = models.DateField(auto_now=True) create_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.name class PriceMaster(models.Model): status_type = ( ('a','Active'), ('d','Deactive') ) items = models.ForeignKey(Item, on_delete=models.CASCADE) gst = models.ForeignKey(Gst, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) status = models.CharField(max_length=1, choices=status_type, default = 'a') create_at = models.DateField(auto_now_add=True) update_at = models.DateField(auto_now=True) create_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return str(self.items) @property def cgst_unround(self): if not hasattr(self,'_cgst'): self._cgst = self.price * self.gst.gst / 100 return round(self._cgst,2) @property def per_gst(self): self.per = self.gst.gst / 2 return self.per @property def cgst(self): return round((self.cgst_unround / 2),2) class TempCalculate(models.Model): quantity = models.IntegerField() items_price = models.ForeignKey(PriceMaster,on_delete=models.CASCADE) create_at = models.DateField(auto_now_add=True) create_by = models.ForeignKey(User, on_delete=models.CASCADE) @property def item_price(self): self.price = self.items_price.price return self.price ** I'm trying to access item name ** @property def item_name(self): self.name = self.items_price.items return self.name Serializer.py I'm trying access item_name field class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = '__all__' class TempCalSerializer(serializers.ModelSerializer): class Meta: model = TempCalculate fields = ['id','item_name','quantity','item_price'] api/view.py @api_view(['GET']) def TempItem(request): queryset = TempCalculate.objects.all() serializer_class = TempCalSerializer(queryset, many=True) return Response(serializer_class.data) I'm trying access the item name but can't because when … -
disable default Django models and migrations
I created a Django project which is supposed to be a small service and it has nothing to do with User and other Django default models. How can I remove them completely? (I need Django admin) When I comment django.contrib.auth in INSTALEDD_APPS I recieve this error: RuntimeError: Model class django.contrib.auth.models.Permission doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. -
cannot import name 'UserSerializer' from 'serializers'
I want to wright api whith django.I installed serializers : pip install serializers and I import UserSerializer in view.py: from serializers import UserSerializer from rest_framework import serializers but When I want to use serializer , I give an error: cannot import name 'UserSerializer' from 'serializers' -
Extra field in custom registration in DRF won't save
I created a custom serializer that extends dj_rest_auth's RegisterSerializer, added the extra user_type field, overrode the get_cleaned_data method to include the user_type in the cleaned data then configured the custom registration serializer used for registration. Here's my code: class CustomRegisterSerializer(RegisterSerializer): user_type = serializers.ChoiceField(choices=[('seeker', 'Seeker'), ('recruiter', 'Recruiter')]) class Meta: model = User fields = "__all__" def get_cleaned_data(self): data = super().get_cleaned_data() data['user_type'] = self.validated_data.get('user_type', '') return data class Profile(models.Model): class Type(models.TextChoices): seeker = "Seeker" recruiter = "Recruiter" base_type = Type.seeker user = models.OneToOneField(User, on_delete=models.CASCADE) user_type = models.CharField(choices=Type.choices, default=base_type, max_length=20) class Meta: verbose_name = "Profile" verbose_name_plural = "Profiles" def __str__(self): return self.user.username class CustomRegisterView(RegisterView): serializer_class = CustomRegisterSerializer -
Pytest tests only one case with @pytest.mark.parametrize
I defined UserFactory class in tests/factories.py as shown below following the doc. *I use pytest-django and pytest-factoryboy in Django: # "tests/factories.py" import factory from django.contrib.auth.models import User class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User And, I defined test_user_instance() with @pytest.mark.parametrize() to test 4 users as shown below: # "tests/test_ex1.py" import pytest from django.contrib.auth.models import User @pytest.mark.parametrize( "username, email", { ("John", "test@test.com"), # Here ("John", "test@test.com"), # Here ("John", "test@test.com"), # Here ("John", "test@test.com") # Here } ) def test_user_instance( db, user_factory, username, email ): user_factory( username=username, email=email ) item = User.objects.all().count() assert item == True But, only one user was tested as shown below: $ pytest -q . [100%] 1 passed in 0.65s So, how can I test 4 tests? -
Profile not creating when creating a User with Django
I'm using DRF for my project and I need help in automatically creating a Profile instance for a User model when a User is created. My signals is: from django.db.models.signals import post_save from django.conf import settings from django.contrib.auth import get_user_model from .models import Profile User = get_user_model() def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) post_save.connect(create_user_profile, sender=User) -
Django With Clean Architecture
I'm trying to build a python application using Clean Architecture principles. I already have the following structure: app/ ├── src │ ├── dependencies │ │ ├── dependencies.py │ │ └── __init__.py │ ├── infrastructure │ │ └── ui │ │ ├── __init__.py │ │ ├── interfaces │ │ │ ├── __init__.py │ │ │ └── ui.py │ │ ├── desktop │ │ │ ├── __init__.py │ │ │ └── tkinter_ui.py │ │ └── web │ │ ├── flask_ui │ │ │ ├── constants │ │ │ │ ├── constants.py │ │ │ │ └── __init__.py │ │ │ ├── endpoints │ │ │ │ ├── endpoints.py │ │ │ │ └── __init__.py │ │ │ ├── flask_ui.py │ │ │ └── __init__.py │ │ └── __init__.py │ ├── __init__.py │ └── main.py Makefile And it works fine for both Tkinter and Flask. Now I'm considering adding django to my project, so I thought my structure would be something like this: app/ ├── src │ ├── dependencies │ │ ├── dependencies.py │ │ └── __init__.py │ ├── infrastructure │ │ └── ui │ │ ├── __init__.py │ │ ├── interfaces │ │ │ ├── __init__.py │ │ │ └── ui.py │ … -
Django: Create and Update seperate objects
In Django models, I aim to ensure that when I create an object from one class, the corresponding object is created in another class. Furthermore, certain fields should be automatically inherited. Here's an example: `class Model1(models.Model): Malfunction = models.CharField(max_length=255, null=True) def __str__(self): return self.Malfunction class Model2(models.Model): sit_id = models.AutoField(primary_key=True) given_Malfunctions = models.ManyToManyField(Model1, blank=True) dynamik_2 = models.CharField(max_length=255, default=None, blank=True) def __str__(self): return f"[{self.sit_id:02d}]" class Model3(models.Model): connection_to_model2 = models.ForeignKey(Model2, on_delete=models.CASCADE, default=None) dynamik_3 = models.CharField(max_length=255, default=None, blank=True) ` Model3 object should be created every time a Model2 object got created. And the fields from dynamik_2 should be automatically updated to dynamik_3. Should i define the signals or functions in model 3? I encountered an issue with "post_save" since I couldn't establish the connection between related objects.