Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django filter form field objects by existing one-to-one relation
I'm new to django and still trying to figure out basic things. I have three models: pc, pcslot and card. pcslot contains the relations to slots and to pc. One pc can have multiple slots, each card can only be in one slot. class pcslot(models.Model): card = models.OneToOneField("card on_delete=models.SET_NULL, null=True, blank=True ) computer = models.ForeignKey('pc', on_delete=models.CASCADE, related_name='slots', editable=False ) Now I would like to exclude all already assigned cards from the form dropdown. I tried to filter the objects inside the form by adding this to the model def get_related(self): if(hasattr(self, 'pcslot')): return 1 return None But django object filter cannot access these methods, so filter(get_related=1) is not working: class pcslotForm(ModelForm): class Meta: model = pcslot fields = "all" def init(self, user=None, **kwargs): super(pcslotForm, self).init(**kwargs) self.fields['card'].queryset = card.objects.filter(get_related=1) What would be the best way to do this? Do I have to loop through all objects and compare or is there a builtin method I don't know yet? Thanks -
How to create a combined stacked bar chart and table to display on a HTML website
I am trying to create something like this: It is a combined bar chart with a table below it. Notice that the table headers and chart's x-axis are the same. I also want the headers and bars to be aligned although it's not shown in the picture. What is the best way I can do this? I am using Python, Django, HTML, CSS and Javascript to build this chart. Is there any library like chart.js to create this type of graph? -
Calculate 38 days from month last date in Django
let us consider date as invoice.created_at = datetime.date(2021, 11, 17) next_month_first_date here is getting the nextmonth first date next_month_first_date = (invoice.created_at.replace(day=1) + datetime.timedelta(days=32)).replace(day=1) # datetime.date(2021, 12, 1) Now I need last day of invoice.created_at month this_month_last_day = ? how to find last date of invoice.created_at month i.e 30/11/2021 and calculate 38 days from this_month_last_day? 38 days from this_month_last_day is 7/01/2021 -
How to access to request.user in def save() in models?
I want to create a user at the creation of an object. This object is linked to the user by a foreign key. I have override the def_save() method to create the user and link it to the object. Problem: I generate a random password for this user and I would like to send it by e-mail not to the just created user but to the user. def save(self, *args, **kwargs): if self._state.adding: super(Machine, self).save(*args, **kwargs) username = f"machine_{slugify(self.site.client.name).lower()}_{self.id}" password = User.objects.make_random_password() self.user = User.objects.create( username=username, password=password ) self.save(update_fields=['user']) send_mail( f'Password of {username}', f'Password: {password}', settings.DEFAULT_FROM_EMAIL, [self.request.user.email], fail_silently=True, ) else: super(Machine, self).save(*args, **kwargs) The problem is that I don't have access to self.request in this method. How can I access to request in my def save()? Or how can I get the password value in my view? -
How to change status of the object automatically?
I am working on a project, aim of the project is that user creates announcement and I need to change is_active status to False automatically after 30 days so announcement be active 30 days but I have no idea how to do that, I am using Django Rest Framework and VueJs. -
API full path in unit tests
Is there any way to specify full path for url when i test APIs. Now i'm doing it in this way: def test_product_types_retrieve(self): self.relative_path = '/api/api_product/' response = self.client.get(self.relative_path + 'product_types/') I should add relative_path part to every single request, but i want to set it, for example in setUp function. Without self.relative_path i will get http://localhost:8000/product_types/ instead of http://localhost:8000/api/api_product/product_types/ My project structure is following, every api have its own urls.py with urlpatterns settings. Project structure -
Django doesn't change language when visiting URL with language code
I'm facing a weird situation when trying to change language after appending the language code to the url example -- domain.pt/en If I visit the site normally throught the domain without the language code appended, it works perfectly, I'm able to change language without problem. If somehow I copy the link and paste it on the browser, the language switcher stops working. example -- domain.pt I have translated a few Django websites so far and found out this happens on all of them. #urls.py urlpatterns = [ path('i18n', include('django.conf.urls.i18n')), path('admin/', admin.site.urls), ] urlpatterns += i18n_patterns( path('', include('base.urls')), prefix_default_language=True, ) template <form id="lang-switcher" action="{% url 'set_language' %}" method="post">{% csrf_token %} <input type="hidden" name="next" value"{{ redirect_to }}"> <select class="language_selector" name="language" id="" onchange="this.form.submit()"> {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}" {% if language.code == LANGUAGE_CODE %} selected {% endif %}> {{ language.code }} </option> {% endfor %} </select> </form> settings.py LANGUAGE_CODE = 'pt' TIME_ZONE = 'Europe/Lisbon' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = [ BASE_DIR / 'locale', ] LANGUAGES = [ ('pt', 'Português'), ('en', 'Inglês'), ('es', 'Espanhol'), ('fr', 'Francês'), ('de', 'Alemão'), ] For the … -
How to format date in html from month dd,yyyy to yyyy-mm-dd
I am trying to set value to the input of type 'date', i am fetching data from mysql table and set it as the value attribute of input tag. On first time it doesn't work, but if set date once then it starts working i.e. input tag shows the content of value attribute even after refreshing. For first time the date is shown as: Nov 12,2021 and from second time it shows like: 12-11-2021 Here is my code for view: def profile(request,id): project=Project.objects.get(id=id) if request.method=='POST': deadline=request.post.get('deadline') project.deadline=deadline project.save() return render(request,'edit_project.html',{'id':id,'project':project}) <html> <body> <form method="POST"> <input type='date' value={{project.deadline}}> <input type='submit' value='submit'> </form> </body> </html> -
Querying Django ORM inside celery task: SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async
We're using celery jobs alongside Django and within different celery tasks there are several occasions where the celery task is reading and writing to the database through Django's ORM. Every once in a while when using the ORM inside the celery task, the tasks throws: SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. I find it strange that it happens sometimes, rather than every time a query is made through the ORM? Secondly, when trying to resolve it as per the suggestions in the Django documentation here: https://docs.djangoproject.com/en/3.2/topics/async/ like so: Example of sync_to_asynch ussage I run into another problem: TypeError: 'coroutine' object is not iterable My question is: Why does this issue only occurs every once in a while and not everytime I query using the ORM inside the celery task? Is there a way it can be solved? Environment The celery tasks are run with gevent like so: celery -A Tasks worker -P gevent -c 10 -l INFO -E Python 3.8 Django 3.1.4 Celery 5.1.0 -
Trying to make API call, but keep getting TypeError
I'm failing to make a simple API call in Django to search for available flights. As per the API documentation, it accepts date_from and date_to parameters in 'MM/DD/YYYY' string format. I'm trying to convert the input date format from the HTML form ('YYYY-MM-DD') to 'MM/DD/YYYY' using strptime and strftime but it doesn't seem to work. I'm getting 'TypeError at /strptime() argument 1 must be str, not None' What am I doing wrong? home.html <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Home</title> </head> <body> {{ response }} <form method="post"> {% csrf_token %} <h3>Search Form</h3> <p> <input type="text" name="Origin" id="inputOrigin" placeholder="From" required> </p> <p> <input type="text" name="Destination" id="inputDestination" placeholder="To" required> </p> <p> <input type="date" name="Departuredate" id="idDeparturedate" required> </p> <p> <input type="number" name="Adults" id="idAdults" required> </p> <input type="Submit" name="Submit" value="Submit"> </form> </body> </html> views.py from django.shortcuts import render import requests import datetime as dt # Create your views here. def home(request): origin = request.POST.get('Origin') destination = request.POST.get('Destination') dep_date = request.POST.get('Departuredate') adults = request.POST.get('Adults') departure_date = dt.datetime.strptime(dep_date,'%Y-%m-%d').strftime('%d/%m/%Y') kwargs = { 'apikey':'UkyTNeGok4791FIGnTeFMD6UrooUWXoI', 'fly_from':origin, 'fly_to':destination, 'date_from':departure_date, 'date_to':departure_date, 'adults':adults } r = requests.get('https://tequila-api.kiwi.com/',params=kwargs).json() return render(request,'searchmyflight/home.html',{'response':r}) -
Convert timestamp to correct datetime in local timezone - Django
I get a timestamp from an API. When I transform it with: timestamp = datetime.fromtimestamp(json.loads(m)["_timestamp"], tz=pytz.timezone('Europe/Berlin')) I get the correct time in the console when I print it: 2021-11-10 15:22:26+01:00 But when I save it to the database with: BedTemperatureHistory.objects.create(TimeStamp=timestamp) The Timestamp looks something like this in the database (one hour less): 2021-11-10 14:22:26.000000 +00:00 My Timezone Settings look like this: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Europe/Berlin' USE_I18N = True USE_L10N = True USE_TZ = False Does anyone know what I need to do in order to save the correct timestamp in my database? -
Django doesn't detect changes in my model
I have an Orders model, in which I didn't have slug field before. So I decided to add a slug field to it. But when I run makemigrations command it says 'No changes detected'. I've tried to manually create migration and run it, but it didn't affect my database. Yes, I did check in settings, app is registered there. Model: class Orders(models.Model): customer = models.ForeignKey('contractors.Customers', models.DO_NOTHING, blank=True, null=True) slug = models.SlugField(max_length=150, blank=True) employee = models.ForeignKey('employees.Employees', models.DO_NOTHING, blank=True, null=True) order_date = models.DateField(blank=True, null=True, auto_now=True) required_date = models.DateField(blank=True, null=True) shipped_date = models.DateField(blank=True, null=True) ship_via = models.ForeignKey('contractors.Shippers', models.DO_NOTHING, db_column='ship_via', blank=True, null=True) freight = models.FloatField(blank=True, null=True) ship_name = models.CharField(max_length=40, blank=True, null=True) ship_address = models.CharField(max_length=60, blank=True, null=True) ship_city = models.CharField(max_length=15, blank=True, null=True) ship_region = models.CharField(max_length=15, blank=True, null=True) ship_postal_code = models.CharField(max_length=10, blank=True, null=True) ship_country = models.CharField(max_length=15, blank=True, null=True) class Meta: managed = False db_table = 'orders' def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.customer + "-" + str(self.order_date)) super(Orders, self).save(*args, **kwargs) def get_absolute_url(self): return u'/orders/%d' % self.pk def __str__(self): return f"{self.customer} {self.order_date}" My attempt to manually create migration: # Generated by Django 3.2.7 on 2021-11-10 13:47 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('orders', '0008_alter_orderdetails_options'), ] operations = [ migrations.AddField( model_name='orders', … -
Join multiple tables and calculate the average in a queryset
I have five Models: Ville, Machine, Compte, Signal, Donnees. The Machine table which has the key of the Ville table gives its key to Signal and Compte. Donnees has the Signal key. Class Ville(models.Model): nom_ville = models.CharField(maxlength=50) ... Class Machine(models.Model): ville = models.ForeignKey(Ville,on_delete=models.CASCADE) ... class Compte(models.Model): machine = models.ForeignKey(Machine,on_delete=models.CASCADE,related_name="credits") montant= models.FloatField() ... class Signal(models.Model): machine = models.ForeignKey(Machine,on_delete=models.CASCADE,related_name="signaux") ... class Donnees(models.Model): signal= models.ForeignKey(Signal,on_delete=models.CASCADE,related_name="donnees_signal") donne1 = models.FloatField() ... I have to calculate the average of Compte.montant and Donnees.donne1 grouped by Ville.nom I'm having trouble writing a single queryset to link these tables and calculate the two averages. Here is what I tried to do: Donnees.objects.values('signal__machine__ville__nom').annotate(moy1=Avg('donnee1'),moy2=Avg(Compte.objects.value('montant'))) It does not work. I need help ! I am open to all proposals and suggestions -
django: how to override the save() function in a model class so that it displays the saved information in an html template?
I am new to the django world and web development in general what I want to do is to preview the data that is saved in one of the created models "Tool" in models.py class Tool(models.Model): text1 = models.CharField(max_length=255) text2 = models.CharField(max_length=255) text3 = models.CharField(max_length=255) def save(self, *args, **kwargs): #override code super(Tool, self).save(*args, **kwargs) now I know that I need to override the save() method inside the class Tool but I don't know how it is done? in veiws.py I did the following from .models import Tool def preview(request): context = { "Tools": Tool.object.all() } return render (request,'myApp/preview.html',context) and in preview.html I have the following <!DOCTYPE html> <html> <head> <title></title> </head> <body> <p>{{Tools.text1}}</p> <p>{{Tools.text2}}</p> <p>{{Tools.text3}}</p> </body> </html> now from here, how can I render the html inside save() in Tool class? -
Can I use OpenCV in Django to draw line on the image from users?
I have developed the program, and one part of the program is getting line information from users. So I made the module in which users can draw lines on the image. (I made the module by two ways - one is opencv and the other is matplotlib) It is similar with below video. https://youtu.be/wx_oxF3vGRE Now I proposed to change my program into django project. But I cannot sure I can make similar function in the django project using matplotlib or opencv. I hope below process in the django webpage: Users select image file in their computer and upload Django save that image file and show that image (as canvas!) Users draw their own line on the shown image Drawn image and coordinates of lines are saved in the Django server. Is it possible with django? -
Send model property value to other model and display it in it's form
I'm working on an app where the user will fill a first form of a model, and he will be redirected to the next form where I want to get a value from property of the first model to be passed to the seconde model and display it in it's form. ***Models*** class Delivery(models.Model): user = models.ForeignKey( Client, on_delete=models.CASCADE, verbose_name=_("Client"), related_name=_("delivery_user") ) pickup_address = models.ForeignKey(Address, on_delete=models.CASCADE, related_name=_("pickup_address")) destination_address = models.ForeignKey(Address, on_delete=models.CASCADE, related_name=_("destination_address")) operation_date = models.DateField( _("desired pickup date"), auto_now=False, auto_now_add=False, blank=False, null=False ) invoice = models.BooleanField(_("check if you want an invoice"), default=False) created_at = models.DateTimeField(_("Created at"), auto_now_add=True, editable=False) updated_at = models.DateTimeField(_("Updated at"), auto_now=True) delivery_key = models.CharField(max_length=200) @property def distance(self): distance = Distance( m=self.pickup_address.address_point.transform(32148, clone=True).distance( self.destination_address.address_point.transform(32148, clone=True) ) ) context = {} context["distance"] = f"{round(distance.m / 1000, 2)}" print(context) return context def __str__(self): return str(self.delivery_key) class DeliveryDetails(models.Model): delivery = models.ForeignKey(Delivery, on_delete=models.CASCADE, related_name=_("delivery")) distance = models.DecimalField(_("Distance Approximative "), max_digits=7, decimal_places=2) delivery_price = models.DecimalField(max_digits=7, decimal_places=2) created_at = models.DateTimeField(_("Created at"), auto_now_add=True, editable=False) updated_at = models.DateTimeField(_("Updated at"), auto_now=True) def __str__(self): return str(self.created_at) ***Views*** class DeliveryCreateView(LoginRequiredMixin, UserPassesTestMixin, CreateView, FormView): model = Delivery form_class = UserDeliveryForm template_name = "deliveries/customer/edit_deliveries.html" def get_success_url(self): return reverse( "delivery:delivery-details", kwargs={"pk": self.object.pk, "distance": self.object.distance}, ) def test_func(self): return self.request.user.is_active class DetailsDeliveryCreateView(LoginRequiredMixin, UserPassesTestMixin, CreateView, … -
Error in Kubernetes cronjob to dump and restore postgres database for Django application
I need to create a testing environment for a specific team to use our Django application for testing against the database. This database must be somewhat in sync with out production database. Considering we have two clusters production and staging, my approach is the following: Create a db_test in the staging Postgres server db_test will be periodically synced with db_prod. To do so: Create a cronjob in the staging cluster that connects to the production database, do a pg_dump and then do a pg_restore to the db_test (using localhost because it's connected through a pgbouncer). I run the migrations to make sure the tables are up to date Next: I need to run a management command that will erase some customer data from this copy (to be GDPR compliant). Desired behavior: pg_dump and pg_restore are successful and the new database is cleared of customer information Actual behaviour: pg_dump and pg_restore are successful. I can psql into the newly created database and everything looks alright. migrate command fails with the traceback below clean_db fails because it can't find some tables (which they exist as I inspected with psql. This is the simple shell script I run in the cronjob: #!/bin/bash # … -
Django project structure for blog
Im new to django and im folowing many tutorial about django and every one of them have a different style and technique. my main focus is to structure my project for my django blog project. please help me to figure it out Here are my question Should i seperate the app for the example post, comment, categorie,tag, meta descriptions or just create the blog app and have all that model view in one app or i need to create the post, comment, categorie, tag, meta descriptions, and adding the frontend app to handle the views and url. if i have to seperate the the app that i mention above should the administrator for the dashboard area so the user can add post or delete in the app it self or i have to create the dashboard/administrator app. Should i seperate the project for dashboard administrator with public page. or should their in same project but in deferent app. i have done many schenario but one of the one i thing the best is. like this but i need aloot of comment about it blog --blog --frontend ---- models.py model i leave it empty ---- views.py i focus handel the view … -
how do I refer to a QuerySet element in Django?
I have such a QuerySet: 'category_1': Product.objects.filter(category__slug='white') how how can I refer to a certain element of this QuerySet? for example, like referring to the elements of a list. in template: {{ category_1[1].image.url }} thanks! -
Can I use textblob library in Django app?
I am working on Django web application. I have input field where user enters word and if the word is entered correctly, user is able to click on that word and get the translation of it. But, if the word is not entered correctly, user has to go back on the previous page and enter the word correctly. So, I need to make something like 'Did you mean' feature. Is it possible to make it by using textblob library, and if it is, can you get me some hints how to make it? Thanks on your answers! -
how to calculate 38 days from next month starting in Django
For example let us consider invoice_date = 09/11/2021 but is payment_period is for 38 days then it should start from 1/12/2021 to 7/01/2022 (because december month have 31 days) then the due_date will be 7/01/2022 the invoice_date can be any date of the month but payment_period should start form 1st date of next upcoming month and due_date should be 38th date from that today = datetime.date.today() (#09/10/11) -
Maintaining and using a list of user in backend using django
I am building a web-chat application using django and django-channels. I have figured out the actual chat part, however I was trying to implement a random chat pairing feature which would allow to pair any two user who choose to chat randomly. I cannnot figure out how to implement this in the backend to create a sort of list which would update automatically and from which I can take two user, pair them and thus remove them from the list. I hope, my question is clear. -
How can I put a list of integers (bit choices) to a database in django
I'm trying to get a list of weekday options into a PositiveSmallIntegerField in Django. I found a very similar question from the year 2011, Representing a multi-select field for weekdays in a Django model I tried the approach with the BitChoices class in there, and the class itself seems to work. However, I cannot put the list returned by the class to the database, since it somehow has to be the sum of that list. But how do I accomplish that? What am I missing? Here's what I have so far (disclaimer: maybe a few lines are superfluous for this example, I tried to reduce it to the bare minimum): models.py from django.db import models from django.conf import settings from django.contrib.auth.models import User from django.utils.translation import gettext_lazy as _ from datetime import date class BitChoices(object): def __init__(self, choices): self._choices = [] self._lookup = {} for index, (key, val) in enumerate(choices): index = 2**index self._choices.append((index, val)) self._lookup[key] = index def __iter__(self): return iter(self._choices) def __len__(self): return len(self._choices) def __getattr__(self, attr): try: return self._lookup[attr] except KeyError: raise AttributeError(attr) def get_selected_keys(self, selection): """ Return a list of keys for the given selection """ return [ k for k,b in self._lookup.items() if b & … -
not able to run vapid --sign claim.json
I'm following this link to create web push notification for my App, right now I'm stuck in step2 (creating public and private key) because I can't run this command(even tough I have implemented successfully the vapid vapid --sign claim.json I got this error when running this command!! 'vapid' is not recognized as an internal or external command, -
How to authenticate user present in one project db from another project?
I have two graphql django projects, lets say project1 and project2. In project1, I have users db and I am building project2 for some other purpose. Now, when I am performing some function in project2, I want to check if the user is authenticated or not from user db in project1. Please provide some suggestion on how to implement this functionality.