Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django left join and right join implemnt sqlite
I have 2 tables country id name 1 A 2 b 3 c state id | country_id | name | population 1 | 1 | x | 234354 2 | 1 | y | 2334 3 | 2 | h | 232323 4 | 2 | E | 8238787 Now i want query with sum poulation with country name like this a has xxxx population b has xxxx population c has 0 population in django query I have write this query City.objects.values('country__name').annotate(Sum('population')) but this has not display 0 for c country :( -
ModelForm has no model class specified Error in Django
This is my forms.py file!!! from django import forms from . models import URLModel class URLForm(forms.ModelForm): class Meta: model = 'URLModel' fields = ['url'] This is my models.py file from django.db import models # Create your models here. class URLModel(models.Model): url=models.URLField(unique=True) short=models.CharField(max_length=200,unique=True) def __str__(self): return self.url Now i just wanted to ask that why this error is coming and i have revieved and i cant observe any error for real...please help -
Can I safely use `self.request.user.is_authenticated` in views?
We are using Django 2.1 for Speedy Net. There is a view which I want to be different for admin (staff) than for regular users. I added the following (3 first) lines to the code: def get_user_queryset(self): if (self.request.user.is_authenticated): if ((self.request.user.is_staff) and (self.request.user.is_superuser)): return User.objects.get_queryset() return User.objects.active() But the problem is, one of the tests fails with an error message: AttributeError: 'WSGIRequest' object has no attribute 'user' (link) And I want to know - Is it safe to use self.request.user.is_authenticated in views? Should I fix the test to work or can my code fail in production? The test uses RequestFactory(), is there a problem with RequestFactory() not containing attribute 'user'? Or is there a problem with my code which may also fail in production? If I should fix the test, how do I do it? Here is the code of the test which fails: class UserMixinTextCaseMixin(object): def set_up(self): super().set_up() self.factory = RequestFactory() self.user = ActiveUserFactory(slug='look-at-me', username='lookatme') self.other_user = ActiveUserFactory() def test_find_user_by_exact_slug(self): view = UserMixinTestView.as_view()(self.factory.get('/look-at-me/some-page/'), slug='look-at-me') self.assertEqual(first=view.get_user().id, second=self.user.id) By the way, I'm not sure what is the purpose of slug='look-at-me' in the view = ... line of the test? -
Django forms: error not displaying in json
I am trying to set up my password forgot in Django using built-in validators, but I am getting no response if reproduce errors, but it supposed to show up the errors others classes, how can I fix this? forms.py class RestorePasswordForm(SetPasswordForm): new_password1 = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control','placeholder':'Password','required': True})) new_password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control','placeholder':'Password','required': True})) views def post(self, request,token): form = RestorePasswordForm(request.POST) if form.is_valid(): obj = token(token) if obj: this_user = User.objects.get(id=obj.email_id) if not this_user: return False this_user.set_password(request.POST.get('new_password2')) this_user.save() obj.token = None obj.save() return JsonResponse({"message":form.errors}) browser response display {"message": {}} -
Webpage not displaying body in chrome
Namaste! I hosted a website on pythonanywhere but body of some pages are not showing in some browsers like chrome while some browsers like opera and mobile browsers work fine. All the contents are there if I inspect elements. What am I doing wrong? Thanks! link: http://mmilann.pythonanywhere.com/ -
How do I program a django view to keep a chomedriver instance alive for conditional user input?
Backstory/Problem I have a web application that runs various jobs. One of these jobs includes running a python script that logs into linkedin. When I run the script an instance of headless chromium starts, navigates to the linkedin login page and submits the proper credentials. Everything works fine up to this point, but sometimes linkedin will send my request to a checkpoint url and prompt me to submit a special pincode sent to my email before I can proceed. I am having trouble understanding how to implement this conditional logic in my view; basically, I want to have a way where I can enter the pincode in my web application. Expected Outcome Run a script from django view to login to linkedin, and prompt user to enter pincode if checkpoint is reached, otherwise continue if no checkpoint is reached and login was successful. What I've tried Google - Couldn't find anything specific to my problem. Code below - The view below shows my current attempt. I know it can be done, but I'm not sure if I should be trying to build it out in a single view, or if I should try passing my chromium instance to another view … -
Edit specific values of a query using a method and join two queries
Basically I have a query B which contains different records from query A. They both are queries of the same model. I need to call a python function for each record in query B and save that data in query. I'd want to use annotate but not sure how to call the method itself, since the method is tied to the model instance. For instance I have a model House, which has a method get_price(parameter). So for every house in query B I have to call method obj.get_price(parameter) and add the return value of get_price to each house of query B as an attribute, parameter does not depend on the model instance itself. I've tried doing this but it does not work: for house in query_b: house.default_price = house.get_price(parameter) It just does not edit the query. How would I do this? Do take notice that I cannot just convert this query to a list as I need to later unionize query A & query B. -
Resizing images on input
I have some models defined and I'm trying to write a create_image() method. I don't want images to be any larger than 960x720 (or 720x960). I tried following this tutorial among others, but I can't quite get it right. Please look at my code and tell me what I can do differently. models.py from django.db import models from home.models import TimestampedModel from .managers import AlbumManager, ImageManager class Album(TimestampedModel): title = models.CharField(max_length=255) objects = AlbumManager() class Image(TimestampedModel): image = models.ImageField(upload_to='img/%Y/%m/%d/') album = models.ForeignKey(Album, on_delete=models.CASCADE) objects = ImageManager() managers.py class ImageManager(models.Manager): def create_image(self, **kwargs): from io import StringIO from PIL import Image # Validations (raise error) if 'image' not in kwargs and 'album' not in kwargs: raise TypeError("create_image() missing 2 required keyword arguments 'image' and 'album'") elif 'image' not in kwargs: raise TypeError("create_image() missing 1 required keyword argument 'image'") elif 'album' not in kwargs: raise TypeError("create_image() missing 1 required keyword argument 'album'") # Downscale image if necessary image = Image.open(kwargs['image']) imagefile = StringIO(image) width, height = image.size if width > height: max_width = float(960) max_height = float(720) ratio = min(max_width / width, max_height / height) width, height = (width * ratio, height * ratio) elif width < height: max_width = float(720) max_height … -
When I access the page first time, .is_valid return false
When I access the page the first time, .is_valid return false. How can I make it not to show False message? Why it shows False when I access the page first time? Is there any way to avoid the False message? urls.py is below from django.urls import path from . import views urlpatterns = ( path('', views.index, name='index'), ) views.py is below from django.shortcuts import render from . import forms def index(request): form = forms.Page1(request.GET or None) if form.is_valid(): message = 'True' else: message = 'False' content = { 'title': 'Webapp', 'form': form, 'message': message, } return render(request, 'forms.html', content) forms.py is below from django import forms EMPTY_CHOICES = ( ('', '-'*10), ) GENDER_CHOICES = ( ('man', '男'), ('woman', '女') ) class Page1(forms.Form): user_sir_name = forms.CharField( label='姓:', max_length=20, required=True, widget=forms.TextInput(), ) user_given_name = forms.CharField( label='名:', max_length=20, required=True, widget=forms.TextInput(), ) user_sex = forms.ChoiceField( label='性別:', widget=forms.Select, choices=EMPTY_CHOICES + GENDER_CHOICES, required=True, ) -
Django Failed to Import Test Module
Trying to run this test file on a simple Django pages app from the book Django for Beginners. The book suggested importing SimpleTestCase bc there are no databases involved. # pages/tests.py from django.test import SimpleTestCase class PagesTests(SimpleTestCase): def test_home_page_status_code(self): response = self.client.get('/') self.assertEqual(response.status_code, 200) def test_about_page_status_code(self): response = self.client.get('/about/') self.assertEqual(response.status_code, 200) And keep getting this error message: ERROR: pages.tests (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: pages.tests Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/loader.py", line 436, in _find_test_path module = self._get_module_from_name(name) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/loader.py", line 377, in _get_module_from_name __import__(name) ModuleNotFoundError: No module named 'pages.tests' ---------------------------------------------------------------------- Ran 3 tests in 0.000s FAILED (errors=3) (pages) bash-3.2$ python3 manage.py test System check identified no issues (0 silenced). EE ====================================================================== ERROR: pages.pages (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: pages.pages Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/loader.py", line 470, in _find_test_path package = self._get_module_from_name(name) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/loader.py", line 377, in _get_module_from_name __import__(name) ModuleNotFoundError: No module named 'pages.pages' ====================================================================== ERROR: pages.pages_project (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: pages.pages_project Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/loader.py", line 470, in _find_test_path package = self._get_module_from_name(name) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/loader.py", line 377, in _get_module_from_name __import__(name) ModuleNotFoundError: No module named 'pages.pages_project' Looks like django can't find the test module.... at … -
Django deleting entries from database
When i delete an entry from the Person table in SQLlite database, is there a way so that the ID changes to the number of entries in the table? For example, I deleted Id=5 but then there is a gap from Id=4 to Id=6 class Person(models.Model): firstname = models.CharField(max_length=200) def __str__(self): return self.firstname enter image description here -
Get instance of foreign key - Django Rest Framework
This is what I have: models.py class Subject(models.Model): name = models.CharField(max_length=50) schedule1 = models.CharField(max_length=30, default="No Schedule") schedule2 = models.CharField(max_length=30, null="No Schedule") def __str__(self): return self.name class Todo(models.Model): title = models.CharField(max_length=100) description = models.CharField(max_length=400) priority = models.CharField(choices=P_CHOICE, max_length=10) timestamp = models.DateTimeField(auto_now_add=True) completed = models.BooleanField(default=False) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) serializers.py class SubjectSerializer(serializers.ModelSerializer): id = serializers.ReadOnlyField() class Meta: model = Subject fields = '__all__' class TodoSerializer(serializers.ModelSerializer): id = serializers.ReadOnlyField() class Meta: model = Todo fields = '__all__' The problem that I have is that when I do a todo get request from the API, I want to show the todo subject name, but I'm getting the ID. Do I have to make another request using the subject ID, I see that not very performance friendly. Is there a way to get the Subject instance right from the todo.subject property? -
Django conditional only works after a hard refresh (shift + refresh)
I have a Django app that uses conditional logic to determine what to display in the navigation bar. For example, if the user is not authenticated --> show "Login", else --> "show username." It works perfectly in development but on my apache server, it seems to always execute the "else" block unless I do a shift+refresh in safari and chrome. It seems to only do this on my index page, on the other pages within the app the if/else works as expected. base.html {% if user.is_authenticated %} <a href="{% url 'login-signout' %}" id="account-link"> {% if user.username %} {{user.username | capfirst }} {% elif user.first_name %} {{user.first_name | capfirst }} {% else %} Account {% endif %} </a> {% else %} <a href="{% url 'login-signup' %}" id="account-link"> Login </a> {% endif %} I tried to just get a fresh copy of the project but I am getting the same results. Any idea why this might be happening? -
Django user matching design - maintain cross scoring table or calculate on the fly?
I am trying to provide an endpoint for matching a pool of users between each other based on their individual criteria. The criteria_ranking table is FK linked to the users table. Users regularly/occasionally updating their criteria_ranking values but are likely to call the list of ranking more frequently. I'm thinking of two different approaches. Generate NxN cross ranking table which gets updated each time a user changes criteria_ranking. Table grows exceptionally large as N increases. Could potentially crash server if many users update at the same time? Calculate ranking on the fly each time user requests for a list of highest ranked matches (usually with some additional filters to narrow down the compared rows). Possibility of multiple duplicate calculations but also goes easy on storage? Ideally I'd like to run the Gale-Shapley algorithm on the rankings after they are calculated. What would you do? Appreciate if you'd let me know if I'm looking at this wrong. -
I have main_project/templates directory to store base.html, but where do I store base.css?
So, as I said I have a base.html file located at main_project/templates/base.html, but where do I put the base.css file? Do I create a main_project/static directory or should I just put in main_project/templates? Thanks in advance for any responses. -
how to compress user uploaded image with Pillow in Django rest framework
how would you compress the image when the user uploads from PIL import Image class photo(models.Model): title = models.CharField(max_length=100) uploader = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) image_url = models.ImageField(upload_to='images', null=True) -
Is there a way I can optimize file size in python
I am working on a python project and i need to compress or optimize uploaded files in python to avoid high storage usage. -
Django generating foreign key relationship based on slug in url
First, English isn't my first language, and neither is Django. Let's say I have the model 'city' with a parent / foreign key relationship to a 'province' (each province can have multiple cities in it). models.py: class Province(models.Model): name = models.CharField(max_length=75, help_text="What province are you adding?", unique=True, default="") slug = models.SlugField(max_length=100, blank=True) class City(models.Model): province = models.ForeignKey(Province, on_delete=models.CASCADE) #Each city belongs to one province slug = models.SlugField(max_length=100, blank=True) A city can be added to a province via a CreateView. My relevant views.py looks like this: class AddCityView(CreateView): model = City form_class = CityForm def get_success_url(self): return reverse('app:provincedetail', kwargs={'slug' : self.object.province.slug}) And the relevant urls.py looks like this: urlpatterns = [ path('<slug:slug>/', views.ProvinceDetailView.as_view(), name='provincedetail'), #shows province information in more detail path('<slug:province>/add/', views.AddCityView.as_view(), name='addcity'), #add a city to a province ] So when a user goes to the province detail view, they can add a city pretty easily from there via a form. I think it would be redundant to have a field for the province in this form, it should just be automatically generated from when the user submits the city form. In my mind, this would be done through the url since the province slug is already in it. What … -
json.loads converts valid JSON to invalid JSON
I'm using django-rest-framework to validate some JSON received in my webhook and then I save some of the fields to my database. That mostly works now. The JSON comes from a third party and varies in format and isn't well documented. My view is therefore grabbing the complete JSON using json.loads and saving it in a separate table so that I have it to help me troubleshoot any requests that fail validation. However I'm finding that the JSON that gets returned by json.loads is slightly different to the JSON that the third party claims to be sending. The third party is sending strings and values in double-quotes but json.loads returns the same in single quotes. The third party is sending false and true values in lowercase but json.loads returns them capitalised, ie True and False. Thus making the JSON invalid. The serialisers are validating the JSON received in the webhook as valid. But if I take the same JSON post returned by json.loads and post it again using Postman then the serializers reject it as invalid. Is it normal for json.loads to return JSON formatted in this way with the invalid single quotes and capitalised True/False values? transaction_json_data = json.loads(request.body) -
How to use schedule with Django?
I would like to execute a task periodicaly in my Django application and I was looking at the schedule (link) Python package which looks relatively simple to use compare to more sophisticated solution like Celery. However when I initialize the module in apps.py the task is executed but my developement webserver stop working with error This site can’t be reached. What is the proper way to use this package with Django? This is how my code looks like: apps.py class MarketsdataConfig(AppConfig): name = 'marketsdata' verbose_name = _('marketsdata') def ready(self): import marketsdata.signals import marketsdata.cron_job cron_job.py import schedule import time def job(): print("I'm working...") schedule.every(10).seconds.do(job) while True: schedule.run_pending() time.sleep(1) -
Django context Datetime unique date
I have in my model one DateTimeField like this timestamp = models.DateTimeField(auto_now=True) I want to filter the displayed results in the template by date, but each date only once and the time not at all. in my views, def get_context_data(self, *args, **kwargs): context['Filter_date'] = Blog.objects.order_by().values('timestamp').distinct() return context in my html template: <form id="filter-form" method="GET" action=""> <select name="dt" id="date"> <option value="">Filter by Date</option> <option value="">All</option> {% for f in Filter_date %} <option value={{f.timestamp|date:"m-d"}}>{{ f.timestamp|date:"d. F" }}</option> <!-- date:"Y-m-d" --> {% endfor %} </select> <input type="submit" value="Filter"><p></p> </form> And later in the views I cach them like this: def get_queryset(self, **kwargs): querydate= self.request.GET.get('dt') start_date = "2020-"+querydate+" 00:00:00" end_date = "2020-"+querydate+" 23:59:59" print(start_date) #return Blog.objects.filter(Q(timestamp__icontains=querydate)) return Blog.objects.filter(Q(timestamp__lte='start_date',timestamp__gte='end_date')) In my template, I have now displayed the same date several times. January January January How can I display the date only once? -
Django Multiple GET requests in one single view
In my django app, in the index page it always recieved 2 get requests (same user who logged in). I noticed it when I'm looking in the command prompt. How can I handle that cause when it querying a model (that model is randomly generated) it query different item so that the system that I made is always broke! -
Django: How to import model from same app?
I've an app called lists. This has 3 main models: List, ListItem and School. Every list could be related to 1 school, or this field could be empty. But when I'm trying to update my model List to have a school field I'm getting: ImportError: cannot import name 'School' from 'lists.models' (D:\web_proyects\scolarte\lists\models.py) (scolarte) Even thought both models are in the same models.py file. I've tried: from .models import School And: from lists.models import School lists/models.py: from django.db import models from products.models import Product from roles.models import User from .models import School # Create your models here. class List(models.Model): LISTA_STATUS = ( ('recibida_pagada', 'Recibida y pagada'), ('recibida_no_pagada', 'Recibida pero no pagada'), ('en_revision', 'En revision'), ('en_camino', 'En camino'), ('entregada', 'Entregada'), ('cancelada', 'Cancelada') ) lista_id = models.CharField(max_length=100) name = models.CharField(max_length=100) user = models.OneToOneField(User, on_delete=models.CASCADE) school = models.OneToOneField(School, on_delete=models.CASCADE) status = models.CharField(max_length=20, choices=LISTA_STATUS, default='recibida_pagada') created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['created_at'] def __str__(self): return str(self.id) class ListItem(models.Model): lista = models.ForeignKey(List, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) comment = models.CharField(max_length=100, blank=True, null=True, default='') uploaded_at = models.DateTimeField(auto_now_add=True) step_two_complete = models.BooleanField(default=False) def sub_total(self): return int(self.product.price) class School(models.Model): name = models.CharField(max_length=100) address = models.CharField(max_length=100, blank=False) address_reference = models.CharField(max_length=100, blank=False) provincia = models.CharField(max_length=100, blank=False, null=True) canton … -
CKEditor SetData() is showing Raw HTML
I am currently using ckeditor in my Django project. setData() in inserting the text as raw html content. Any suggestion how to convert that raw HTML to rich text when setData() us used. Follwing command is used by me. CKEDITOR.instances.editor1.setData( "<%- data.description %>" ); -
How to serialize JSON with custom attribute name in Django Rest Framework
I need to validate the following JSON using Django Rest Framework Serializer: { "type": "profit", "value": 7200 } My Serializer is defined as: class SaleSerializer(serializers.Serializer): TYPE_CHOICES = [ 'profit', 'cost', ] type = serializers.ChoiceField(choices=TYPE_CHOICES) value = serializers.IntegerField(validators=[MaxValueValidator(limit_value=10000), MinValueValidator(limit_value=0)], allow_null=False) However, type is one of Python built-in so I don't want to use it for my Serializer. How can I define my serializer so that type in the input JSON would be serialized into sale_type for example?