Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Duplicated models with Djnago admin
For a specific model I use Django admin interface. I implemented custom validation (clean methods) and save method. So, I have something like this: class DailyActivitiesAdmin(admin.ModelAdmin): form= MyCustomFormForm def save_model(self, request, obj, form, change): .... my custom save .... class MyCustomFormForm(forms.ModelForm): .... def clean(self): ... my custom validation ... def clean_my_field(self): ... my custom field validation ... My question is: Have I to manage explicitly the transaction from validation to save model or the atomicity is already managed in Django admin? A my customer reported me a bug about it: Into my clean validation I implemented a check to avoid similar models; Sometime he can create model duplicated. I think that probably he make more click on save button and probably he had a slowly internet connection. It is a possible scenario? Can I void it? For example, Can I disable the save buttons during the save requests? Can I guarantee atomicity in some way if it is not already managed? PS: I use Python 3, Djnago 2 and Postgres -
How to change date format for Django logging?
The comments in the answer here say that you should be able to customize the date format for logging in Django: Note that if you're using the dictConfig method of configuring logging (e.g. if you're using Django), you can set this using the 'datefmt' dict key for a formatter. See: Django Logging Configuration , logging module: Dictionary Schema Details However, it does not work: # settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'django.server': { # duplicate of default for django.server '()': 'django.utils.log.ServerFormatter', 'format': '[{server_time}] {message}', 'style': '{', 'datefmt' : '%Y-%m-%d %H:%M:%S' } } This does not work either: # settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'default': { 'datefmt' : '%Y-%m-%d %H:%M:%S' }, } In both cases, I still get the default logging date format: [13/Mar/2019 21:53:05] "GET / HTTP/1.1" 200 16808 Note that in the source code, the datefmt should have been passed on and used, but it appears that this is not the case: https://github.com/django/django/blob/782d85b6dfa191e67c0f1d572641d8236c79174c/django/utils/log.py#L190 Using Python 3.6 and Django 2.1 -
DRF and Django Filters - filter releated objects
I've got two models: class User(models.Model): name = models.CharField(max_length=255) class Note(models.Model): timestamp = models.DateTimeField() Both have serializers: class NoteSerializer(ModelSerializer): class Meta: model = User fields = '__all__' class UserSerializer(ModelSerializer): class Meta: model = Note fields = '__all__' notes = NoteSerializer( many=True, read_only=True, ) Now, I need to an endpoint that will return a JSON with the list of users with related notes for each one of them. The trick here is to be able to filter those notes by a date range. I imagine the URL would look like this: /api/clients/?range=month&date=2019-03 This translates to: "give me a list of all users with their related notes with timestamp between 2019-03-01 and 2019-04-1. And the question is: what's the best approach to accomplish that using Django Filters? -
Custom validation of ModelForm in Django
I am working on a Django app to register sales. I have created three models: Project, Employee, and Sale. The project and employee models are as follows: class Project(models.Model): project_id = models.IntegerField(primary_key = True) name = models.CharField(max_length = 100, unique = True) class Meta: ordering = ['name'] def __str__(self): return self.name class Employee(models.Model): employee_id = models.IntegerField(primary_key = True) name = models.CharField(max_length = 50) email = models.CharField(max_length = 40) class Meta: ordering = ['name'] def __str__(self): return self.name Then the sale model: class Sale(models.Model): sale_name = models.CharField(max_length = 30) project = models.ForeignKey('Project', on_delete = models.CASCADE) proactive_seller = models.ManyToManyField(Employee, related_name = 'proactive') participants = models.ManyToManyField(Employee, related_name = 'participant') doers = models.ManyToManyField(Employee, related_name = 'doer') start_date = models.DateField() end_date = models.DateField() def __str__(self): return self.sale_name So the each sale object contains information on what project the sale is related to, which employee was the proactive/lead seller, which employees were participating in the sale, and also which employees will be doing the actual project. In my forms.py I want to make sure that the sales are unique in the sense that I want to raise an error if the user is trying to enter a sale which already has the same project, same date … -
Django get count of object many to many field in a set
I can't seem to wrap my head around mildly complicated queries in django. I have a player that has played games. each play has a many to many field with players that played that game. With player1, how do i calculate which opponent he has played the most with django orm? In SQL I guess this could be counted from the many-to-many table, something like: SELECT player_id, count(*) FROM play_player WHERE play_id in (SELECT play_id FROM play_player WHERE player_id = 'player1_id') These are my models: class Game(models.Model): """A game to be played and/or owned""" name = models.CharField(max_length=255) class Player(models.Model): """Someone who plays games""" name = models.CharField(max_length=255) games = models.ManyToManyField(Game) class Play(models.Model): """Players have played a game""" name = models.CharField(max_length=50, null=True, blank=True) description = models.TextField(max_length=250, null=True, blank=True) date = models.DateField( default=timezone.now, help_text='When was the game played?') game = models.ForeignKey( Game, on_delete=models.SET_NULL, null=True, help_text='What game was played?') players = models.ManyToManyField(Player, help_text='Who was playing?') winner = models.ForeignKey( Player, on_delete=models.SET_NULL, null=True, related_name='winner') Gist of models -
KeyError at /addData/ 'user'
Getting this KeyError on form POST action. What im trying to do here is my users have lists and in those lists they can add number values. Here i'm trying to call for all of some specific users lists to my form where user can choose wich for of his/hers list they want to add the value to. form: class data_form(forms.Form): selection = forms.ModelChoiceField(queryset=None) data = forms.IntegerField() def __init__(self, *args, **kwargs): user = kwargs.pop("user") super(data_form, self).__init__(*args, **kwargs) self.fields['selection'].queryset = List.objects.filter(user=user) Views, first handles main page and second is for adding the data @login_required def app(request): form = list_form form2 = data_form(user=request.user) user = request.user.pk user_lists = List.objects.filter(user=user) list_data = {} for list in user_lists: list_data[list.name] = DataItem.objects.filter(list=list) context = {'user_lists': user_lists, 'form': form, 'form2': form2, 'list_data': list_data} return render(request, 'FitApp/app.html', context) @require_POST def addData(request): form = data_form(request.POST) if form.is_valid(): new_data = DataItem(data=request.POST['data'], list=List.objects.get(id=request.POST['selection'])) new_data.save() return redirect('/app/') -
Django model elapsed time between two DateTimeFields
I am pretty new to django and haven't been able to find a way to get the elapsed time between two DateTimeFields and save it to another model. from django.db import models class Timesheet(models.Model): startTime = models.DateTimeField(auto_now_add=True) endTime = models.DateTimeField(blank=True, null=True) duration = models.DateTimeField(endTime - startTime) def _str_(self): return self.startTime How can I make duration = endTime - startTime? I am also using a PostgreSQL database. -
Django ORM: Implement Pre-save for a "Field" instead of a "Model"
let's say I have this model: class MyModel(models.Model): char_field = models.CharField(max_length=64) json_field = LimitedJSONField(default={}) where LimitedJSONField is a custom field for storing JSONStrings on DB. I would like to do pre-save check on json_field (e.g. truncate its length if exceeding). I have read about overriding save method for MyModel, I also know I can implement a pre-save signal but I would like to handle it on field-level. Because let's say I use LimitedJSONField on 500 models. Do I have to override save method for each of those 500 models? I implemented a validate method on LimitedJSONField but it does not get triggered on save (it's triggered only on form validation, i.e. full_clean routine). How can I implement a validator for LimitedJSONField, so that whatever Model uses it, this field gets validated with regards to one single business logic written inside LimitedJSONField? Thanks a lot for your time! -
Edit a django login form
I am running an example django app from this library, here is the whole code. I would like to add the login part of this app, i want to add more fields to the login view but i really don't understand how to do that, because the app does not have it's own view, but it's just calling the module's own login view. But what if i would like to use this library for my own project? Would i be forced to use their login view? How can i edit it? Here is the login view that the example is calling to handle authentication: core.py @class_view_decorator(sensitive_post_parameters()) @class_view_decorator(never_cache) class LoginView(IdempotentSessionWizardView): """ View for handling the login process, including OTP verification. The login process is composed like a wizard. The first step asks for the user's credentials. If the credentials are correct, the wizard proceeds to the OTP verification step. If the user has a default OTP device configured, that device is asked to generate a token (send sms / call phone) and the user is asked to provide the generated token. The backup devices are also listed, allowing the user to select a backup device for verification. """ template_name = 'two_factor/core/login.html' … -
Entry point of Django Admin panel for profiling
I have a Django admin panel with inlines which is behaving slowly. With the help of the Django Debug Bar, I have been able to reduce the number of queries, caching contents of dropdown (link) and in general making sure that the database is not the bottleneck anymore. However, loading the page is still slow. For an object with a medium amount of inlines (±100), the page is loading in 800 ms, 2.5 ms of which for database queries. Now I want to profile the Python code. What would be the best way of profiling loading an admin panel page? I am looking for some output like cProfile, but in order to use that, I need to call the exact same function as is called whenever I load the page. I have no clue however what that entry point would be. I wouldn't mind hacking temporarily in the Django code itself. How can I find out where to start profiling the loading of a single admin panel page? I am using Django 1.8, Python 3.4. -
How to test a relationship with pytest in drf
I am writing some tests for my API. My basic is: Create a fixture; Run tests as bellow. @pytest.mark.django_db def test_product(client, product): response = create_product response_get = client.get(f'/myapi/v1/product/{response.data["id"]}/') assert response_get.status_code == 200 This example above works fine for me, but I need to test a relationship model. What is the way to create this type of test? -
Django allauth add extra model fields to form
I am quite new to Django and I am trying to add extra fields to a signup form (I use django-allauth to manage signup/login etc.). For now, I have the fields in my model: # models.py from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) gender = models.CharField(max_length=100) birthdate = models.CharField(max_length=100) plan = models.CharField(max_length=100) And I also have an extended signup form which shows the fields: # forms.py from allauth.account.forms import SignupForm from django import forms from .models import Profile class CustomSignupForm(SignupForm): first_name = forms.CharField(max_length=30, label='First Name') last_name = forms.CharField(max_length=30, label='Last Name') GENDERS = (('1', 'Male'),('2', 'Female'), ('3', 'Prefer not to say'),) gender = forms.ChoiceField(choices=GENDERS, label='Gender') YEARS = [x for x in range(1940,2019)] birthdate = forms.DateField(widget=forms.SelectDateWidget(years=YEARS), label='Birthdate') PLANS = (('1', 'Free'),('2', 'Pro - $9.99/mo'),) plan = forms.ChoiceField(choices=PLANS, label='Plan') def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.gender = self.cleaned_data['gender'] user.birthdate = self.cleaned_data['birthdate'] user.plan = self.cleaned_data['plan'] user.save() return user I also have registered the Profile in the admin section and I am able to chenge it from there. The form is registred in settings.py as well. How do I link the form and its extra entries to a new user? … -
Django-Filters Empty String Query Param Cause Validation Error
When using django-filters with django rest framework, the default query filtering form will add all query params for all fields, and the empty fields end up as empty strings passed to the backend. Empty strings are not None, so the status = self.request.query_params.get('status', None) will still add the empty string to the variable, and this will make its way to the queryset.filter function. This is very bad when the field being filtered is not a string. So my question is am I doing something wrong? Is there a way to check for empty string params? I'm not sure if I'm even doing filtering right (I'm probably filtering twice for no reason, but I wanted django-filters in there because of the built in integration with django-rest-frameworks browseable API. My workaround is the ternary operator checking for the empty string after the call to query_params.get Below is my view code for the API: class JobList(generics.ListCreateAPIView): serializer_class = JobCreateSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) filter_backends = (filters.OrderingFilter, DjangoFilterBackend) filterset_fields = ('status', 'success', 'worker_id', 'owner', 'job_type') ordering_fields = ('priority', 'submitted', 'assigned', 'completed') def perform_create(self, serializer): serializer.save(owner=self.request.user) def get(self, request, format=None): # IMPORTANT: use self.get_queryset() any place you want filtering to be enabled # for built in … -
How to return different output from more than 1 user simultaneously in Django?
I have a created a website which runs a python file and takes input from user and then returns a variable which I print on my webpage and its all done using Django now everything is good till there is only 1 user but the moment when there are more than 1 users then what's happening is everything runs fine but the output that is coming in both users screen are from the user which pressed the submit button at end def function(): outputvar = 2* inputvar time.sleep(5) return outputvar now suppose the user1 entered '2' and user2 entered '4' then the output on both the users screen is 8 if the user2 entered the the value '4' within 4 seconds. so how to overcome this issue I want output on user1's screen to be '4' and user2's screen to be '8' even if both the user press the submit button simultaneously because my python program takes some time to generate output I am new to Django so I don't know much about how Django processes python script . -
TypeError at /myapp/beds/
get() missing 1 required positional argument: 'mat_number' I am new to programming, please how could I resolve the above TypeError following the details below: from django.shortcuts import render, redirect from django.views import views class BedsView(View): def get_user_details(self, username, mat_number): try: user = User.objects.get(username=username) except User.DoesNotExist: return redirect('index') userbeds = Userbed.objects.filter(user=user, mat_number=mat_number).order_by(-posted_date)[0] form = UserBedsForm({'mat_number':userbeds.mat_number}) return (user, userbeds, form) @method_decorator(login_required) def get(self, request, username, mat_number): (user, userbeds, form) = self.get_user_details(username, mat_number) return render(request, 'myapp/beds.html', {'userbeds':userbeds, 'selecteduser':user, 'form':form}) @method_decorator(login_required) def post(self, request, username): (user, userbeds, form) = self.get_user_details(username) form = UserBedsForm(request.POST, instance=userbeds) if form.is_valid(): form.save(commit=True) return redirect('beds', user. username) else: print(form.errors) return render(request, 'myapp/beds.html', {'userbeds':userbeds, 'selecteduser':user, 'form':form}) At myapp urls.py, from django.urls import path from myapp import views from myapp.views import BedsView app_name = 'myapp' urlpatterns = [ path('beds/<username>/', BedsView.as_view(), name='beds'), ] At myproject urls.py, from django.contrib import admin from django.urls import path, include from myapp import views urlpatterns = [ path(' ', views.index, name='index'), path('admin/', admin.site.urls), path('myapp/', include('myapp. urls')), ] How do I sort this TypeError, please?... -
How to automate setting django model attribute based on some condition?
class TimecardModel(models.Model): latitude = models.FloatField(max_length=16, blank=True, null=True) longitude = models.FloatField(max_length=16, blank=True, null=True) employee = models.ForeignKey(User) clock_in = models.DateTimeField(blank=True, null=True, editable=True) clock_out = models.DateTimeField(blank=True, null=True) is_clocked_out = models.BooleanField(blank=True, default=False) I want to set is_clocked_out = True everytime when employee clock_out, how do I achieve this thing. I know that django singals can do the job, but can I write method on django model to do this. If I write one how this method will execute everytime emplyee clock_out. Do I need to call this or it will work everytime I save the model object. Will @property help me? then how? Thanks in advance. -
Django save dict from Json to DB
i would like to know how i can save a field i get from json as dict. to my database field. Currently i only get 'int' object is not callable my code: ... decoded_balance = json.loads(check_balance) User.objects.update_or_create( decoded_balance=user.acc_balance('confirmed') ) decoded_balance contains the following key:vaules "confirmed" & "unconfirmed": $number thank and regards -
Django - creating and saving multiple object in a loop, with ForeignKeys
I am having trouble creating and saving objects in Django. I am very new to Django so I'm sure I'm missing something very obvious! I am building a price comparison app, and I have a Search model: Search - all searches carried out, recording best price, worst price, product searched for, time of search etc. I have successfully managed to save these searches to a DB and am happy with this model. The two new models I am working with are: Result - this is intended to record all search results returned, for each search carried out. I.e. Seller 1 £100, Seller 2 £200, Seller 3, £300. (One search has many search results). 'Agent' - a simple table of Agents that I compare prices at. (One Agent can have many search Results). class Agent(models.Model): agent_id = models.AutoField(primary_key=True) agent_name = models.CharField(max_length=30) class Result(models.Model): search_id = models.ForeignKey(Search, on_delete=models.CASCADE) # Foreign Key of Search table agent_id = models.ForeignKey(Agent, on_delete=models.CASCADE) # Foreign Key of Agent table price = models.FloatField() search_position = models.IntegerField(). My code that is creating and saving the objects is here: def update_search_table(listed, product): if len(listed) > 0: search = Search(product=product, no_of_agents=len(listed), valid_search=1, best_price=listed[0]['cost'], worst_price=listed[-1]['cost']) search.save() for i in range(len(listed)): agent = … -
Implementing "Save For Later" functionality in a Django Shopping Cart App?
I'm trying to teach myself Django by using it to make an e-commerce site. I'm working on the shopping cart right now; it's implemented using Django sessions and it's currently working fine, but I'm having trouble implementing the "save for later" functionality that you can find on lots of online stores (i.e. Amazon or whatever) that allows users to remove items from their shopping cart and instead put them on a list that allows them to easily see it from their shopping cart page. Before I go on, here's the views.py and cart.py for my current shopping cart: cart.py: from decimal import Decimal from django.conf import settings from bookDetails.models import Book # This is the cart class. class Cart(object): # Constructor method for the class - includes a request parameter def __init__(self, request): # Start by creating a session for the new cart self.session = request.session userCart = self.session.get(settings.CART_SESSION_ID) if not userCart: userCart = self.session[settings.CART_SESSION_ID] = {} self.userCart = userCart def save(self): self.session.modified = True def add(self, book, amount=1, change_amount=False): book_id = str(book.id) if book_id not in self.userCart: self.userCart[book_id] = {'amount': 0, 'author': book.book_author, 'author_bio': book.author_bio, 'description': book.book_description, 'genre': book.book_genre, 'publishing_info': book.publishing_info, 'avg_rating': str(book.avg_rating), 'price': str(book.price)} if change_amount: self.userCart[book_id]['amount'] = … -
Why is Django UUIDField with editable=False is editable?
I want to make the UUID field not editable in Django, i am using the uuid as the names of static files which loses its integrity if the corresponding UUID is changed. I was trying to make UUID readonly (on shell, not concerned about forms and admin) so that nothing should never change the uuid of a model once defined. class Car(models.Model): uuid = muuid = models.UUIDField(default=uuid.uuid4, editable=False) so when i try to change the uuid in shell >>> x = Car.objects.first() >>> x.uuid UUID('acd963cf-aa2f-4f44-988d-87091d492766') >>> x.uuid = uuid.uuid4 >>> x.save() >>> x.uuid UUID('1155ce6d-d783-4dc8-a970-a004dc63f3d8') Django version is 2.1.7, database is PostgreSQL 10 -
How to use current field?
I have model Order with fields: id,date,value...., id is Auto field in my view how to get the current id when saving new record to save it in related model? My view: def item(request,Product_id,ln): user = request.user if request.method == 'GET': item = models.Product.objects.get(id=Product_id) data=AddGet() context = { 'item': item, 'former':data, 'lan':ln } return render(request,'Item.html', context) else: table1 = models.Order() table1.lan = ln table1.user_id = user.id table1.save() item = models.Product.objects.get(id=Product_id) d=item.Price data = AddGet(request.POST) if data.is_valid(): table = models.Get() table.count = data.cleaned_data['count'] table.order_id = a table.product_id = item c=d*data.cleaned_data['count'] table.value=c table.save() return redirect('/invoice/' ) -
Git for a Django project with static pages and separate interactive application
I am new to Django, and would like to use Git to to develop an existing Django project which has (1) some fairly static pages (home, description, contact, FAQ..) and (2) a more sophisticated interactive application (a sort of dashboard application). The static web pages will generally be updated more frequently (e.g. weekly) than the dashboard application (e.g. monthly). Before adopting Django, I used to have a separate repository for the static web page content, and a separate repository for developing the dashboard application, which I pushed individually to a remote server when required. In Django, how should I setup Git to allow a flexible development of both the static web pages, and the application? In variant A (cf. picture below), I cannot update the web pages content without also having to push the dashboard app, even if it isn't in a deployable state. In variant B, I could .gitignore the main mysite app in the a first repo, and create another repo for it in order to only push edits made in that app. In variant C, the mysite app only contains project-related files (settings.py, dbrouters.py...), and pages' content is moved to a specific app called pages (for lack … -
Django prevent creating objects in concurrency
models: class CouponUsage(models.Model): coupon = models.ForeignKey('Coupon', on_delete=models.CASCADE, related_name="usage") date = models.DateTimeField(auto_now_add=True) class Coupon(models.Model): name = models.CharField(max_length=255) capacity = models.IntegerField() @property def remaining(self): usage = self.usage.all().count() return self.capacity - usage views: def use_coupon(request): coupon = Coupon.objects.get(condition) if coupon.remaining > 0: # do something I don't know how to handle concurrency issues in the code above, I believe one possible bug is that when the if clause in the view is executing another CouponUsage object can be created... how do I go about handling that? how do I prevent CouponUsage objects from being created when inside the if clause in the view -
HostName Cannot be Assigned: Getting getaddrinfo error in django
(base) C:\Users\Laksh\PythonProjects\Django\PIFORMS>python manage.py runserver example:8080 Performing system checks... System check identified no issues (0 silenced). You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. March 13, 2019 - 23:51:35 Django version 2.1.3, using settings 'PIFORMS.settings' Starting development server at http://example:8080/ Quit the server with CTRL-BREAK. Error: [Errno 11001] getaddrinfo failed -
GDAL installation fails on azure web app service
I have a linux web app running on python 3.6 stack which was working fine until 2nd week of Feb, it stopped working and started throwing error saying that gdal was not found(checked logs). GDAL was being installed from the start up command which sent the web app went into boot loop. So, I tried two different approaches to resolve this. Installed GDAL locally inside web app itself (from SSH terminal). Building GDAL from source locally inside web app itself (from SSH terminal). In both cases, GDAL gets installed but when I push any code changes to the web app same error is thrown again. ERROR Could not find the GDAL library (tried "gdal", "GDAL", "gdal2.2.0", "gdal2.1.0", "gdal2.0.0", "gdal1.11.0", "gdal1.10.0", "gdal1.9.0"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings Start-up commands apt-get update -y && DEBIAN_FRONTEND=noninteractive apt-get -y upgrade && apt-get install binutils libproj-dev gdal-bin libgdal-dev -y Can anyone guess what is going wrong? Or Know how to resolve this?