Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF nested serializer issue on create
I have a User model and a phone model the phone model has a foreign key relation with the user model i read the docs on NestedSerializers and tried it to no avail. this is my serializers.py file class PhoneSerializer(serializers.ModelSerializer): # opt = serializers.IntegerField(read_only=True) class Meta: model = Phone fields = ['phone'] class RegisterSerializerBase(serializers.ModelSerializer): phone = PhoneSerializer(many=False, allow_null=True) # otp = PhoneSerializer(many=True, read_only=True) email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())]) password = serializers.CharField( write_only=True, required=True, validators=[validate_password]) password2 = serializers.CharField(write_only=True, required=True) class Meta: model = User fields = ('email', 'firstname', 'lastname', 'password', 'password2', 'phone',) extra_kwargs = {'password': {'write_only': True}, 'password2': {'write_only': True}, 'firstname': {'required': True}, 'lastname': {'required': True}, } def validate(self, attrs): if attrs['password'] != attrs['password2']: raise serializers.ValidationError( {"password": "Password fields didn't match."}) return attrs def create(self, validated_data): phones = validated_data.pop('phone') instance = User.objects.create( email=validated_data['email'], firstname=validated_data['firstname'], lastname=validated_data['lastname'], is_active='True', type=User.TYPES.OWNER, ) instance.set_password(validated_data['password']) for phone in phones: Phone.objects.create(instance=instance, **phone) return instance when I go the the Browsable API and create a user with the credentials an error comes up saying django.db.models.manager.BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method() argument after ** must be a mapping, not str -
Django Postgres PostGISSpatialRefSys matching query does not exist
I am implementing location feature in my Django project with Postgresql as my database, so for that I install Postgres and then install PostGis extension I have the following filter query executed in my views.py from django.contrib.gis.measure import D from django.contrib.gis.db.models.functions import Distance Lesson.objects.filter(venue_coord__distance_gte=(request.user.location_coord, D(km=int(km))) Executing the above filter results in error: PostGISSpatialRefSys matching query does not exist In models.py I have venue_coord & location_coord that stores PointField as follows venue_coord = models.PointField(verbose_name=_(" Venue Co-ord"), blank=True, null=True) location_coord = models.PointField(verbose_name=_(" User Co-ord"), blank=True, null=True) Can anyone suggest why postgis is giving error all of a sudden. -
How to print the correct time from the datetime input in the form
I am getting date and time input from form through datetimepicker in Django. Because the current template outputs {{ form }} , you need to set the format of the time to be output to the template in models.py. I entered 3 PM, but 06:00 is stored in the db, and the time obtained by the get_time function is also 06:00. What should I set to display 15:00 in the template? def get_time(self): return self.date.strftime('%H:%M') @property def get_html_url(self): url = reverse('dataroom:training_edit', args=(self.id,)) return f'<div class="training-title" data-toggle="modal" data-target="#training_{self.id}">{self.get_time()}: {self.topic}' \ f'<a href="{url}" style="color:black;">&nbsp;&nbsp;<span style="color:red;">Edit</span></a></div>' -
Image is not loading from django rest framework in react
i am beginner in drf. i want to load image from django rest framework to react but I does not show image in react. views.py def PostView(request): parser_classes = (MultiPartParser, FormParser,JSONParser) if request.method=="GET": post = Post.objects.all() post_serializer = PostSerializer(post, many=True) return Response(post_serializer.data) Seriliazer.py class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = "__all__" settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Axios call async function getPost() { await axios .get( "http://127.0.0.1:8000/api/post/" ) .then((res) => { console.log(res.data); setPost(res.data); }); } and react code is <div className="card mb-3" key={res.id}> <img className="card-img-top" src={`http://127.0.0.1:8000${res.image}`} alt="post image" /> <div className="card-body"> <h4>{res.title}</h4> <p className="card-text">{res.image}</p> </div> following is my API response following is my API response and browser error error -
django.core.exceptions.validationerror value true or false during migration
I am running into this error while trying to migrate a table. Once the error came, I has been persistent. KINDLY ASSIST. -
Django index unique on where
I have a class, which represents photos attached to a person. class PersonPhoto(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) photo = models.FileField(upload_to='photos/', blank=True, null=True) person = models.ForeignKey( Person, related_name="photos", on_delete=models.CASCADE ) main = models.BooleanField(default=False) I want to make sure that for every person there could be only one main photo. In pure SQL i would use something like create unique index on photo (person_id, main) where main = true; You can play with it here http://sqlfiddle.com/#!15/34dfe/4 How to express such constraint in django model? I am using django 4.0.1 -
Adding the member in django REST framework serializer
I am using serializer of Django REST framework I have this Serializer and class. This serializes data and passes as json. class SpotSerializer(serializers.Serializer): spot_id = serializers.IntegerField() another_id = serializers.IntegerField() class Spot: def __init__(self, spot_id,another_id) self.spot_id = spot_id self.another_id = another_id Now I want to add the another variable not the class member such as class SpotSerializer(serializers.Serializer): spot_id = serializers.IntegerField() another_id = serializers.IntegerField() another_name = Another.objects.get(id=another_id).name // adding This code doesn't show error but no another_name field is appeared in json. So is it possible? -
Django : How to redirect any post request on some views
I have a project setup on server(Cloud) which talks to another server(like chat system), at both sides we make API calls for servers(Cloud) to talk to each other we can call them Server#1 and Server#2.Now I want to setup this project on local(ngrok , localtunnel), so how do I redirect post requests by Server#1 on some views that I get on Server#2 to local web server or public domain of ngrok or localtunnel. I can use requests module to make API calls to public ngrok domain but I'll have to write this in many views.Is there any alternative or better way to handle this? -
Django JWT Token json response
I'm trying to do jwt token auth on django, when i try on postman im getting json response as ss 1 but on the frontend site im gettin html page. why is that, is there anyone to know fix this. thanks. postman-response -
Django AJAX call to refresh table data instead of using "append"
I want to refresh the data in my table every 10 seconds, without reloading the whole page again and again So I wrote some code in AJAX to append the new data But I want to refresh the data in the existing table and am not sure how to do that My current HTML code is just appending the whole table again and again, but I just want to refresh the data in a single table <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>temp1</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1>Hello there</h1> <h1>{{info_data}}</h1> <table id="_appendHere" class="table table-striped table-condensed"> <tr> <th>Username</th> <th>Email</th> <th>Gender</th> </tr> {% for item in info_data %} <tr><td>{{item.username}} - {{item.email}} - {{item.gender}}</td></tr> {% endfor %} </table> </body> <script> var append_increment = 0; setInterval(function() { $.ajax({ type: "GET", url: {% url 'App1:tempPage' %}, // URL to your view that serves new info data: {'append_increment': append_increment} }) .done(function(response) { $('#_appendHere').append(response); append_increment += 10; }); }, 10000) </script> </html> Any help would be highly appreciated!! Thanks!! -
How to implement authentication with Azure Directory when using React Frontend and Django REST API backend?
I'm just now learning Django REST Framework. However, I've been put on a project in charge of the DRF API. The project has a React frontend connected to a DRF API backend. I've made basic JWT Auth on the DRF API side before. However, we've been tasked with using Azure Directory for authentication. My question is how would this be setup? Would the Azure Directory auth be implemented on the frontend? What should be passed back and forth from the DRF API? I'm just a little confused reading the documentation and what needs to be stored for login and sessions on the API vs the frontend. Any information would be helpful, whether it would be specifics or the general apparatus. -
Django-error OSError: dlopen() failed to load a library: cairo / cairo-2 / cairo-gobject-2
When I do manage.py makemigrations An error like this occurs PS C:\Users\User\PycharmProject\onlineshop-master> python .\manage.py makemigrations Traceback (most recent call last): File "C:\Users\User\PycharmProject\onlineshop-master\manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\User\PycharmProject\onlineshop\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\User\PycharmProject\onlineshop\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\User\PycharmProject\onlineshop\venv\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\User\PycharmProject\onlineshop\venv\lib\site-packages\django\core\management\base.py", line 350, in execute self.check() File "C:\Users\User\PycharmProject\onlineshop\venv\lib\site-packages\django\core\management\base.py", line 376, in check all_issues = self._run_checks( File "C:\Users\User\PycharmProject\onlineshop\venv\lib\site-packages\django\core\management\base.py", line 366, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\User\PycharmProject\onlineshop\venv\lib\site-packages\django\core\checks\registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\User\PycharmProject\onlineshop\venv\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "C:\Users\User\PycharmProject\onlineshop\venv\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "C:\Users\User\PycharmProject\onlineshop\venv\lib\site-packages\django\utils\functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\User\PycharmProject\onlineshop\venv\lib\site-packages\django\urls\resolvers.py", line 533, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\User\PycharmProject\onlineshop\venv\lib\site-packages\django\utils\functional.py", line 37, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\User\PycharmProject\onlineshop\venv\lib\site-packages\django\urls\resolvers.py", line 526, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\User\PycharmProject\onlineshop-master\config\urls.py", line 24, in … -
Django how to sort and paginate nested ORM and non-ORM object
I need to make a query to get some properties and with its category FK get data for monthly cost in another table. With the result, need to calc value by day, installments, total price and due date. all works fine but there is a need to order data by some fields of the Property model, order by total price and paginate the result. i could make both, order and paginate work, but not together. Also, i'd like to ask if those calcs with installments is right to be placed on serializer.py, or should be moved to the viewset.py, or somewhere else? Here is my code so far: ViewSet.py with pagination: class MyViewSet(viewsets.ModelViewSet): queryset = MyModel.Property.objects.filter(status)\ .prefetch_related('owner__user')\ .prefetch_related('host__user')\ .prefetch_related('category__user') serializer_class = MySerializer pagination_class = StandardResultsSetPagination filterset_class = MyFilterSet filter_backends = [filters.OrderingFilter, dj_filters.DjangoFilterBackend] def get_queryset(self): today = str(datetime.now()) start_date = self.request.query_params.get('start_date') end_date = self.request.query_params.get('end_date') ''' validate start_date and end_date ''' return self.queryset ViewSet.py with sort: class MyViewSet(viewsets.ModelViewSet): queryset = MyModel.Property.objects.filter(status)\ .prefetch_related('owner__user')\ .prefetch_related('host__user')\ .prefetch_related('category__user') serializer_class = MySerializer # pagination_class = StandardResultsSetPagination filterset_class = MyFilterSet filter_backends = [filters.OrderingFilter, dj_filters.DjangoFilterBackend] def get_queryset(self): today = str(datetime.now()) start_date = self.request.query_params.get('start_date') end_date = self.request.query_params.get('end_date') ''' validate start_date and end_date ''' return self.queryset def list(self, request, *args, **kwargs): … -
Celery ForkPoolWorker returns None
I use Celery in my Django app. If I've understood correctly, Celery has two processes, MainProcess and ForkPoolWorker. The latter one is asynchronous and is used to do the heavy lifting to not block the main process. In my project, it seems like the MainProcess does the job and ForkPoolWorker logs None. Every time it runs a scheduled task, I get two loggins: [2022-01-28 02:13:35,597: INFO/MainProcess] Task my_task[0b0f3301-1a98-41f3-b635-a660c0779281] received [2022-01-28 02:13:35,706: INFO/ForkPoolWorker-2] Task my_task[0b0f3301-1a98-41f3-b635-a660c0779281] succeeded in 0.10891842400087626s: None I assume it returns None because the ForkPoolWorker doesn't do anything. Is it an automatic process or do I need to activate it somehow? Or does it kick in if I at some point have lots of tasks to process? At the moment I only have one task, is it the reason why the main process is used and if so, is there something I'd need to do to my setup? -
Unable to build a docker for Django and Mysql
I am building an application with Djnago and MySql. But I have error while build. This is my code: docker-compose.yml version: '3.9' services: db: image: mysql ports: - '3306:3306' environment: MYSQL_DATABASE: 'repository' MYSQL_USER: 'root' MYSQL_PASSWORD: '' MYSQL_ROOT_PASSWORD: '' web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - ./:/repository ports: - "8000:8000" depends_on: - db dockerfile FROM python:3.7.3-alpine # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN pip install --upgrade pip COPY requirements.txt . RUN pip install -r requirements.txt # copy project COPY . /usr/src/app EXPOSE 8000 CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] requirements.txt Django==3.2 django-cors-headers==2.4.0 django-crispy-forms==1.11.0 django-js-asset==1.2.2 djangorestframework==3.11.0 mysqlclient==1.4.6 xhtml2pdf==0.2.5 settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'repository', 'USER': 'root', 'PASSWORD': '', 'HOST':'localhost', 'PORT':'3306', } } This is My Error > #9 10.61 ERROR: Could not find a version that satisfies the requirement mysqlclient==1.4.6 (from versions: 1.3.0, 1.3.1, 1.3.2, > 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.3.8, 1.3.9, 1.3.10, 1.3.11rc1, 1.3.11, 1.3.12, 1.3.13, 1.3.14, 1.4.0rc1, 1.4.0rc2, 1.4.0rc3, 1.4.0, 1.4.1, 1.4.2, 1.4.2.post1, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 2.0.0, 2.0.1, 2.0.2, 2.0.3, 2.1.0rc1, 2.1.0) > #9 10.61 ERROR: No matching distribution found for mysqlclient==1.4.6 > ------ > executor failed running [/bin/sh … -
NoReverseMatch Error at "url" in Django while requesting AJAX url
I am trying to refresh the table data in my Django HTML page, without refreshing the whole page after every 10 seconds ... for which I am using AJAX in Django This is the HTML Page I want to render - <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>temp1</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h1>Hello there</h1> <h1>{{info_data}}</h1> <table id="_appendHere" class="table table-striped table-condensed"> <tr> <th>Username</th> <th>Email</th> <th>Gender</th> </tr> {% for item in info_data %} <tr><td>{{item.username}} - {{item.email}} - {{item.gender}}</td></tr> {% endfor %} </table> </body> <script> var append_increment = 0; setInterval(function() { $.ajax({ type: "GET", url: {% url 'App1:temp' %}, // URL to your view that serves new info }) }, 10000) </script> </html> I have created a model inside an app called "App1" whose data I am passing to this table using this code - from django.shortcuts import render from App1.models import Info # Create your views here. def tempPage(request): info_data=Info.objects.all() context={"info_data":info_data} return render(request,"App1/temp1.html",context) This is the urls.py for App1 - from django.contrib import admin from django.urls import path,include from App1 import views app_name = 'App1' urlpatterns = [ path('temp/', views.tempPage,name="tempPage"), ] But I get this error on the URL http://localhost:8000/temp/ - NoReverseMatch at /temp/ … -
How to convert Django Management Commands into Form Actions to populate database with an uploaded CSV file?
Django 1.9.8, Python 3.6, Postgres database I am writing a small Django app that will use the UI to import products from an uploaded csv file via a Form and populate the database. I have written the backend logic for the app using Custom Management Commands but am struggling confused about how to connect this to the frontend using Forms. Here's an example of the csv file: name,sku,description Brian James,skus-will-look-like-this,The products will have various descriptions. And multiple lines too. I have the following logic implemented: Read a large csv file of 500K products to the database using SKU as a unique field. When the file has uploaded, a live stream of what is happening should be displayed. print() currently serves this purpose but I think it should be possible to implement this with SSE on the front end. All products can be searched / filtered. Be able to delete all existing records and start a fresh upload as well as being able to add/update products manually. I created a simple form uploader as a separate project to play around with it, but even after this and reading the docs I am not clear on how to make the jump from … -
Get submit input in Django without forms
I have a page with several buttons, and only some appear depending on the scenario. More specifically, I have a user profile page that gives the user various buttons depending on their relationship to the user that they are viewing. I determine which buttons to display by identifying the user's relationship with the user they are viewing, then use a series of if statements in the profile page to display the right buttons. For example, when the user is viewing a stranger, they have block and send friend request options. If they are viewing someone that is their friend, they have an unfriend and block option. The backend needs to know that the user pressed the submit button, so that it can update the database. Using forms for this seems excessive, since I just need a simple submit input to reach the backend(no other user data). I am showing what I'm currently using below, but for some reason, it refuses to send a POST request at all. Profile Template <h1>{{viewingName}}</h1> <img src="{{displayed_user.profile_picture.url}}" width="240"> <p>{{displayed_user.bio}}</p> {% if areFriends %} <p>You're viewing your friend</p> <input type="submit" value="Remove Friendship" name ="remove_friends_form"> <input type="submit" value="Block" name ="block_form"> {% elif activeRequestTo %} <p>Friend Request Delivered. … -
Mongoengine: create a QuerySet from a MongoDB cursor object received from aggregate
I have a MongoDB cursor which is generated by an aggregation. pipeline= [ {"$match": {'orderStatus': "OPEN" }}, {'$lookup': {"from": 'items', "localField": 'itemid', "foreignField": 'itemid', "as": 'items'}}, ] cursor = Orders.objects.aggregate(pipeline) Since mongoengine documentation specifies that a QuerySet is a wrapper of a MongoDB cursor, is there any way to create a QuerySet with a given cursor? Note: There is an obvious solution, querying the database again but i don't want to query db again which will reduce time -
django.db.utils.ProgrammingError: relation "django_content_type" already exists
When I create a new model and ran the server I am getting an error as "django.db.utils.ProgrammingError: relation "django_content_type" already exists". As I couldnt able to create a new table in the existing database. I have tried all the existing solutions still couldnt able to resolve it. kindly help me with it. Tried solutions: manage.py migrate --fake manage.py migrate --fake-initial python manage.py migrate --run-syncdb -
Using Memcached with Django and using cache page decorator for guest users but in one condition I need to invalidate the cache but dont know cache key
def inner_decorator(func): @wraps(func) def inner_function(request, *args, **kwargs): if not request.user.is_authenticated: return cache_page(*cache_args, **cache_kwargs)(func)(request, *args, **kwargs) return func(request, *args, **kwargs) return inner_function return inner_decorator``` -
Django Form not Saving The field I added
I am following a Django tutorial on Youtube, I added a bio field in the UserUpdateForm. There is a slot for me to edit the bio on change_profile.html but when I press the update button it updates everything else except for the bio. from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class UserUpdateForm(forms.ModelForm): email = forms.EmailField() # What I added bio = forms.CharField(required=False) class Meta: model = User fields = ['username', 'email', 'bio'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] The function that saves the forms @login_required def change_profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, 'Profile Updated') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form' : u_form, 'p_form' : p_form } return render(request, 'users/change_profile.html', context) The change_profile.html {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block title %}Change Profile{% endblock title %} {% block content %} <div class="content-section"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Edit Profile</legend> {{ u_form|crispy }} … -
Unable to Create new tables in Postgres (Django rest API)
File "/usr/lib/python3/dist-packages/django/db/backends/utils.py", line 82, in _execute return self.cursor.execute(sql) django.db.utils.ProgrammingError: relation "django_content_type" already exists Can someone guide me to solve this error? -
How to order by last name on a full name column in Django?
I have a model contact with a column called FullName which contains, for example, "John Smith". How can order the data by the last name that appears in the FullName column? For a long name like "John Smith Doe", I would like to order the data by the word "Doe". I am using postgres db -
Is there a way to convert a Django project with postgresql database built from source with cube extension into a msi?
I created a Django project and distributed on IIS that uses PostgreSQL as database. I compiled PostgreSQL from source with a modification on creating an extension. It is running quite well in IIS but I just want to convert all Django project to be a MSI in order to be able to distributing on others windows PC. So please anyone advise a way or solution that can help me on this. It would be highly appreciated for your help! Thanks in advance.