Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Slow loading basic page in development environment in Chrome - but fast in incognito mode
I've been working on my first Django app, installing gunicorn and making various changes to deploy it to staging. Somewhere along the way, my app has slowed down tremendously in Chrome in my development environment. When I go to 127.0.0.1:8000 in a normal tab in Chrome, it often takes >30 seconds to load a simple homepage with some bootstrap static assets. I can see in the logs that occasionally a worker times out. If I do the same in an incognito tab in Chrome, it's lightning fast. Or if I try a different browser. To solve the issue, I've gone into Settings --> Site Settings to clear cookies and data associated with 127.0.0.1. But this hasn't had any effect. I tried also using Chrome NetLogs. Admittedly I'm out of my depth in reading these, but in the timeline, I could see what looked like about 30 seconds of a URL request waiting for a response? I'm unsure exactly when the slowdown started. It might be when I switched to gunicorn. It might be something related to when I was messing around with security settings prior to deployment (I think I tried looking at the site using https locally at one … -
VSCode Python and Django remote execution/interpritation
I have VS Code Insider running the newer extension of Remote SSH. SSH is established. I can open remote workspace, remote files over ssh connection established to the Linux system. Here the VScode only acts as an editor because I can open and edit the files but can't compile/execute them on that remote server and see the output. How do I get python and Django projects executed/interpreted remotely? -
Database design for django application
I have a problem to make it easier : I have a relation like user -> Hotel - > Rooms . User can create Hotel and then every hotel can have many rooms . Now I have a user model like class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company_name=models.CharField(max_length=50, null=False, blank=False) email=models.CharField(max_length=50, null=False, blank=False) company_number=models.CharField(max_length=50, null=False, blank=False) and to create restaurant class Restaurant(models.Model): rest_owner = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name='rest_owner') name = models.CharField(max_length=50, null=False, blank=False) address = models.TextField(max_length=100, null=False) city = models.CharField(null=True, max_length=50) country = models.CharField(null=True, max_length=30) and now room class Room(models.Model): rest_owner = models.ForeignKey(Restaurant, on_delete=models.CASCADE, related_name='rest_owner') name = models.IntegerField() Rooms = models.IntegerField() is that a good approach to do this ? and to save images of room and restaurant Should I make a class Image(models.Model): image = models.ImageField(null=False, upload_to='Gallery') and then use in room and restaurant like images = models.ManyToManyField(Image) ? . I need to know best ways to doing both of these . thanks -
Django and Tkinter conectivity?
So i am creating an application with Tkinter on python, now i need to connect to an API sending a json object and retrieve the ID for that object (this connects to an incident management API, so im sending the json with the incident information i need to retrieve the incident number and display) At the end of the day what i am attempting is to get the information from MySQL(this is already working on my app) then generate the json file(already working on the app), and then send it over to the API. For this last part of it i am considering the use the HTTP functions of django(POST and GET). Yet for some reason my gut says this is not the best way to do it, hence i am looking for advise on what would be the best way to make it possible. PD: i am using a library called request in python, but this is definitely not enough for this. -
Accessing variable context name in template
I'm just discovering Django and i'm still a total noob. I got a view that return multiple query set. class RouteDateView(ListView): model = Tblsummary template_name = 'reviewrouteassess/selectdaterange.html' def get_context_data(self, *args, **kwargs): context = super(RouteDateView, self).get_context_data(*args, **kwargs) context['allroute'] = Tblsummary.objects.filter(off_no=self.request.GET.get('depotcode')[:4]) for p in context['allroute']: context[p.res_route] = Tblsummary.objects.filter(res_route=p.res_route) return context Then in my template I would like to access those dynamically name context. That's where i'm stuck. <table> {% for a in allroute %} <tr> <td>{{ a.res_route }}</td> <td>{{ a.hcalls }}</td> </tr> {% for d in a.res_route %} <tr> <td>{{ d.res_route }}</td> <td>{{ d.hcalls }}</td> </tr> {% endfor %} {% endfor %} How can I evaluate a.res_route so that a.res_route return the context passed by the view?? Thanks you so much!! {% for d in a.res_route %} -
How can I log information about a GraphQL request in Graphene Django?
Currently, Django logs: [16/Dec/2019 13:29:16] "POST /graphql HTTP/1.1" 200 1735 for any incoming graphql request. I'd like to be able to log more information about the incoming request (which queries, mutations, etc it is running). Is there a standardized way to do this, or should I just write my own middleware? -
Hierarchical Router Django Rest
So I have a Django project in which each app manages some type of a data table. Thus all of them follow a similar format in which there is a Table and Item model, each with an accompanying serializer and viewset. I'd like my apps to function such that there is no naming conflict between models of the same name in different apps. I would also like the router to act in a hierarchy first listing all the apps in the renderer in the form of /api/{app} and once you click it will give you the viewsets such as: /api/{app}/table /api/{app}/item I've tried playing around with DefaultRouter and SimpleRouter but couldn't really managed to get anything to work properly. -
Django AbstractUser vs Profile
Model design considerations Think carefully before handling information not directly related to authentication in your custom User Model. It may be better to store app-specific user information in a model that has a relation with the User model. That allows each app to specify its own user data requirements without risking conflicts with other apps. On the other hand, queries to retrieve this related information will involve a database join, which may have an effect on performance. The AbstractUser model provides the fields first_name and last_name and since that's related to the profile and not authentication why does AbstractUser model provides it? Should I extend the AbstractUser or create a Profile model? It feels wrong extending with Profile and include the user first and last name on the authentication table. What should I do? -
anchor tag doesn't submit items to cart python django
I have a dashboard of items displayed from my uniform model. I am attempting to send the item to a cart for checking out the item. I am not having issues loading my internal server, and I am getting no debugging issues. But when looking at my admin Order Item model, nothing has been pushed to it: views.py # add to cart def add_to_cart(request, slug): item = get_object_or_404(Uniform, slug=slug) order_item = OrderItem.objects.create(item = uniform) order_qs = Transaction.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] if transaction.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() else: transaction.item.add(item) else: ordered_date = timezone.now() order = Transaction.objects.create(user=request.user, ordered_date = ordered_date) order.items.add(order_item) messages.success(request, "Added to cart!") return redirect('apparelapp:item_list') models.py #OrderItem class OrderItem(models.Model): uniform = models.OneToOneField(Uniform, on_delete = models.PROTECT) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField(null = True) quantity = models.IntegerField(default = 1) def __str__(self): return self.uniform.description #Item class Uniform(models.Model): category = models.CharField(choices = CATEGORY_CHOICES, max_length=11) description = models.CharField(max_length = 50) price = models.FloatField(max_length = 6) size = models.CharField(choices=CLOTHES_SIZE, max_length=4, blank=True) style = models.CharField(choices=STYLE_CHOICES, max_length=15, blank=True) image = models.ImageField(upload_to='uniforms/') slug = models.SlugField() class Meta: ordering = ['category'] def __str__(self): return '{}: {} - {} - ${}'.format(self.category, self.description, self.size, self.price) def add_to_cart_url(self): return reverse("apparelapp:add_to_cart", slug=slug) html <h2>List of items</h2> <section class="text-center mb-4"> <div … -
Why is the email not saving on user sign up?
I went to test the user sign up but it keeps telling me UNIQUE constraint failed: users_customuser.email. That's because the email isn't saving with the rest of the form. I checked the database with an inspector and it shows a blank email field. The view looks fine so it doesn't make sense to me. Should I just switch to django 2.2? views.py def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = SignUpForm() return render(request, 'user_accounts/signup.html', {'form': form}) forms.py class SignUpForm(UserCreationForm): email = forms.EmailField(max_length=254, help_text='Enter a valid email address') class Meta: model = CustomUser fields = ('username', 'password1', 'password2') signup.html {% block content %} <h2>Sign up</h2> <form method="post"> {% csrf_token %} {% for field in form %} <p> {{ field.label_tag }}<br> {{ field }} {% if field.help_text %} <small style="color: grey">{{ field.help_text }}</small> {% endif %} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </p> {% endfor %} <button type="submit">Sign up</button> </form> {% endblock %} -
Authentication with REST Framework Django
I'm new to Django and curious how the authentication of Rest Framework works. So as I understand, the flow of authentication is: Frontend sends request with username and password > Backend (Django) sends back token > From then on frontend send this token in header to authenticate. But because anyone can see the header I send, so how is this safe? -
Pass save parameter through Django create method
Let's say I have the following Django model, which overrides the save method: class Person(models.Model): name = models.CharField(max_length=50) def save(self, lock=False, *args, **kwargs): if lock: print("LOCKING OBJECT...") super().save(*args, **kwargs) I know I can create a person and pass lock to the save method like so: steve = Person(name="Steve") steve.save(lock=True) # LOCKING OBJECT... However, I really enjoy using the create method, as it's much more readable: Person.objects.create(name="Michelle") How can I pass lock using the latter approach? The following doesn't work: Person.objects.create(name="Michelle", lock=True) # TypeError: Person() got an unexpected keyword argument 'lock' -
DJANGO Insert Data Into Form Field
What i am trying to accomplish is insert the Word "YES" into my field if the following condition is met. if K8Points.objects.filter(student_name=studentpsid).exists() and K8Points.objects.filter(time_frame='9:30AM - 10:00AM' ).exists() and grand_total >= 20: Then once the field is filled in with the word YES. The form is considered valid and will save. How do i do this ? Thanks Full Code def Student_Progress(request, studentpsid): if request.method == 'POST': form = K8Points_Score(request.POST) studentid = Student.objects.get(studentpsid=studentpsid) date = datetime.date.today() academic = K8Points.objects.values_list('academic', flat = True).filter(student_name_id=studentpsid) behavior = K8Points.objects.values_list('behavior', flat = True).filter(student_name_id=studentpsid) academic_total = 0 behav_total = 0 for score in academic: academic_total += int(score) for score in behavior: behav_total += int(score) grand_total = academic_total + behav_total counseling = Student.objects.values_list('counseling_goal', flat = True).get(studentpsid=studentpsid) if K8Points.objects.filter(student_name=studentpsid).exists() and K8Points.objects.filter(time_frame='9:30AM - 10:00AM' ).exists() and grand_total >= 20: if form.is_valid(): morning_recess = form.cleaned_data.get(morning_recess= "YES") form.save return render(request, 'points/student_progress.html', {'form': form,'studentid': studentid ,'date':date, 'counseling': counseling, 'grand_total':grand_total, 'academic_total': academic_total, 'behav_total': behav_total,'morning_recess': morning_recess } ) elif K8Points.objects.filter(student_name=studentpsid).exists(): form = K8Points_Score() studentid = Student.objects.get(studentpsid=studentpsid) date = datetime.date.today() academic = K8Points.objects.values_list('academic', flat = True).filter(student_name_id=studentpsid) behavior = K8Points.objects.values_list('behavior', flat = True).filter(student_name_id=studentpsid) academic_total = 0 behav_total = 0 for score in academic: academic_total += int(score) for score in behavior: behav_total += int(score) grand_total = academic_total + … -
Using Pytest to test an 'if statement' in a DJango module
This is the environment settings.py from decouple import config STEMMER = config('STEMMER', default = 'porter') views.py from my_project import settings from nltk import PorterStemmer, LancasterStemmer if settings.STEMMER == 'porter': stemmer = PorterStemmer() elif settings.STEMMER == 'lancaster': stemmer = LancasterStemmer() def one_function(): """Do some stuffs with the stemmer""" def another_function(): """Do another stuffs with the stemmer""" The question is how to create a test using Pytest that covers both cases? Thanks in advance -
How to catch specific ValidationError in Django form
I have a django form in which the user can submit a form to create a new item. There are a few error conditions which return different JsonResponses. I'm wondering if I can catch a specific validation error without checking the string contents of the error. The two errors I am checking for are either if the fields are not all filled out, or if the item name has an invalid length (there's a max of 25 characters). To better explain, here is a snippet of my code: form = ItemForm(request.POST) if form.is_valid(): item = form.save() return JsonResponse({item: item.to_json()}) else: if "has at most" in str(form.errors): return JsonResponse({ "error": "Invalid Length", "message": "Ensure the category name is within the given length" }) else: return JsonResponse({ "error": "Invalid", "message": "Please fill out all of the fields." }) This code does currently work, but obviously I would like to avoid this hack where I am checking the contents of the error in the string. Any help would be appreciated. Thanks! -
Placeholder in django form dropdown field
I have a little problem with a dropdown field in django form. I want to add to this field placeholder (or not active first option as placeholder) and some other stuff as no label, class etc. I wrote something like this, in my forms.py but now my form is broken - don't save values to database. from .models import Scenario, ScenarioArea from django import forms class newScenario(forms.ModelForm): scenarioArea=forms.ModelChoiceField(label="", queryset=ScenarioArea.objects.values_list("scenarioAreaName", flat=True).distinct(), empty_label=None) lass Meta: model = Scenario fields = ['scenarioArea'] Every other field type is working, but not this dropdown... Could you help me? -
keyerror:django line 66, in __getitem__
I used pycharm to build a URL shortener using Django 3.0 but when I imported django_hosts it caused the following error. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\wiwek\wirr\lib\site-packages\django\template\utils.py", line 66, in getitem return self._engines[alias] KeyError: 'django' my project files are below: from django.contrib import admin from django.urls import path, re_path from shortner.views import wirrcbview, wirrcfview,testview urlpatterns = [ path('admin/', admin.site.urls), path('about/', testview), re_path(r'^a/(?P<shortcode>[\w-]+){6,15}/$', wirrcfview), re_path(r'^b/(?P<shortcode>[\w-]+){6,15}/$', wirrcbview.as_view()), ] -
How to return current date and time from timepicker?
I have a form that uses a datetimepicker, however, I realized that, most of the time, the user will be submitting only a timestamp, and not really a date, unless an admin creates a record which is from a different page, so they shouldn't have access to change it themselves. I changed the datetimepicker to be a timepicker, so that it is less complicated to use. However, we have all the logic set to work with datetime, and timepicker only returns the time. Is there a way I can change the timepicker so that it returns today's date along with the actual time they are submitting, but without modifying the base timepicker? It is used in other pages so I would rather not mess with other parts, but not sure how I can achieve this. I just need general guidance and I am working with custom made datetimepickers that use the django ones as a base, but I cannot modify the existing ones. -
what is the best django shared hosting?
hi i want to ask what is the best django shared hosting i need : 1- Unlimited space (ssd ) 2- Unlimited bandwidth 3- Unlimited mysql and encrypt so any idea ? * i tried a2 hosting but i don't understand how to setup the project -
Can't get data in the template from a model associated with one-to-many relationship
I'm new to programming and I'm stuck in this problem. Thanks in advance. I have the following models in a one to many relationship: 1) Paciente Model: class Paciente(models.Model): nome = models.CharField(max_length=100) cpf_paciente = models.CharField(unique=True, max_length=100) 2) Processo Model: class Processo(models.Model): cid = models.CharField(max_length=6) paciente = models.ForeignKey(Paciente, on_delete=models.CASCADE, related_name='processos') usuario = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) paciente = models.ForeignKey(Paciente, on_delete=models.CASCADE, related_name='processos') The view that performs a QuerySet: @login_required def renovacao_rapida(request): if request.method == 'GET': busca = request.GET.get('b') usuario = request.user.pk pacientes = Paciente.objects.filter( (Q(nome__icontains=busca) | Q(cpf_paciente__icontains=busca)) & Q(usuario_id__in=Usuario.objects.filter(id=usuario)) ) contexto = {'pacientes': pacientes} return render(request, 'processos/renovacao_rapida.html', contexto) else: pass And the template rendered by the View: <ul> {% for paciente in pacientes %} <li> {{ paciente.processos }} </li> {% endfor %} My goal is to show in the template the Processo assigned to Pacientes. Although there are processos assigned to pacientes in the DB, I get in the Template the following output: processos.Processo.None processos.Processo.None ...... Whereas when I try {{ pacientes.usuario }}, the output is as expected: User1 User2 ... -
Convert url to file path and class name in Django
First, I'm new to Django so apologies if this is a simple question. For my site, I'd like to be able to extend it without adding lots of new url patterns. My thought was that I could use the url to form the filename that contains the class and then also use it as the class name to call. I'm basing the design off of https://stackoverflow.com/a/6073714/10230283 but there was no example provided. Just the idea. For example let's say all my extended pages will be have the url form 'http://example.com/extended/section/part' So the urlpattern would match anything starting with 'extended' like below. urls.py urlpatterns = [ ... url(r'^extended/', ExtendedHandler.as_view()), ... ] Then in the ExtendedHandler function, it should parse the request.path, load 'section.py' using import and then use the 'part' as the class that needs called. This is the piece I'm having trouble with. It may not even be the best solution so I'm open to suggestions. extended_handler.py class ExtendedHandler(View): def get(self, request): # if request.path is 'extended/section/part' then # treat the 'section' part as the file (i.e section.py) # and use the 'part' part as the class that should # actually be called or redirected to. return redirect() -
Solving the Error " TypeError at /editprofile/ context must be a dict rather than set."
I got some troubles with solving of "TypeError at /editprofile/ context must be a dict rather than set." in my Django project. I'm trying to allow the users to edit their personal information but I keep getting an error. I tried to read everything here and in other pages but nothing has helped, I would love to know how to solve this if anyone could direct me or give me some tips on how to fix this. forms.py class EditProfileForm(UserChangeForm): class Meta: model = User fields = ( 'username', 'email', 'country' ) views.py def editprofile(request): if request.method == 'POST': form = EditProfileForm(request.POST, instance=request.user) if form.is_valid(): form.save() return render(request, 'movies_app/profile.html') else: form = EditProfileForm(instance=request.user) args = {'form', form} return render(request, 'movies_app/editprofile.html', args) editprofile.html {% extends 'base.html' %} {% block head %} <title>Edit form</title> {% endblock %} {% block body %} <form action="." method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> {% endblock %} -
How to fill a form field based on another field in Django template using Ajax+jQuery
I am trying to populate the unit of measure field based on a product selected by the user using a dropdown. In my products model each product has been assigned a unit of measure and I am trying to autofill the unit field during order creation. I am using jQuery to pick up the product by and capturing the event .on('change'). In my endeavour to complete the scenario, I have tried to use this example code here . In the example, we are checking if a particular name entered by a user exists or not using Ajax calls sent to the database, which I have been able to replicate. What I am unable to get around to, is picking up the related field value "unit of measure" on selection of a "product". What would be the correct way to send Ajax call to the database to pick up associated value of unit of measure based on selection of the product? -
Using custom query to return JSON in Django Rest Framework
I started to work with Django rest and I want to know: Can I make a View or something else to make a custom query and return a JSON? -
Why is my form generating a KeyError instead of raising ValidationError from forms?
I have a form that has three main fields which are required. These fields are ForeignKey fields. the second and third are dropdowns, the third being a dropdown that is dependent on the second field data. When I submit the form fully filled out, it works. If I submit the first and second field, with the third empty, when it should have something selected, it does raise the ValidationError, however when I submit the form with just the first field filled out, it creates this error, instead of raising the ValidationError KeyError at /operations/enter-exit-area/ 'work_area' Request Method: POST Request URL: http://localhost:8000/operations/enter-exit-area/ Django Version: 2.1.5 Exception Type: KeyError Exception Value: 'work_area' Exception Location: operations\forms.py in clean, line 23 models.py class WorkArea(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Station(models.Model): work_area = models.ForeignKey(WorkArea, on_delete=models.CASCADE, related_name="stations") name = models.CharField(max_length=50) def __str__(self): return self.name class EmployeeWorkAreaLog(TimeStampedAuthModel, SoftDeleteModel, models.Model): employee_number = models.ForeignKey(Salesman, on_delete=models.SET_NULL, help_text="Employee #", null=True, 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(Station, on_delete=models.SET_NULL, null=True, help_text="Station", related_name="stations", blank=True) forms.py class WarehouseForm(AppsModelForm): class Meta: model = EmployeeWorkAreaLog widgets = { 'employee_number': ForeignKeyRawIdWidget(EmployeeWorkAreaLog._meta.get_field('employee_number').remote_field, site, attrs={'id':'employee_number_field'}), } fields = ('employee_number', 'work_area', 'station_number', 'modified_in', 'modified_out') def clean(self): cleaned_data = super().clean() emp_num = …