Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django multiple serializers with relation
I have two tables of users and I am creating a form to store the user information. Models.py class MyUser(User): address = models.CharField(max_length=200) city = models.CharField(max_length=200) expire_date = models.DateField() This creates a table with user_ptr_id to the auth_user table of django. I created two serializers: one for the User: class UserSerializer(serializers.ModelSerializer): first_name = serializers.CharField(min_length=2, required=True) last_name = serializers.CharField(min_length=2, required=True) email = serializers.EmailField(min_length=5, required=True) password = serializers.CharField(min_length=8, write_only=True, required=True) class Meta: model = User fields = ('email', 'first_name', 'last_name', 'password') def create(self, validated_data): return UserSerializer(**validated_data) And MyUser class: class MyUserSerializer(serializers.ModelSerializer): address = serializers.CharField(max_length=200) city = serializers.CharField(max_length=200) class Meta: model = MyUser fields = ('city', 'address') def create(self, validated_data): return MyUser(**validated_data) As I am using Django Rest-Framework-Auth, I craeted a serializer to catch the data, but I don't know how to let the things work together. In the "MyUserSerializer" class, I also perform many validate checks, that I omitted here to keep the code clean. Code below doesn't work class UserSignup(serializers.Serializer): user = UserSerializer() my_user = MyUserSerializer() confirm_psw = serializers.CharField(min_length=8, write_only=True, required=True) def validate(self, data): if not data["user"].get('password') or not data.get('confirm_psw'): raise serializers.ValidationError("Please enter a password and confirm it.") if data["user"].get('password') != data.get('confirm_psw'): raise serializers.ValidationError("Those passwords don't match.") return data def save(self, … -
page not found error on Django 3 by examples tutorial
I'm learning Django and I'm trying to get a blog application running but I keep getting the same error: page not found error I even went to the files available in github link which are the endgoal (while slightly different) I imported the whole mysite folder, opened a virtual env, installed Django, pushed the migrations and ran the server but I still get the same error. It seems the problem arises with both my code and with the reference code in the github files. -
Django FormWizard resets unexpectedly on production
I have a 5 step form-wizard which works perfectly when running locally. But on production, EVERYTIME I click next when on step 2, instead of going to step 3 it goes back to step 1. With the data still remaining in the form-data! I have been looking around Google but I think this issue is too specific. Does anyone have any experience with this or something comparable? Also, it has been working before, but since a week ago it started doing this. Without any new commits having been pushed in the meantime... -
Error: "DoesNotExist at / Menu matching query does not exist."
I was practicing with wagtail, following this tutorial when i got that DoesNotExist at / Menu matching query does not exist error, but i can not find the root of the problem. I would really appreciate any help or knowlegde Django: 3.2.9 Python: 3.10.0 debug_toolbar: 3.2.2 django_extensions: 3.1.5 taggit: 1.5.1 wagtail.core: 2.15.1 Environment: Request Method: GET Request URL: http://localhost:8000/ Django Version: 3.2.9 Python Version: 3.10.0 Installed Applications: ['home', 'search', 'flex', 'streams', 'site_settings', 'subscribers', 'blog', 'menus', 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.contrib.settings', 'wagtail.contrib.routable_page', 'wagtail.contrib.sitemaps', 'wagtail.contrib.modeladmin', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail.core', 'modelcluster', 'taggit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.sitemaps', 'debug_toolbar', 'django_extensions'] Installed Middleware: ['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', 'django.middleware.security.SecurityMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware'] Template error: In template C:\Users\pedro.garcia\website\mysite\mysite\templates\base.html, error at line 3 Menu matching query does not exist. 1 : {% load static wagtailuserbar menus_tags %} 2 : 3 : {% get_menu "main" as navigation %} 4 : 5 : <!DOCTYPE html> 6 : <html class="no-js" lang="en"> 7 : <head> 8 : <meta charset="utf-8" /> 9 : <title> 10 : {% block title %} 11 : {% if self.seo_title %}{{ self.seo_title }}{% else %}{{ self.title }}{% endif %} 12 : {% endblock %} 13 : {% block title_suffix %} Traceback (most recent … -
Django PWA/deployment with pre populated DB
I have a website ready, developed with django on the backend and Javascript/Jquery/AJAX on the front end. Now, I want to convert it into a PWA on android but I want to keep some pre-poulated DB entries in the PWA and do not want to re create these entries upon deployment. On my laptop, I have a script populate.py that I run manually after makemigrations and migrate commands so that my DB has those standard entries for any user who registers and logs in the website. I wish to keep those entries upon deployment specially when I create a PWA but I cannot find a link describing the steps to keeping the DB entries. I found this Core Data entities missing when tested on device link and this link Deploy app with pre-populated Core Data for ios but I am looking forward to an android Can you suggest ? -
How to use Error Report from GCE with Docker and Django?
I'm running Django on a compute engine using Docker. I would like to know how to check the error in the Error Report when the application encounters an error like Cloud run. I'm looking at how to set up an Error Report in Python. https://github.com/googleapis/python-error-reporting/tree/main/samples/snippets/fluent_on_compute Looking at this sample, it looks like I need to raise an exception and run report (traceback.format_exc ()) to use the Error Report. Sample code def simulate_error(): fluent.sender.setup('myapp', host='localhost', port=24224) def report(ex): data = {} data['message'] = '{0}'.format(ex) data['serviceContext'] = {'service': 'myapp'} # ... add more metadata fluent.event.Event('errors', data) # report exception data using: try: # simulate calling a method that's not defined raise NameError except Exception: report(traceback.format_exc()) When I run Django, I get an error other than using try: execpt. How can I display such errors in the Error Report? Please let me know if there is any good way. thank you. -
Django: Writing Model Field-Value into another Models Dropdown List?
I got a Model "PC_Configuration" with a bunch of Dropdown-Lists: class PC_Configuration(models.Model): PROCESSOR_CHOICES = ( ('None', 'Wähle deinen Prozessor'), ('1', 'Prozessor1'), ('2', 'Prozessor2'), ('3', 'Prozessor3'), ) GRAPHICSCARD_CHOICES = ( ('None', 'Wähle deine Grafikkarte'), ('1', 'Grafikkarte1'), ('2', 'Grafikkarte2'), ('3', 'Grafikkarte3'), ) OS_CHOICES = ( ('None', 'Wähle dein Betriebssystem'), ('1', 'Betriebssystem1'), ('2', 'Betriebssystem2'), ('3', 'Betriebssystem3'), ) RAM_CHOICES = ( ('None', 'Wähle deinen Arbeitsspeicher'), ('1', 'RAM1'), ('2', 'RAM2'), ('3', 'RAM3'), ) HARDDRIVE_CHOICES = ( ('None', 'Wähle deine Restspeicher-Größe'), ('1', 'Festplatte1'), ('2', 'Festplatte2'), ('3', 'Festplatte3'), ) processor = models.CharField(max_length=25, choices=PROCESSOR_CHOICES, default='None') graphicscard = models.CharField(max_length=25, choices=GRAPHICSCARD_CHOICES, default='None') ram = models.CharField(max_length=25, choices=RAM_CHOICES, default='None') os = models.CharField(max_length=25, choices=OS_CHOICES, default='None') harddrive = models.CharField(max_length=25, choices=HARDDRIVE_CHOICES, default='None') I just tested the Choices of those Dropdown-Fields with some Hardcoded Inputs, but I actually want to get all Data for the Choices of e.g. the "processors"-Dropdown-Field from the Table of the field name of the Model Processors: class Processors(models.Model): name = models.CharField(max_length=50) So my question is: Is it possible to get all the values inside the name-Fields of the Processors-Model, maybe write them into a Array just like the current Hardcoded Input for being able to show them inside the Dropdown-Field of the PC_Configuration Model? -
Trouble with SlugRelated returning nested slug_field Django Serializer
I have this serializer field like this members = serializers.SlugRelatedField(queryset=Member.objects.all(), many=True, slug_field="user__username") But it flags an Attribute error that says 'Member' object has no attribute 'user__id' -
Django TransactionManagementError
In my application I have cause to refresh my django database connection in case it has dropped during a long blocking (not database related) task. This generally works but I have found that creating a new model directly after reconnecting causes an error. My code: from django.db import connection from django.db.utils import OperationalError import time connection.close() db_conn = False while not db_conn: try: connection.ensure_connection() db_conn = True except OperationalError: print('Database unavailable, waiting 1 second...') time.sleep(1) print('Database available') proc_info = models.ProcessingInfo() proc_info.processing_name = "xxx" proc_info.in_progress = False proc_info.save() This gives the following error: File "/usr/local/lib/python3.7/dist-packages/django/db/backends/base/base.py", line 448, in validate_no_broken_transaction "An error occurred in the current transaction. You can't " django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. Any idea what the issue could be? -
How to add custom data to the response in UpdateAPIView?
How to add custom data to the response in UpdateAPIView? class UpdateItemAPIView(UpdateAPIView): authentication_classes = (SessionAuthentication, ) permission_classes = (IsAuthenticated, ) serializer_class = UpdateItemSerializer def get_object(self): return get_object_or_404(Item, pk=self.kwargs.get('pk'), user=self.request.user) def get(self, request, pk, format=None): item = self.get_object() serializer = UpdateItemSerializer(item) return Response(serializer.data) -
Nginx (13: Permission denied) while connecting to upstream
I'm deploying my Djano application on a VPS and I'm following the steps in the below link to configure my app with Gunicorn and Nginx. How To Set Up Django with Postgres, Nginx, and Gunicorn on Ubuntu 16.04 Everything went well with the tutorial (gunicorn and nginx are running) but the issue is that when Im' visiting the VPS through the static IP its showing a white screen that is always reloading. After checking nginx log I found the following: (13: Permission denied) while connecting to upstream, client: <client_ip>, server: <server_ip>, request: "GET / HTTP/1.1, upstream: "http://unix:/root/myproject/myproject.sock:/", host: "<server_ip>", referrer: "http://<server_ip>/" -
DJANGO updating single row result from a template table listing .all() queryset results
I have a permissions view with a queryset showing all rows in the permissions db table as a <table> in permissions.html template. Looks good :) I have wrapped a each result as <form><tr> with a button in the last <td> My desire is to change some of the fields in a single row and press the button to update that particular permission row in the permissions table. def permissions(request): users = User.objects.all() userformset = modelform_factory(User) forms_list = [] if request.method == "POST": # UPDATE RESULT WITH ID OF ROW WHERE BUTTON WAS PRESSED # if form.is_valid(): # form.save() # return redirect('permissions') # refresh the page>? for user in users: forms_list.append({'form': PermissionsForm(instance=user, label_suffix='')}) # REMOVE THE COLON context = { 'forms': forms_list, } return render(request, 'useradmin/permissions.html', context) Passing a value in the request would mean i would need to have something like str:pk but then that would cause an error as the page will need to keep showing multiple (updated) results. Any advice or solutions would be greatly appreciated. Thanks -
In the netbox plugin development tutorial, where is manage.py being run from?
I am following the tutorial on plugin development at https://netbox.readthedocs.io/en/stable/plugins/development/ I have gone as far as creating the models and want to make migrations... However, the manage.py is not found in the root of my plugin folder. Where is it expected that manage.py is? -
DateTimeField not shown in a template - django
I have two DateTime Fields in a model: models.py start_appointment = models.DateTimeField(default=timezone.now, blank=True) end_appointment = models.DateTimeField(default=timezone.now, blank=True) i also have a form where i set widgets for above fields: 'start_appointment': forms.DateTimeInput(attrs={'class': 'form-control', 'type': "datetime-local"}), 'end_appointment': forms.DateTimeInput(attrs={'class': 'form-control', 'type': "datetime-local"}), i have an update view where i want to update appointment's fields for example start_appointment. However when rendering form in a template these two fields are shown as dd/mm/yyyy --:--, -- meaning values from database not shown, while all the others are rendered with no problem. From the other hand i can execute the form with no problem and update is successful. template: <div class="form-group row"> <label class="col-form-label col-3 text-lg-right text-left">{% trans 'Start Appointment' %}</label> <div class="col-9"> {{ form.start_appointment }} </div> </div> What might be the problem? -
How to query Reverse related field in the django serializer?
I want a query result that looks like this in Django using a Serializer relations: [ { "id": 1, "title": "Article 1", "authors": ["John Doe", "Rose Mary"], } ] What I tried is a slugRelatedField that looks like this: authors = serializers.SlugRelatedField(slug_field="file__folder__workspace", many=True, read_only=True) But it failed. My model Post have file field and has a relation of "file__folder__workspace". I want to fetch the authors that belong to the workspace. -
How to render Django CheckoxInput in a grid from Modelform?
models.py class MyModel(Model): author = ForeignKey(settings.AUTH_USER_MODEL, on_delete=CASCADE) title = CharField(max_length=200, default='') text = TextField(default='') choice_1 = BooleanField(default=False) choice_2 = BooleanField(default=False) choice_3 = BooleanField(default=False) choice_4 = BooleanField(default=False) choice_5 = BooleanField(default=False) choice_6 = BooleanField(default=False) def __str__(self): return self.title forms.py class MyModelForm(ModelForm): class Meta: model = MyModel fields = [ 'title', 'text', 'choice_1', 'choice_2', 'choice_3', 'choice_4', 'choice_5', 'choice_6' ] widgets = { 'text': Textarea(), 'choice_1': CheckboxInput(), 'choice_2': CheckboxInput(), 'choice_3': CheckboxInput(), 'choice_4': CheckboxInput(), 'choice_5': CheckboxInput(), 'choice_6': CheckboxInput() } I am using the django bootstrap 5 integration and attempting to render the checkboxes on a grid like this: {% extends "base.html" %} {% block content %} {% load static %} {% load bootstrap5 %} {% bootstrap_css %} {% bootstrap_javascript %} {% bootstrap_messages %} (Other code here...) <div class="row-cols-4"> {% for field in form %} <div class="col-sm">{% bootstrap_field field layout='horizontal'%}</div> {% endfor %} </div> However, the row and column css (also from bootstrap 5) seem to do absolutely nothing, and it's not really clear to me why this is the case. What am I doing wrong here? -
For loop in for loop Django template
i want to set up 'send request/cancel request' function in template. The problem with displaying, if request exist 'cancel', if not 'send'. I don't get how to correctly get request and compare 'profile' with 'to_profile'. Now i got stuck with 'for' loop in 'for' loop... \ In template it shows 3 buttons( the same quantity requests from this event ) for one profile enter image description here Could you give me some tips how to fix, avoid, or do in another way please. Thank you! request model class EventInviteRequest(models.Model): from_event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='from_event', null=True) to_profile = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='to_profile', null=True) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return f"From {self.from_event} to {self.to_profile}" view i try to use def get_list_of_all_users(request, event_id): """Get list of all users""" event = Event.objects.get(id=event_id) profiles = Profile.objects.all() requests = EventInviteRequest.objects.filter(from_event=event) context = {'profiles': profiles, 'event': event, 'requests': requests} return render(request, 'events/invite_all_profiles_to_event.html', context) template {% extends 'base.html' %} {% load static %} {% block title %}All profiles{% endblock %} {% block content %} <h3>All profiles:</h3> {% for profile in profiles %} <div style="display: inline-block; margin-right: 10px; text-align: center;"> <a href="{% url 'account:profile' profile.id %}"> {% if profile.photo %} <img src="{{ profile.photo.url }}" width="70" height="100"> {% else %} <img … -
How to i18n translate url patterns Django 3.2
I'm stuck in url translation while adding language support to my app. Although I have applied the ones written in the documents one by one, I still have not solved this problem. Can you help me see where I went wrong? The problem is exactly that my application will have two languages (TR and EN) 12.0.0.0.1/tr-url when the application is in tr while in english It's hard to go to 12.0.0.0.1/en/en-url addresses. However, when switching from Turkish to English, the urls are as follows: en: 127.0.0.1/en/en-url en: 127.0.0.1/en/en-url Similarly, when switching from English to Turkish, en: 127.0.0.1/en/en-url en: 127.0.0.1/en/en-url is in the form. If anyone knows how to switch languages, I'd be very happy. from django.utils.translation import gettext_lazy as _ from django.conf.urls.i18n import i18n_patterns from New import views as new_views from Home import views as home_views from Home.views import change_language urlpatterns = [ path('admin/', admin.site.urls), path('change_language/', change_language, name='change_language'), path('i18n/', include('django.conf.urls.i18n')), ] home_patterns =([path('', home_views.Index, name="index"), path(_('sistem-cozumumuz/'), home_views.Solution, name='solution'), path(_('teklif-isteyin/'), home_views.OfferRequests, name="offer-request"), path(_('gizlilik-politikasi/'), home_views.PrivacyPolicy, name='policy'), path(_('iletisim/'), home_views.Contact, name='contact'), ]) news_patterns =([path('', new_views.Index, name="index"), path(_('referanslar/'), new_views.References, name="reference"), path(_('yorumlar/'), new_views.Comments, name="event"), path(_('basinda-biz/'),new_views.News,name="new"), path(_('dokumanlar/'), new_views.Downloads, name="download"), path(_('<slug:slug>/'),new_views.NewDetails,name="new-detail"), path(_('yorumlar/<slug:slug>/'),new_views.CommentDetails,name="comment-detail"), path(_('referanslar/<slug:slug>/'),new_views.ReferenceDetails,name="reference-detail"), ]) urlpatterns += i18n_patterns( path('', include(home_patterns),name="Home"), path(_('haberler/'), include(news_patterns), name="New"), path('change_language/', change_language, name='change_language'), path('i18n/', include('django.conf.urls.i18n')), prefix_default_language=False,) … -
how to set url like /<int:post_id>/apply?
url urlpatterns = [ path('company', views.CompanyAdList, name='CompanyAdList'), path('company/write', views.CompanyAdWrite, name='CompanyAdWrite'), path('company/<int:post_id>', views.CompanyAdDetail, name='CompanyAdDetail'), path('company/<int:post_id>/apply', views.CompanyAdApply, name='CompanyAdApply'), ] js in /company/1 function apply_request() { var queryString = $("form[name=applyForm]").serialize(); $.ajax({ type : 'post', url : "{% url 'CompanyAdApply' %}", data : queryString, dataType : 'json', success: function(data){ if(data.result==200){ openPopup("alert", data.result_text); }else{ openPopup("alert", data.result_text); } return; }, error: function (request, status, error){ var msg = "ERROR : " + request.status + "<br>" msg += + "content: " + request.responseText + "<br>" + error; console.log(msg); } }); } I want to make form in /company/1 to /company/1/apply how to do this? when I do what I think. showed error. ['company/(?P<post_id>[0-9]+)/apply$'] -
INNER JOIN in django orm
I have two tables that only contain the same product ids and they didnt have foreigh keys. So question is about how i can filter them both in query by id. In SQL i want to do something like this SELECT Url FROM pricehistory p INNER JOIN product d ON p.ProductID = d.ProductID -
Python is running perfectly on aws but not get any result showing site can't reachable . Port is working fine as we tested a nodejs
The code is working fine in local and we are using ec2 instance the server database is working fine the port also because I just run a node project on that port which is working and i can fetch data from server db. -
Creating a GIN index with a function specified in Django
I have created a model in Django. class MyModel(models.Model): features = TextField(blank=True, default='') There are several possible ways to store the data in the feature field. Some examples below. feature1;feature2 feature1, feature2 feature1,feature2 And so on. I need to create a GIN index for that field. I would probably do it in postgreSQL in the following way CREATE INDEX features_search_idx ON "mymodel" USING gin (regexp_split_to_array("mymodel"."features", E'[,;\\s]+')); Would it be possible to do the same thing by a migration? -
Define model and form through url dispatcher slug parameters
I have the code in urls.py: from django.urls import path from tables.models import subcomponentsTable, rawMaterialsTable from tables.forms import subcomponentsTableForm, rawMaterialsTableForm urlpatterns = [path('newEquipment', views.createTableView.as_view(model=subcomponentsTable,form_class=subcomponentsTableForm), name='newEquipment'), path('newRawMaterial', views.createTableView.as_view(model=rawMaterialsTable, form_class=rawMaterialsTableForm),name='newRawMaterial'), ... etc. and i would like to refractor it as follows to make it reusable for different models and forms: urlpatterns = [path('new/<slug:tableType>', views.createTableView.as_view(), name='newInstance'),... views.py: class createTableView(LoginRequiredMixin, CreateView): template_name = 'tables/createTableTemplate.html' what method in createTableView I should overload, so I could calculate appropriate form and model from slug:tableType, and use it in my view? To do it properly? Will be there any difference with UpdateView and DeleteView? Thank you in advance! -
create() takes 1 positional argument but 2 were given. Django rest framework,. How to slove it?
I am new to Django restframework I want to register a new student to school but it does not work. I have tried many solutions . what I got is:create() takes 1 positional argument but 2 were given when I try to post. I am not sure if my code in the viewset correct. Can someone help me? In my serializers.py: class StudentSerializer(serializers.Serializer): class Meta: model = Student fields = ['first_name'] class SchoolSerializer(serializers.Serializer): is_existing_student = = serializers.BooleanField() student = StudentSerializer(many=True) class Meta: model = School fields = ['is_existing_student', 'name', 'city', 'street', 'student'] def create(self, **validated_data): student_data = validated_data.pop('student') school_instance = School.objects.create(**validated_data) for student_data in student_data: Student.objects.create(school_instance=school_instance, **student_data) return school_instance In my views.py: class SchoolViewSet(mixins.CreateModelMixin, RetrieveModelMixin, ListModelMixin, GenericViewSet): serializer_class = SchoolSerializer queryset = School.objects.all() @action(detail=True, methods=['POST']) def school(self, request, *args, **kwargs): school = self.get_object() if serializer.is_valid(): School.create(school=school, name='name', street='street', city='city', student='student') school.save() else: return Response(status=status.HTTP_204_NO_CONTENT) In my url: router.register(r'register', SchoolViewSet) -
django Could not find the GDAL library
when I ran ./manage.py runserver i got django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal3.1.0", "gdal3.0.0", "gdal2.4.0", "gdal2.3.0", "gdal2.2.0", "gdal2.1.0", "gdal2.0.0"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. So, I find out GDAL is not installed by running brew list and I did not find it when I ran brew install gdal i got this error Error: gdal: Failed to download resource "gdal" Failure while executing; `git clone --branch master -c advice.detachedHead=false https://github.com/OSGeo/gdal.git /Users/apple/Library/Caches/Homebrew/gdal--git` exited with 128. Here's the output: Cloning into '/Users/apple/Library/Caches/Homebrew/gdal--git'... error: RPC failed; curl 18 transfer closed with outstanding read data remaining error: 715 bytes of body are still expected fetch-pack: unexpected disconnect while reading sideband packet fatal: early EOF fatal: fetch-pack: invalid index-pack output is there other ways to install gdal because my internet connection too slow, Also, where is the problem here.