Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Make isort recognize imports from Django apps as first-party imports
I'm working on a project with many different Django apps. I want to use isort on this project but the imports from Django apps (from myapp1.mymodule import myfunction) are seen by isort as third-party imports. How can I make isort recognize them as first-party imports? I could add in the isort configuration (in the .cfg): known_first_party=myapp1,myapp2... but I'll have to maintain this list. Is there a better way? -
order_with_respect_to a null ForeignKey causes expensive query
I have a model that looks like this: class CharacterSheetNode(models.Model): parent = models.ForeignKey('self', related_name='items', null=True, on_delete=models.CASCADE) # other fields class Meta: order_with_respect_to = 'parent' I have 30M+ instances of this model in my database. My problem is that when I create a new instance of it, the following Django code is ran: site-packages\django\db\models\base.py, line 876: if meta.order_with_respect_to: # If this is a model with an order_with_respect_to # autopopulate the _order field field = meta.order_with_respect_to filter_args = field.get_filter_kwargs_for_object(self) self._order = cls._base_manager.using(using).filter(**filter_args).aggregate( _order__max=Coalesce( ExpressionWrapper(Max('_order') + Value(1), output_field=IntegerField()), Value(0), ), )['_order__max'] This piece of code will go through all the CharacterSheetNode with no parent (there are probably 1M of them), and look for the Max('_order') value. As if they were all children of the same parent "None". The query itself takes 7 seconds to run. How can I avoid running this code if the parent is null? Or at least tell Django to only set the order_value if there is a parent? The whole method from which these lines were extracted: def _save_table(self, raw=False, cls=None, force_insert=False, force_update=False, using=None, update_fields=None): """ Do the heavy-lifting involved in saving. Update or insert the data for a single table. """ meta = cls._meta non_pks = [f for … -
Cannot Get Django & Celery to work to Upload Images
I'm working on a django app that allows the user to upload multiple images at the same time. The problem is when they upload more than a two or three images they're forced to wait for too long while they're processed. The more images they put in there the longer they have to wait, also if they upload a ton of images (15 ~3mb images seems to be the max) it crashes. I would like them to be able to upload as many images as they want at the same time and not have huge wait times or crashes. I researched and seems like Celery & Rabbitmq would be great solutions to solve this as they would upload in the background while the user could return to the app, so it solves the waiting issue and the timeout issue as they'd all be uploaded as separate tasks (I think) I have rabbitmq installed and open, celery 4.3 installed but I'm not able to get it to work. I'm getting this error when I submit the form Exception Type: EncodeError at /test_form/ Exception Value: Object of type InMemoryUploadedFile is not JSON serializable I've tried to force celery to use pickle (celery.py … -
unique_together = (("name", "added_by"),) in Django model gives IntergretyError at/admin instead of Validation Error
I want to show a validation message like "This Project already exists" in my django admin. I keep getting an IntegrityError at my Name. Isn't Django supposed to validate this and give an ValidationError if I use unique_together=((,)) in my model? Or do I have to Try and Catch the IntegrityError myself? Can anyone tell me a best practice for validating unique users inside a form/model. models.py class Project(models.Model): name = models.CharField(max_length=200) added_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, default=None) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: unique_together = (("name", "added_by"),) def __str__(self): return self.name -
How can I access related_name from a model inside another app in Django?
I am working with models from differents apps in Django. I have two apps. One is called partners and other contracts. In the app partners, inside the file models.py, I have this model defined: class Partner(models.Model): cpf = models.CharField(max_length=11, null=False, blank=True) In the app contracts, inside the file models.py, I have this model defined: from partners.models import Partner class Contrato(models.Model): ... indications = models.ManyToManyField(Partner, through='ContractIndication', related_name='indications') class ContractIndication(models.Model): contract = models.ForeignKey(Contract, on_delete=models.CASCADE) partner = models.ForeignKey(Partner, on_delete=models.CASCADE) payed = models.CharField(max_length=1, choices=YES_NO, null=False, blank=True, default='N') However, in the file views.py from partners app, I cannot access all the contracts that a partner is linked, using this: partner = Partner.objects.get(...) indications = partner.indications.all() I am already using the related_name attribute from Contract. What am I doing wrong? -
Pass in variable to tag django
is there a way to pass in a variable in a tag in django templating? For example, <a href="{% url '{{ url_path }}' %}">Click here</a>, as you can see, I want to pass the url_path variable into the url tag, but when I do this, django treats {{ url_path }} as the string itself, not the variable url_path. Is there a way to pass in that variable in the url tag? Thanks in advance! -
Django make migrations error, fields clashes
I am doing a Django Web Application and I have a problem when I try to import the models with: python manage.py makemigrations ERROR SystemCheckError: System check identified some issues: ERRORS: beers.Beer.company: (models.E006) The field 'company' clashes with the field 'company' from model 'core.commoninfo'. CLASS BEERS.BERR Path: my_project/beers/models.py class Beer(CommonInfo): COLOR_YELLOW = 1 COLOR_BLACK = 2 COLOR_AMBER = 3 COLOR_BROWN = 4 COLORS_CHOICE = ( (COLOR_YELLOW, 'Yellow'), (COLOR_BLACK, 'Balck'), (COLOR_AMBER, 'Amber'), (COLOR_BROWN, 'Brown'), ) name = models.CharField('Name', max_length=50) abv = models.DecimalField('Alcohol By Volume', decimal_places=2, max_digits=5, default=0) color = models.PositiveSmallIntegerField('Color', choices=COLORS_CHOICE, default=COLOR_YELLOW) is_filtered = models.BooleanField('Is filtered?',default=False) creation_date = models.DateField('Creation Date', auto_now_add=True) image = models.ImageField('Image', blank=True, null=True, upload_to=beer_image_upload_location) company = models.ForeignKey(Company, related_name='beers', on_delete=models.CASCADE) class Meta: verbose_name = "Beer" verbose_name_plural = "Beers" ordering = ['name'] def __str__(self): return self.name @property def is_alcoholic(self): return self.abv > 0 def more_alcohol_than(self, alcohol): return self.abv > alcohol FATHER CLASS CORE.COMMONINFO Path: my_project/core/models.py For some reason I had to add core to my settings.py INSTALLED_APPS, but this isn't an app. class CommonInfo(models.Model): created_at = models.DateTimeField('Created at', blank=True, default=now) last_modified_at = models.DateTimeField('Modified at', blank=True, default=now) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='Created by', blank=True, null=True, related_name="%(app_label)s_%(class)s_created", on_delete=models.DO_NOTHING) last_modified_by = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='Modified by', blank=True, null=True, related_name="%(app_label)s_%(class)s_lastmodified", on_delete=models.CASCADE) def save(self, *args, **kwargs): if not … -
direction on how to update page for multiple users
I've created a django app that deals with company vehicles. A user enters the site and is able to see a list of vehicles. Then the user can click and check out a vehicle which then grays out the vehicle. The user can also click the gray and select the vehicle as being free for someone else to use. Question I have is what's the best way in handling if there was multiple users on the page? how do I update the page for user A when user B selected vehicle X. I've read about django-channels and also signals. I'm not sure what's the best fit. -
xhtml2pdf - Problem with displaying table rows using django forloop tag
What I am trying to do is to create an invoice pdf file with several table rows. Table rows would be created using for loop in Django. The problem is data inside for loop tag is not visible on the pdf file. You can check the screenshots below. Django properly renders invoice.html template so the code is valid, but the pdf file contains empty frame without any table rows. To render pdf from html I am using xhtml2pdf. how django render the invoice.html template how pdf file looks like invoice.html <html> <head> {% load static %} <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta charset="UTF-8"> <style> @font-face { font-family: Roboto; src: url('{% static 'fonts/Roboto-Regular.ttf' %}'); } @font-face { font-family: Roboto-bold; src: url('{% static 'fonts/Roboto-Bold.ttf' %}'); font-weight: bold; } @page { size: a4 portrait; @frame header_frame { /* Static Frame */ -pdf-frame-content: frame_header_left; left: 50pt; width: 245pt; top: 30pt; height: 150pt; } @frame header_frame { /* Static Frame */ -pdf-frame-content: frame_header_right; left: 300pt; width: 245pt; top: 50pt; height: 150pt; } @frame content_frame { /* Content Frame */ -pdf-frame-content: frame_invoice_number; left: 50pt; width: 512pt; top: 170pt; height: 30pt; } @frame col1 { -pdf-frame-content: frame_col1; left: 50pt; width: 245pt; top: 220pt; height: 130pt; } @frame … -
Model validation and intengrity errors
When my model need special validations i usually think first of db constraints to ensure the integrity of my database completely but i found some problem with this approach. I usually use UniqueConstraints like: models.UniqueConstraint( fields=('author', 'title'), name='valid_unique_author_title', ), and they work well because the forms and serializers catch the error and show a error like Post with this Author and Title already exists. but what happen with UniqueConstraint have a condition like models.UniqueConstraint( fields=('author', 'title'), condition=models.Q(title='title1'), name='valid_unique_title1_author_title', ), Contrary to expected they throw a integrity error which is not captured by the form and serializers (DRF), that cause a http response with 500 as status code, only just by adding a condition the error is no longer captured. The first question, I must modified all the forms and serializers that have check constraints or unique constraints with condition for catch Integrity errors? Finally the same happens with CheckConstraints like: models.CheckConstraint( check=~models.Q(title='forbidden_title'), name='valid_forbidden_title' ), The aboves examples are differents, i found two cases of constraints: No susceptible for race conditions. The check constraint that verified if the title is different for forbidden_title. Susceptible for race conditions. The second UniqueConstraint that verified if the author have other post with the same … -
django templates not showing objects
hi i m trying to pass data from my models but it does not show anything.. it is rendering {{Experience.first.Designation}} but {{Experience.Designation}} is showing nothing.. also if i use {{Experience.first.Designation}} it will ony show one row of database in for loop repetedly which i dont want {% for queryset in Experience %} <li class="{% if forloop.counter|divisibleby:2 %}timeline-right{% else %}timeline-left{% endif %}"> <div class="timeline-badge"> <i class="fa fa-calendar"></i> <p class="{% if forloop.counter|divisibleby:2 %}date-inverted wow {% else %}date wow {% endif %}">{{Experience.first.FromDate}} -{{Experience.first.ToDate}}</p> </div><!-- end timeline-badge --> <div class="timeline-panel wow slideInRight"> <div class="experience-content"> <h4>{{Experience.Designation}}</h4> <h5>{{Experience.Department}}</h5> <p>{{Experience.ShortNote}}</p> </div> </div><!--end timeline-panel --> </li><!-- end timeline-right --> {% endfor %} here is views.py file from django.shortcuts import render from home.models import * from django.views.generic import ListView # Create your views here. def index(request): abt = About.objects.all() return render(request,'home/index.html',{'abt': abt.first()}) def Experience(request): Exp = Experience.objects.all() return render(request,'home/Experience.html',{'Exp': Exp}) class MyView(ListView): context_object_name = 'name' template_name = 'home/index.html' queryset = About.objects.all() def get_context_data(self, **kwargs): context = super(MyView, self).get_context_data(**kwargs) context['Experience'] = Experience.objects.all() context['About'] = self.queryset return context here is models.py from django.db import models import datetime # Create your models here. class About(models.Model): image = models.ImageField(upload_to = 'pics') desc = models.TextField() class Experience(models.Model): Designation = models.CharField(max_length=150) Department = models.CharField(max_length=150,default='my dept') … -
Adding multiple filters onto a template variable
I am having trouble applying multiple filters to my template variables. The two filters I want to use are: add_class:"px-0" AND floatformat:2 When I add both filters it doesnt render the data no matter the order I put the filters. I am currently trying to implement it like this: {{ form.field | add_class:"px-0" | floatformat:2 }} -
Get field data from database to populate form fields for a user who has already submitted the form
I built a model form wherein I want a user to first login and then fill my form fields. For a new user with no previous submission, I want the form to be blank. For a customer who has submitted the form before, I want to get the id of that logged in customer making GET request and retrieve field values from database to populate the form, with data he previously entered to submit the form. At the moment I am trying this approach to get id of logged in user to populate the fields in views.py cur_customer = Customer.objects.get(id=request.user.id) This however gives me an error saying Customer matching query does not exist. So how would I implement this? views.py def multi_form(request): form=RegForm() if request.method=='POST': form=RegForm(request.POST, request.FILES) if form.is_valid(): form.save() messages.success(request, "Your Response has been recorded") context={'form':form} return render(request, 'customer/index.html', context) else : return render(request, 'customer/index.html', {'form': form}) else: cur_customer = Customer.objects.get(id=request.user.id) form=RegForm(initial={ 'first_name':cur_customer.get('first_name',''), 'last_name':cur_customer.get('last_name','')}) context = {'form': form} return render(request, 'customer/index.html', context) models.py class Customer(models.Model): id=models.AutoField(primary_key=True, default=None) customerReg=models.OneToOneField(CustomerReg, on_delete=models.SET_NULL, null=True, blank=True) first_name=models.CharField(max_length=200, blank=False, default=None) last_name=models.CharField(max_length=200, blank=False, default=None) class CustomerReg(models.Model): user=models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name=models.CharField(max_length=200, null=True) email=models.EmailField(max_length=254) -
ValueError: The 'photo' attribute has no file associated with it. from pillow
I got this error The 'photo' attribute has no file associated with it. when I am trying to save the image after process with Pillow. This is my view.py def preview_page(request, invoice): applicant_image_form = ApplicantImageForm( request.POST or None, request.FILES or None ) applicant_info = ApplicantInfo.objects.get(invoice=invoice) education_info = ApplicantEducation.objects.get(invoice=applicant_info.sl) if request.method == 'POST': photo = request.FILES.get('photo') signeture = request.FILES.get('signature') photo_open = Image.open(photo) signeture_open = Image.open(signeture) p_s = photo_open.size s_s = signeture_open.size if p_s[0] == 300 and p_s[1] == 300 and s_s[0] == 300 and s_s[1] == 80: photo = photo_open.thumbnail(size=(100, 100)) signeture = signeture_open.thumbnail(size=(100, 50)) applicant = ApplicantInfo.objects.get(invoice=invoice) ApplicantImage.objects.create( invoice=applicant, photo=photo, signeture=signeture ) return redirect('final-report', invoice=invoice) else: context = { 'applicant': applicant_info, 'education': education_info, 'form': applicant_image_form, 'message': 'invalid' } return render(request, 'dpe/preview.html', context) context = { 'applicant': applicant_info, 'education': education_info, 'form': applicant_image_form } return render(request, 'dpe/preview.html', context) How can I solve this issue? -
Django Slugfield with how to treat underscore and hyphen the same in uniqueness?
I have a slugfield: name = models.CharField( unique=True, validators=[ validate_slug, ], max_length=255 ) However, I also want to ensure uniqueness is checked where hyphens and underscores are treated the same. For this test case: name1 = 'surfer_190_chap` name2 = `surfer-190_chap` record = Record(name=name1) if record.full_clean(): record.save() record2 = Record(name=name2) with self.assertRaises(ValidationError): if record2.full_clean(): record2.save() The second name should fail, however it does not. What I tried (I'm still researching how to do this part): def validate_unique_underscore_hyphen(value): if '_' in value or '-' in value: ... name = models.CharField( unique=True, validators=[ validate_slug, validate_unique_underscore_hyphen ], max_length=255 ) -
convert list of dictionaries to queryset django
def db_data(request): grid_data = list(table_name.objects.all().values()) return JsonResponse(grid_data, safe=False) I am hitting above endpoint which gives list of dictionaries as response. Is there a way where I can convert this back to Queryset object at the receiver side so that I can perform ORM operations on this queryset object. -
Django , error when trying to pre populate form when editing it
I am trying to write a code to edit a post, and when I click to edit this post it must be pre populate with the old text. I trying many ways. Could someone help to see what is wrong with this code? enter code heredef edit_entry(request): if request.method == "POST": form = EditEntryForm(request.POST) if form.is_valid(): title = form.cleaned_data["title"] content = form.cleaned_data["content"] util.save_entry(title,content) args = {'form':form, 'content':content} return render (request, "encyclopedia/edit.html", { "name": title, "content": content }, args) if request.method == "GET": util.save_entry(title, content) return render(request, "encyclopedia/edit.html",{ "previous_title": title, "previous_content": content }) -
How Saleor core app flow for graphql query from database?
i am very new to saleor.io and in saleor currently i am seeing code of saleor core and run it successfully on local host. And it shows me result of grapghql query also. My question is that: When i try to run grapghql query in debug mode the saleor core doesnot stop at debug point of saleor core where i put the breakpoint (in my case i put debug points on urls.py). But when i start my application it stop on all break point which confuse me more that how it is getting data and returing data from postgres database. By debugging, i just want to see the flow of it and i am feeling difficulty in understanding it. Can anyone have a useful link or someone can explain it easily the flow of saleor core. So that this post also help other new users of saleor.io -
Remove duplicate result in django search
I hope you're well. Does anyone know how I can remove duplicate in search result? For instance, if i search "Louis". I got 4 duplicates results. Is there any way to got unique result? thanks in advance. user/views.py #search profile @method_decorator(login_required(login_url='/earlycooker/login/'),name="dispatch") class UserProfileResultsView(ListView): model = UserProfile template_name = 'search_results_user.html' def get_queryset(self): # new query = self.request.GET.get('q') object_list = UserProfile.objects.filter( Q(pays__icontains=query) | Q(town__icontains=query) | Q(user__username__icontains=query) | Q(mealtrend__name__icontains=query) | Q(pricetrend__name__icontains=query) | Q(speedtrend__name__icontains=query)| Q(strengthtrend__name__icontains=query) | Q(wellnesstrend__name__icontains=query) ) return object_list templates/search_result_user.html {% for userprofile in object_list %} <a href="{% url 'user:user_public_cookwall' slug=userprofile.user.userprofile.slug %}" class="search_user_link">{{ userprofile.user.username }}</a> {% endfor %} -
How to store a mysql database in the project folder for django3?
My settings.py looks like this :-> DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', #'NAME': BASE_DIR / 'db.sqlite3', 'NAME': 'django_test_db', 'USER': 'root', 'PASSWORD':'123', 'HOST': 'localhost', 'PORT': '3306', } } The database is getting stored in the default mysql directories on my computer. I want to save this database in the project folder itself. Please help. -
Generate Django model from Open API spec
I'd like to generate a set of Django models from a 3rd party's Open API / Swagger spec (so I can then use the Django Rest framework to receive messages from that 3rd party) In Swaggerhub / Codegen there is an option to export 'server stubs' for a variety of frameworks inc ASP.net and Flask Is there an equivalent way for Django? -
Using Static JSON and CSV Files for D3 Visuals in Django App
I am trying to test the capability of adding D3 Visualizations into my Django app. I found and am using this Sun Burst code here (thanks to Eduard Trott and Serhii Pahuta): https://bl.ocks.org/maybelinot/5552606564ef37b5de7e47ed2b7dc099 The page renders just fine when using the default code (since the data from that code is being called from an internet location, however, it fails when I try to use my own static file in the following way: d3.json("file_path_on_local_machine/json_file", function(error, root) { ... }; How do I properly call my data into this code? -
while sending data to api it gives integrity error
when i send date to my api it throws the following error IntegrityError at /api/add/ NOT NULL constraint failed: api_userinfo.user_id urls.py path('add/',views.UserAdditionalView.as_view()) models.py class User(AbstractUser): # username = None email = models.EmailField(verbose_name='email',max_length=50,unique=True) #phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$') #phone = PhoneNumberField(unique=True,blank=False,null=False) phone = models.CharField(max_length=17,blank=True) REQUIRED_FIELDS = [ 'first_name', 'last_name', 'phone', 'username', ] USERNAME_FIELD = 'email' def get_username(self): return self.email class UserInfo(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) address = models.CharField(max_length=50) zipcode = models.CharField(max_length=20) def __str__(self): return str(self.user) my views is views.py class UserAdditionalView(generics.ListCreateAPIView): queryset = UserInfo.objects.all() serializer_class = UserAdditionalSerializers i'm trying to add more user info to database through the api.i used djoser for registering of user. whenever i try to add user through postman it throws IntegrityError . i cant find a solution -
how to redirect after delete obj?
i want to redirect to that URL : user/str:username after delete task so I set success_url='user-tasks' but after delete task error (Page not found (404) ) appear . so is there any other way to use success_url ? #-----------------------views.py----------------------- class UserDeleteView(LoginRequiredMixin,DeleteView): model=tasks success_url='user-tasks' # <==== does not work def test_func(self): task=self.get_object() if self.request.user == task.user: return True return False #----------------------------------------------------- #----------------------urls.py------------------------------------------------------- from django.urls import path from . import views from . views import TaskListView,TaskCreateView,TaskUpadteView,UserTaskListView urlpatterns = [ path('', views.TaskListView.as_view(),name='home-page'), path('task/new/', views.TaskCreateView.as_view(),name='create-task'), path('task/<int:pk>/update/', views.TaskUpadteView.as_view(),name='update-task'), path('task/<int:pk>/delete/', views.UserDeleteView.as_view(),name='delete-task'), path('user/<str:username>', views.UserTaskListView.as_view(),name='user-tasks') ] #------------------------------------------------------------------------------------ enter image description here -
From a django library can we overwrite only parts of a viewset instead of rewriting the viewset completely?
I am working with djoser and upon reading the documentation, I want to alter some parts of the code from Userviewset. I want to overwrite def me(self, request, *args, **kwargs) and customize it. For the get request, instead of returning all the fields of the model, I want to return only Username and Profile Picture. I tried doing from djoser.views import UserViewSet. Then, class UserViewSet(viewsets.ModelViewSet): # from djoser docs which I want to update @action(["get", "put", "patch", "delete"], detail=False) def me(self, request, *args, **kwargs): self.get_object = self.get_instance if request.method == "GET": return self.retrieve(request, *args, **kwargs) elif request.method == "PUT": return self.update(request, *args, **kwargs) elif request.method == "PATCH": return self.partial_update(request, *args, **kwargs) elif request.method == "DELETE": return self.destroy(request, *args, **kwargs) But I wonder this would work since neither retrieve nor get_instance are mentioned. Is there a shorter correct way to do this?