Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Compare two dictionaries returned from REST framework using pytest
I am trying to test my django application with pytest. I am trying to send an object like so: { "x" :1 "y" :2 .... } What my view does, is returning a list of dictionaries, so in my scenario a list with this one sent dictionary. I want to check if my sent data equals my data when I do a get call. My problem is that the two dictionaries are always evaluated to false. This is what I am doing: def test_post_data_is_get_data(self): url = api_reverse('urlname') #I get the url data = sent_data #this is my dict I am sending defined as a big dict in my code response_create = client.post(url, data, format='json') # I save the response response_get = client.get(url) # I get the created data back print(type(response_create.data)) #debugging print(type(data)) print(type(response_create.content)) print(type(response_get)) assert response_create == response_get The types I am printing out is: <class 'rest_framework.utils.serializer_helpers.ReturnDict'> <class 'dict'> <class 'bytes'> Doesn't matter how I compare it is never the same. I tried comparing sent data with: 1) response_create.content == response_get.content 2) response_create.data == response_get.data 3) response_create.data == response_get[0] 4) response_create.data == response_get.first() ## error that byte like object has not attribute first Since I am calling a list view … -
Django - How to make a ForeignKey dropdown toggle-able when there are no options are available in it?
I'm fairly new to Django/python. I have a form that has a dependent dropdown. Based on which work area you choose, your options for station will change, but there are some work areas that do not have any stations, in which case I would like the station dropdown to just not show up, but I'm not sure how to approach this, if it's on the html side or the other forms.py class WarehouseForm(AppsModelForm): """ Warehouse tracking form fields """ class Meta: model = EmployeeWorkAreaLog fields = ('adp_number', 'work_area', 'station_number') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['station_number'].queryset = StationNumber.objects.none() if 'work_area' in self.data: try: work_area_id = int(self.data.get('work_area')) self.fields['station_number'].queryset = StationNumber.objects.filter(work_area_id=work_area_id).order_by('name') except (ValueError, TypeError): pass elif self.instance.pk: self.fields['station_number'].queryset = self.instance.work_area.stations.order_by('name') views.py class EnterExitArea(CreateView): model = EmployeeWorkAreaLog template_name = "operations/enter_exit_area.html" form_class = WarehouseForm def form_valid(self, form): emp_num = form.cleaned_data['adp'] area = form.cleaned_data['work_area'] station = form.cleaned_data['station_number'] if 'enter_area' in self.request.POST: form.save() return HttpResponseRedirect(self.request.path_info) elif 'leave_area' in self.request.POST: form.save() EmployeeWorkAreaLog.objects.filter(adp_number=emp_num, work_area=area, station_number=station).update(time_out=datetime.now()) return HttpResponseRedirect(self.request.path_info) def load_stations(request): work_area_id = request.GET.get('work_area') stations = StationNumber.objects.filter(work_area_id=work_area_id).order_by('name') return render(request, 'operations/station_number_dropdown_options.html', {'stations': stations}) Here the user only really fills out their # and select work area, so I was wondering if there's a way maybe within the div to make it … -
How to get a button to link to another HTML template in Django?
I'm new to Django, I'm trying to get a button on the homepage to link to another (as of right now) static page. I thought this was pretty simple, I've done frontend work before and a simple href to the file would be enough but for some reason its not linking. <h1> This is the homepage yay!</h1> <div class="container"> <button type="button" href="./scoringsheet.html" class="btn btn-1">Judges</button> <button type="button" class="btn btn-2">Students</button> </div> -
Trying to pass Bokeh Wordcloud2 to Django Templete
I am working on passing data visualization using Bokeh library to Django project. I am able to pass standard Bokeh visualization but when I am trying to used an external wordcloud2 library my project crashes. I receive message "A server error occurred. Please contact the administrator." Any ideas would be much appreciated?! Imports used: from bokeh.plotting import figure, output_file, show from bokeh.embed import components # Bokeh WordCloud from bokeh.io import show from bokeh.models import ColumnDataSource from bokeh_wordcloud2 import WordCloud2 views.py Code below is working: x = [1,2,3,4,5] y = [1,2,3,4,5] plot = figure(title='Line Graph', x_axis_label='x_stuff', y_axis_label='y_stuff', plot_width=400, plot_height=400) plot.line(x, y, line_width=2) auto_div - dynamically generates div elemetent script, auto_div = components(plot) Based on example above, I am trying to pass values for wordcloud in very similar way but it is not working: titles = ['lorem ipsum dolor sit amet', 'consectetur adipiscing elit', 'cras iaculis semper odio', 'eu posuere urna vulputate sed'] test1 = ColumnDataSource({'titles':titles}) wordcloud = WordCloud2(source=test1,wordCol="titles",color=['pink','blue','green']) script, auto_div = components(wordcloud) context = { 'script':script, 'auto_div':auto_div, } return render(request, 'two_boxes/home.html', context) Based on my testing it seems like the problem occurs at script, auto_div = components(wordcloud) statement home.html <head> {% block bokeh_dependencies %} <link href="http://cdn.pydata.org/bokeh/release/bokeh-1.3.4.min.css" rel=”stylesheet” type=”text/css”> <link href="http://cdn.pydata.org/bokeh/release/bokeh-widgets-1.3.4.min.css" rel=”stylesheet” … -
How to update a field in the model using ForegnKey lookup?
I need to be able to update a field num_places in the Event model accessing it via event ForeignKey in the Participant model when the last is saved. Here are my models.py: class Event(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=500) text = models.TextField() image = models.ImageField(blank=True) date = models.DateTimeField() price = models.PositiveIntegerField() num_places = models.PositiveIntegerField(default=50) slug = models.SlugField() class Participant(models.Model): name = models.CharField(max_length=200) participant_uuid = models.UUIDField(primary_key=False, verbose_name='UUID') email = models.EmailField() phone_regex = RegexValidator(regex=r'^\+7\d{10}$') phone_number = models.CharField(validators=[phone_regex], max_length=12) num_places = models.PositiveIntegerField(default=1) event = models.ForeignKey(Event, on_delete=models.CASCADE) paid = models.BooleanField(default=False) def __str__(self): return self.name def save(self, *args, **kwargs): try: self.full_clean(exclude=None) self.event.num_places -= self.num_places # the value isn't updated super().save(*args, **kwargs) self.valid = True self.non_field_errors = False except ValidationError as e: self.non_field_errors = e.message_dict[NON_FIELD_ERRORS] self.valid = False class Meta: unique_together = ('name', 'email', 'phone_number', 'event') The code with a comment has a problem: the num_places value in the Event model stays unchanged. How to fix it? -
Overriding __init__() in class-based form causing AttributeError ('str' object has no attribute 'get')
Each User in my Django application has a 1-to-1 relationship with a Profile object. I want to do some fancy crispy-forms display stuff in my ProfileUpdateForm. When I override init() in my ProfileUpdateForm class, the page breaks with an Attribute Error. I originally suspected the issue is because my users modify their profile at /u/update, with no in the url string. So perhaps the form was not receiving an existing Profile instance. In the traceback, I do see the profile I would expect, so maybe this is not the problem. In my class-based view, I've set get_object() to return self.request.user.profile, so that any user that visits u/update will only be able to update their own profile and not others. This works fine, but as soon as I try overriding init() in my class-based form, the update form breaks. Here's what we have: Form class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ('tagline', 'summary_text_public', 'summary_text_contacts') View class ProfileUpdate(LoginRequiredMixin, generic.UpdateView): form_class = ProfileUpdateForm template_name = 'profile/update.html' success_url = reverse_lazy('profile:redirect_to_self') def get_object(self): return self.request.user.profile URL Pattern path('update/', views.ProfileUpdate.as_view(), name='update'), The code above works as expected, users can update their profiles at u/update. When I add minimal init() code (below) to ProfileUpdateForm, it … -
defined a Form class, but django raised exception saying it is not defined
Followed instructions as on the page. to customize user profile while using django-allauth. Django/python saying it can't find the "SignupForm" class definition, which is clearly defined in the file forms.py in the users app as in the code below. Anyone has any idea what's going on? forms.py from django import forms from allauth.account.forms import AddEmailForm, BaseSignupForm from django.core.exceptions import ValidationError from django.conf import settings from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class SignupForm(BaseSignupForm): first_name = forms.CharField(max_length=30, label='Firstname') last_name = forms.CharField(max_length=150, label='Lastname') def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() class MyAddEmailForm(AddEmailForm): def clean_email(self): email = super().clean_email() if self.user.emailaddress_set.count() >= settings.USERS_EMAILS_MAX_COUNT: raise ValidationError('Number of related emails can be no more than %d.' % settings.USERS_EMAILS_MAX_COUNT) return email class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = (...) class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = (...) Error message is: File "D:\Python\Django\m4ever\users\admin.py", line 4, in <module> from .forms import CustomUserCreationForm, CustomUserChangeForm File "D:\Python\Django\m4ever\users\forms.py", line 3, in <module> from allauth.account.forms import AddEmailForm, BaseSignupForm File "C:\Users\Freedom\Anaconda3\envs\myvenv\lib\site-packages\allauth\account\forms.py", line 261, in <module> class BaseSignupForm(_base_signup_form_class()): File "C:\Users\Freedom\Anaconda3\envs\myvenv\lib\site-packages\allauth\account\forms.py", line 249, in _base_signup_form_class fc_classname)) django.core.exceptions.ImproperlyConfigured: Module "users.forms" does not define a "SignupForm" class -
Using django-tables2 form to send selection to another form - nothing saves?
I have a django-tables2 form that passes selected model items to a second form. The goal of the second form is to allow a user to edit values that will be applied to all the items. My problem is that the second form fails validation and then the input values don't get saved. How can I link these two forms and allow user input before the form tries to validate? image_list.html: <form method="post" action="{% url 'ExifReader:delete_image_list' %}"> {% render_table table %} {% csrf_token %} <button type="submit" style="margin-right:10px" class="btn btn-primary" name="edit_FAN">Edit Exif</button> <button type="submit" style="margin-right:10px" class="btn btn-danger" onclick="return confirm('Delete?')" name="delete_images">Delete Images</button> </form> Note: The delete_images button works fine. views.py: def delete_image_list(request): if request.method == 'POST': if 'delete_images' in request.POST: pks = request.POST.getlist('selection') # Delete items... elif 'edit_FAN' in request.POST: form = EditFANForm() pks = request.POST.getlist('selection') imgs = [] for pk in pks: ex = exif.objects.get(pk=pk) imgs.append(ex.image_id) if request.method == 'POST': print('POST') for img in imgs: print(image.objects.get(pk=img)) form = EditFANForm(instance=image.objects.get(pk=img)) if form.is_valid(): print('Valid') formS = form.save(commit=False) img.FAN = formS.FAN fromS.save() else: print('ERRORS: ', form.errors) return render(request, 'ExifReader/edit_fan_form.html', {'form': form, 'pks':pks}) When I click the button for "edit_FAN" from the table view, the EditFANForm renders correctly, I can enter values, get redirected back … -
Can we show Window Service with Django?
I very new in Django and i dont know its possible to show a list of windows service from a Server in web in Django I do this and admin the service with Python (STOP, START and RESTART) but i dont have any GUI or simmilar Thanks -
django debt listing and grouping
I use django, I have 2 questions 1 question: The following code includes the total debt and pays that users pay. But he brings the records twice. Can we group this? I grouped by "id" number again. Question 2: how can we show the result as json? He writes the results twice, he writes once. But there are two results {'customer': 54, 'totalDebtResult': Decimal('150.00'), 'totalreceivedAmount': Decimal('30.00')}, {'customer': 54, 'totalDebtResult': Decimal('150.00'), 'totalreceivedAmount': Decimal('30.00')}, {'customer': 55, 'totalDebtResult': Decimal('250.00'), 'totalreceivedAmount': Decimal('80.00')} {'customer': 55, 'totalDebtResult': Decimal('250.00'), 'totalreceivedAmount': Decimal('80.00')} class DebtListAPIView(ListAPIView): serializer_class = DebtCreateSerializer def get_queryset(self): result = Debt.objects.all().values('customer__id').distinct().annotate(totalDebt=Sum('totalDebt'), receivedAmount=Sum('receivedAmount')).order_by('customer__id') print(result) -
Django - How to make a ForeignKey field toggle if no options are available?
I'm fairly new to Django/python. I have a form that has a dependent dropdown. Based on which work area you choose, your options for station will change, but there are some work areas that do not have any stations, in which case I would like the station dropdown to just not show up, but I'm not sure how to approach this, if it's on the html side or the other forms.py class WarehouseForm(AppsModelForm): """ Warehouse tracking form fields """ class Meta: model = EmployeeWorkAreaLog fields = ('adp_number', 'work_area', 'station_number') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['station_number'].queryset = StationNumber.objects.none() if 'work_area' in self.data: try: work_area_id = int(self.data.get('work_area')) self.fields['station_number'].queryset = StationNumber.objects.filter(work_area_id=work_area_id).order_by('name') except (ValueError, TypeError): pass elif self.instance.pk: self.fields['station_number'].queryset = self.instance.work_area.stations.order_by('name') views.py class EnterExitArea(CreateView): model = EmployeeWorkAreaLog template_name = "operations/enter_exit_area.html" form_class = WarehouseForm def form_valid(self, form): emp_num = form.cleaned_data['adp'] area = form.cleaned_data['work_area'] station = form.cleaned_data['station_number'] if 'enter_area' in self.request.POST: form.save() return HttpResponseRedirect(self.request.path_info) elif 'leave_area' in self.request.POST: form.save() EmployeeWorkAreaLog.objects.filter(adp_number=emp_num, work_area=area, station_number=station).update(time_out=datetime.now()) return HttpResponseRedirect(self.request.path_info) def load_stations(request): work_area_id = request.GET.get('work_area') stations = StationNumber.objects.filter(work_area_id=work_area_id).order_by('name') return render(request, 'operations/station_number_dropdown_options.html', {'stations': stations}) enter_exit_area.html {% extends "base.html" %} {% block main %} <form id="warehouseForm" action="" method="POST" data-stations-url="{% url 'operations:ajax_load_stations' %}" novalidate > {% csrf_token %} {{ form.non_field_errors }} {{ form.source.errors }} … -
HTML not connecting with CSS correctly
In my Django project, I attempt connect HTMl to CSS. I have looked online and at other related problems on stack overflow, and still cannot get html and css to link together. I am also a complete newbie to frontend development. Here's my code (The css file is in the same directory as this file): <head> <link rel="stylesheet" href="signup.css" type="text/css"> </head> <div id="signuptext" class="pb-0"><span>Sign Up</span></div> CSS: #signuptext { font-size: 30px; } Error received: Not Found: /accounts/signup/signup.css I don't understand this error as my css file is in the same folder as the HTML file. Does anybody know whats wrong? Thank you. -
Render diagram of Django models including properties
I am successfully rendering diagrams of Django models with ./manage.py graph_models. I would like to include model properties as well. I completely understand that they are not a part of the database. However, I believe it might be helpful to have them in the diagram. So far, the box for each model contains pairs of field name - field type. My idea is that properties could be shown as property name - property. Is there a tool which supports such a feature? -
A simple Query having a times of 90ms (fetching usernames)
I'm trying to do a form for my users. In this form I need to get every usernames because the users will select one of them. forms.py getName= forms.ModelChoiceField(queryset=CustomUser.objects.values_list('username', flat=True) template.html {{ form.getName}} Django debug toolbar screenshot Here is the time with only 1 user. How comes it take so much time ? My page's loading speed goes from 80ms to 400ms with it. Thanks for the help ! -
ImportError: symbol __res_maybe_init version GLIBC_PRIVATE not defined in file libc.so.6 with link time reference
I'm running an installation script that installs a number of different python packages. The one that is getting stuck on is psycopg2. The script attempts to install version 2.6.1. But I run into the error: Error: could not determine PostgreSQL version from '10.10' I figured it has something to do with the version of psycopg2 that's incompatible with postgresql version 10.10. Is this an invalid conclusion? Assuming my conclusion of version incompatibility is correct I changed the installation version of psycopg2 to 2.7. By doing that the error above went away. However, when I run: python manage.py runserver 0.0.0.0:888 I get the error: File "/home/mark/.virtualenvs/nova/lib/python3.6/site-packages/django/contrib/postgres/apps.py", line 7, in <module> from .signals import register_hstore_handler File "/home/mark/.virtualenvs/nova/lib/python3.6/site-packages/django/contrib/postgres/signals.py", line 1, in <module> from psycopg2 import ProgrammingError File "/home/mark/.virtualenvs/nova/lib/python3.6/site-packages/psycopg2/__init__.py", line 50, in <module> from psycopg2._psycopg import ( # noqa ImportError: /home/mark/.virtualenvs/nova/lib/python3.6/site-packages/psycopg2/.libs/./libresolv-2-c4c53def.5.so: symbol __res_maybe_init version GLIBC_PRIVATE not defined in file libc.so.6 with link time reference This makes me think that, maybe version 2.6.1 is probably the version that I needed to use because it's complaining about psycopg2? How do I fix the problem such that I can run the Django development server without the above error? -
How to change the message icon if a message is received
I've built a chat app using Django Channels. To check messages I should click on the message icon (just like stackoverflow for example). I want to add the feature enabling to have these small red circles on the message icon indicating the number of messages not read and I don't even know what I should type on Google to look for this. Any suggestions ? Thanks! -
Django, Celery - periodic_task in random time
I'm trying to run my celery task at random intervals. How can I do it the easiest way? I tried to do the task this way, but it only calls my random function once. And then he always performs at a previously random time interval. tasks.py from celery.task.schedules import crontab from celery.decorators import periodic_task import random a = random.randint(1, 5) @periodic_task(run_every=(crontab(minute='*/%s'%a))) def get_all_weather_data(): print('This is my random number %s'%a) So I changed that a new random function would be called each time. It seems to me that it works well, but it is not very effective. def random_function(): a = random.randint(1, 5) return a @periodic_task(run_every=(crontab(minute='*/%s'%random_function()))) def get_all_weather_data(): print('This is my random function') Does anyone know a better way to call a random interval of 1 to 5 minutes in which the celery task will be done? Maybe there is some built-in function that I missed in the documentation? This seems to be a fairly common problem. Any help will be appreciated. -
How to validate if a field is not blank in a form when it's set Blank = True in the model
I have a model wich is filled in different steps by different forms. Fields that are not filled in the first step need to be set Blank = True so you can submit the form. When I try to fill those fields later, the form lets the user leave them blank, which is undesirable. How can I make them mandatory in the subsecuent forms? I've tried implementing a Validation method (clean_almacen) like the one below, but it does nothing. class RecepcionForm(ModelForm): def clean_almacen(self): data = self.cleaned_data['almacen'] # Check if the field is empty. if data == '': raise ValidationError(_('¡Seleccione un almacén!')) return data def clean_usuario(self): if not self.cleaned_data['usuario_recepcion']: return User() return self.cleaned_data['usuario_recepcion'] class Meta: model = Pedido fields = ['almacen'] Also, setting the field Blank = False and null = True will make this work, but it will make mandatory to assign a value to the field when you edit the object in the admin page (which is undesirable too). This is my code: models.py class Pedido(models.Model): nombre = models.CharField(max_length=40, help_text=_('Nombre del producto.')) referencia = models.CharField(max_length=20, help_text=_('Referencia del fabricante.')) cpm = models.CharField(max_length=20, default ='A la espera.',help_text=_('Código del CPM asignado a este pedido.'), null = True, blank = True, verbose_name = … -
Django - Best way to create snapshots of objects
I am currently working on a Django 2+ project involving a blockchain, and I want to make copies of some of my object's states into that blockchain. Basically, I have a model (say "contract") that has a list of several "signature" objects. I want to make a snapshot of that contract, with the signatures. What I am basically doing is taking the contract at some point in time (when it's created for example) and building a JSON from it. My problem is: I want to update that snapshot anytime a signature is added/updated/deleted, and each time the contract is modified. The intuitive solution would be to override each "delete", "create", "update" of each of the models involved in that snapshot, and pray that all of them the are implemented right, and that I didn't forget any. But I think that this is not scalable at all, hard to debug and ton maintain. I have thought of a solution that might be more centralized: using a periodical job to get the last update date of my object, compare it to the date of my snapshot, and update the snapshot if necessary. However with that solution, I can identify changes when objects … -
Speed up queryset with aggregate in Django Orm
I'm waiting for quite long time before i get report in my project(written in Django = 2.2, python=3.7). i have complicate Model schema, and in my report i'm actually want to get users' information for particular tasks. I have find what part of my code making me wait so long and can't update it myself I've tried to change Aggregate function to annotate, but it works even longer. I've researched in Django documentation and googled for better approaches but couldn't find any good information how to modify existing code. I've also tried to add index=True to Model ,which I'm often work with when i get reports, but didn't succeed too. def make_report(self, worklogs, project, date_range_list, from_date): report = {} current_date = for d in date_range_list: report[str(d.date())] = {} for user in tasks.user.iterator(): current_user_usernames = user.get_board_usernames() #here is the problems begin **report[d.strftime('%Y-%m-%d')][user.id] = ( worklogs.filter(username__in=current_user_usernames) .filter(timestamp__range=(from_date, from_date + datetime.timedelta(days=1))) .aggregate(Sum("seconds"))["seconds__sum"] or 0 )** # each iteration takes quite long time current_date = current_date + datetime.timedelta(days=1) return report I'm waiting about 8-10 seconds for small tasks , and till couple of minutes for very big tasks. -
Django - How I can populate data in a model from another table/model in the same database?
I have a form that once is filled out, I'd like for it to cross-check the Employee # with another model's data and if the person exists, then the name would be automatically populated with the matching person once the entry is submitted. Currently I have this, but I'm not sure how to check for the number and then take the name of the person and copy it elsewhere. models.py class EmployeeWorkAreaLog(models.Model): employee_name = models.CharField(max_length=25) employee_number = models.IntegerField(max_length=50, help_text="Employee #", blank=False) work_area = models.ForeignKey(WorkArea, on_delete=models.SET_NULL, null=True, blank=False, help_text="Work Area", related_name="work_area") station_number = models.ForeignKey(StationNumber, on_delete=models.SET_NULL, null=True, help_text="Station", related_name="stations", blank=True) time_in = models.DateTimeField(help_text="Time in", null=True, blank=True) time_out = models.DateTimeField(blank=True, help_text="Time out", null=True) def __str__(self): return self.employee_number and I have another model in the database which stores current employees with their names and ID #'s, which looks sorta like this. class Salesman(models.Model): slsmn_name = models.CharField(max_length=25) adp_number = models.IntegerField(max_length=6) ... This is my views too, just in case. I created a function which returns the employee name from the database that has it, but I'm not sure how to use it of if there's another way to approach this. class EnterExitArea(CreateView): model = EmployeeWorkAreaLog template_name = "operations/enter_exit_area.html" form_class = WarehouseForm def form_valid(self, form): emp_num … -
Django: manage.py loaddata is returning 'Deserialization Error'
So when I try to load data into my models from my .json file from cmd, it is giving me this error: It seems to be a problem with the 'category_id' but I'm not sure how I go about fixing this issue. Here is my code: shop/models.py from django.db import models from django.urls import reverse # Create your models here. class Category(models.Model): name = models.TextField() products = models.ManyToManyField('Product') def get_products(self): return Product.objects.filter(category=self) def __str__(self): return self.name def get_absolute_url(self): return reverse('product_list_by_category',args=[self.id]) class Product(models.Model): name = models.TextField() description = models.TextField() stock = models.IntegerField() price = models.DecimalField(max_digits=10,decimal_places=2) image = models.ImageField(upload_to='images/', blank=True) def __str__(self): return self.name shop/views.py from django.shortcuts import render, get_object_or_404, redirect from .models import Category, Product from django.db.models import Count from django.contrib.auth.models import Group, User from django.core.paginator import Paginator, EmptyPage, InvalidPage def product_list(request, category_id=None): category = None products = Product.objects.all() ccat = Category.objects.annotate(num_products=Count('products')) if category_id: category = get_object_or_404(Category, id=category_id) products = products.filter(category=category) paginator = Paginator(products, 3) try: page = int(request.GET.get('page', 1)) except: page = 1 try: products = paginator.page(page) except(EmptyPage, InvalidPage): products = paginator.page(paginator.num_pages) return render(request, 'products.html', {'products': products, 'countcat':ccat}) And this are the two .json files I wish to load into my database (worth noting that createcategories.json worked without issue) createcategories.json … -
How to contextualy cache class method result in Python
I have a django model which implement a method performing database queries. During an import process, This method will be called in different part of the code. I want to avoid multiple database queries because I know the result will be the same during the import process. This method would be called in many parts of the code and it would be difficult for me to do dependencies injection. I'm seeking for a way to do that using a context manager but may be it's not the best option : class OrganizationSettings(models.Model): year = models.IntegerField() @classmethod def for_year(cls, year): return cls.objects.get(year=year) class CacheOrganizationSettings(): def __init__(): # ??? pass def __enter__(self): # ??? pass def __exit__(self, type, value, traceback): # ??? pass def process(): # Somewhere in the (deep)code this is called many times : settings = OrganizationSettings.for_year(2018) # No cache used (query at each call) process() # With cache (query, one by year) with CacheOrganizationSettings(): process() -
Django query duplicated 2 times in form
I'm trying to do a signup form for my django website. There is 3 fields : Username, password and Race. With my code, the django debug toolbar tells me : (4 queries including 2 similar and 2 duplicates ) The problem is only with "Race", deleting it in the template solve the problem. How can I get rid of the duplicates, and how to only call the names ? forms.py class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = ('username', 'race',) def __init__(self, *args, **kwargs): super(UserCreationForm, self).__init__(*args, **kwargs) ...... views.py def signup(request): if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): ....... else: form = CustomUserCreationForm() return render(request, 'signup.html', {'form': form}) signup.html <form method="post"> {% csrf_token %} {{ form.non_field_errors }} {{ form.subject.errors }} .... {{ form.username }} ..... {{ form.password1 }} .... {{ form.race }} <button>Sign up</button> </form> I want the user to be able to select the race name, but with my code I'm guessing it call the whole thing with the values linked to it, when I only want the name. Thanks for the help -
Images are not shown on my heroku website. static files are loaded fine
In my website static files are loaded without problem. But media files under Training.image.url containing images are not loading. I tried looking for solution online and on this forum as well but no solution. Following are small portion of my files. settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'portfoliodb', 'USER': config('DB_USER'), 'PASSWORD': config('DB_PASSWORD'), 'HOST': 'localhost', 'PORT': config('DB_PORT'), } } ------------------------------------------------------- STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'portfolio/static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py file urlpatterns = [ path('admin/', admin.site.urls), path('', Trainings.views.home, name = 'homepage'), path('blog/', include('Blog.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)