Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
probleme to upload multiple file in Django
I'm getting an error when I try to upload multiple files in a form. this is my model: class Delivery(models.Model): user = models.ForeignKey( Client, on_delete=models.CASCADE, verbose_name=_("Client"), related_name=_("delivery_user") ) pickup_address = models.ForeignKey(Address, on_delete=models.CASCADE, related_name=_("pickup_address")) destination_address = models.ForeignKey(Address, on_delete=models.CASCADE, related_name=_("destination_address")) operation_date = models.DateField( _("desired pickup date"), auto_now=False, auto_now_add=False, blank=False, null=False ) operation_time = models.TimeField( _("desired pickup date"), auto_now=False, auto_now_add=False, blank=False, null=False ) document = models.FileField( help_text=_("Delivery Documets"), verbose_name=_("Delivery Certificates"), upload_to="documents/deliveries_documents/", blank=True, null=True, ) class Meta: ordering = ("-created_at",) verbose_name = _("Delivery") verbose_name_plural = _("Deliveries") def get_absolute_url(self): return reverse("delivery:unconf-delivery-details", args=[self.id]) I used an exemple from Django website to handle the multiple upload of files and this is the form and the view for this model: View.py class DeliveryCreateView(LoginRequiredMixin, UserPassesTestMixin, CreateView, FormView): model = Delivery form_class = UserDeliveryForm template_name = "deliveries/customer/edit_deliveries.html" def get_success_url(self): return reverse("delivery:operation-form", kwargs={"pk": self.object.pk}) def test_func(self): return self.request.user.is_active def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist("decument") if form.is_valid(): for file in files: self.Delivery.objects.create(document=file) return self.form_valid(form) else: return self.form_invalid(form) Form.py class UserDeliveryForm(forms.ModelForm): class Meta: model = Delivery fields = [ "user", "pickup_address", "destination_address", "operation_date", "operation_time", "document", ] widgets = { "operation_date": forms.DateInput( format=("%d %B %Y"), attrs={"class": "form-control mb-2 delivery-form", "placeholder": "JJ-MM-AAAA"}, ), "operation_time": forms.TimeInput( attrs={"type": "time", … -
how to create new upload_to for FileField folder from views.py
in models.py, class Files(models.Model): File = models.FileField(upload_to="documents/") in my views.py, all works perfectly when i remove the 3rd line file = Files(File=f) file.File.upload_to('Media/') file.save() Question is. I want to create new upload_to Folder from views.py only. is it even POSSIBLE ? I know the instance function method of creating Folder used in models.py, i dont want to use it -
Wagtail Custom Translatable Menu
I am new to wagtail and i am working with a custom menu. I set up a custom menu class and use a tag to display the menu-items in the templates. This works fine, however i would need to create different menus depending on what language my site is used in. (i know wagtailmenus exists, however i could not find a satisfying way to create translated menus there either) I wanted to create a similar translation experience like wagtail-localize does with pages. Is this possible or do i have to take a different approach? I already tried to use wagtails TranslatableMixin to simply create duplicates of my menu with different translations, however this does not seem to work. -
how to use if in django class based view
i want to use if and i need to have a variable and that variable needs kwords class ResetPassword(FormView): template_name = 'reset_password.html' form_class = ResetPasswordForm def get_context_data(self, **kwargs): context = super(ResetPassword, self).get_context_data(**kwargs) context['uuid'] = kwargs.get('uuid') context['base64'] = kwargs.get('base64') return context if (get_context_data['context']['uuid'] and get_context_data['context']['base64']) == (url_uuid and url_base64): def form_valid(self, form): user = User.objects.get(id= self.request.user.id) user.set_password(form.cleaned_data['password']) user.save() return redirect('/login') -
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.