Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django views many-to-many relationship field problem
During work on my 1st app(kind of cookery book where it will be possible also to create meal plans) i have a problem to addapt one field from many-to-many(through) model to my html template. Field name is 'meal' in RecipeMealPlan model. Here are my models: class Recipe(models.Model): title = models.CharField(max_length=50) cooking_time = models.IntegerField(help_text='in minutes', validators=[MinValueValidator(1), MaxValueValidator(5000)]) difficulty_level = models.IntegerField(choices=DIFFICULTY_LEVELS, default=1) description = models.TextField() created = models.DateTimeField(auto_now_add=True) cuisine = models.ForeignKey('Cuisine', on_delete=models.CASCADE, null=True) ingredient = models.ManyToManyField(Ingredient, through='IngredientRecipe') meal_plan = models.ManyToManyField('MealPlan', through='RecipeMealPlan') class RecipeMealPlan(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) meal_plan = models.ForeignKey('MealPlan', on_delete=models.CASCADE) meal = models.IntegerField(choices=MEALS) MEALS = ( (1, 'Breakfast'), (2, '2nd breakfast'), (3, 'Lunch'), (4, 'Snack'), (5, 'Dinner') ) class MealPlan(models.Model): name = models.CharField(max_length=50) amount = models.IntegerField(validators=[MinValueValidator(4), MaxValueValidator(6)]) Here is my view created to show mealplan details on my app: class MealPlanDetailsView(View): def get(self, request, id): mealplan = MealPlan.objects.get(id=id) recipes = mealplan.recipe_set.all() return render(request, 'diet_app/mealplan_details.html', {'mealplan': mealplan, 'recipes': recipes}) And html template: {% extends 'diet_app/base.html' %} {% block title %}{{ mealplan|upper }}{% endblock %} {% block content %} <h2>{{ mealplan|upper }}</h2> <ul> <p>Posiłki:</p> {% for recipe in mealplan.recipemealplan_set.all %} <li>{{ recipe.get_meal_display}}: <a href="/recipe/{{recipe.id}}/">{{ recipe }}</a></li> {% endfor %} </ul> {% endblock %} Everything looks fine but link to receipe details doestnt work: … -
Get timezones with utc offset
is there a module or public API that given the UTC offset returns a list of all timezones in that offset ? For example given UTC+2 it returns the following list: Africa/Blantyre Africa/Bujumbura Africa/Cairo Africa/Gaborone Africa/Harare Africa/Johannesburg Africa/Juba Africa/Khartoum Africa/Kigali Africa/Lubumbashi Africa/Lusaka Africa/Maputo Africa/Maseru Africa/Mbabane Africa/Tripoli Africa/Windhoek Asia/Amman Asia/Beirut Asia/Damascus Asia/Famagusta Asia/Gaza Asia/Hebron Asia/Jerusalem Asia/Nicosia Europe/Athens Europe/Bucharest Europe/Chisinau Europe/Helsinki Europe/Kaliningrad Europe/Kiev Europe/Mariehamn Europe/Riga Europe/Sofia Europe/Tallinn Europe/Uzhgorod Europe/Vilnius Europe/Zaporozhye -
What should happen to the data when disabling an app in django?
I have a django app "my_debug" that contains a model like this: class MyDebugEntry(Model): user = ForeignKey(User, on_delete=CASCADE) data = TextField() This app is only for debugging purposes, so I add it to INSTALLED_APPS when I need it and remove it afterwards. This works fine for the most part. However, when I try to remove a user I get the following error message: IntegrityError at /some/path/ update or delete on table "auth_users" violates foreign key constraint "mydebug_mydebugentry_user_id_d738bc03_fk_users_" on table "mydebug_mydebugentry" DETAIL: Key (id)=(5) is still referenced from table "mydebug_mydebugentry". This is because on_delete=CASCADE is implemented in python, not in the database itself. So when the "my_debug" app is disabled, the on_deleted behavior is disabled along with it. So what is the proper way to do this? Should I drop all of the app's tables when removing it from INSTALLED_APPS? -
What will Max return from an empty record?
what will the max return if particular customer has no order__id, below is the code in views.py in django, queryset = Customer.objects.annotate(last_order_id=Max('order__id')) screenshot of the table -
Django-fsm, what am I missing?
I'm starting to wonder what is the point of django-fsm? I am working on a production management system. As an example, a transition from state INCEPTED (details being entered) to states IN_PRODUCTION (being manufactured) or RESOURCE_WAIT (some necessary input entity is not yet available). Establishing the details involves querying a considerable number of different models, and might come to involve asking questions of the user. It seems unnatural to attempt to put querysets on other models into the model containing the state field. (It's causing me a circular import problem as well, which I don't know how to resolve). So, I have written this transaction as a view instead, which also means that I can display a list of checks which were made, and their success/fail status. The issue of making sure that the transition is fully committed or not committed is easily handled via with transaction.atomic() so if anything goes wrong, nothing is committed to the DB. Which leaves me wondering what I am missing. Why does django-fsm exist? It doesn't seem to fit into what I am trying to accomplish. Too low-level, or .... -
Send missed notifications to a client when webscoket connection is made
I am developing a chat application with django channels. But I have a problem. How can I make client application sync with the server. If the client application disconnect and reconnect it will lose the changes. How can I make the client application synced with the server. Sorry for bad english. -
How to use django-filter and django-mptt in template?
I want to use these third apps together in my template. But it doesn't work. I don't know why it is. Individually they work well, but when I tried to build its together it doesn't work. I tried to use recursetree and |tree_info but it also doen't work. I will be happy if you help me. It took a long time to me. template.html <form method="get"> <label for="{{ filter.form.subject.id_for_label }}" class="form-label">Subject:</label> {% for su,structure in subject|tree_info %} {% if structure.new_level %}<ul> <li>{% else %}</li> <li>{% endif %} {{filter.form.su }} {% for level in structure.closed_levels %}</li> </ul>{% endfor %} {% if filter.form.su.errors %} <div class="alert alert-warning" role="alert"> {% for error in filter.form.su.errors %} {{error}} {% endfor %} </div> {% endif %} {% if filter.form.su.help_text%} <div class="form-text ms-2">{{filter.form.su.help_text}}</div> {% endif %} {% endfor %} </div> <button type="submit">Search</button> </form> {% for article in filter.qs %} <div class="bg-light d-flex flex-column flex-wrap"> <a href="{{ article.get_absolute_url }}">{{ article.title|safe }}</a> <a href="{{ article.author.profile.get_absolute_url }}">{{ article.author.get_full_name|default:article.author.username }}</a> <p><strong>Abstract:</strong> {{ article.abstract|safe|truncatewords_html:25 }}</p> <p class="align-self-end"><i class="fas fa-eye"></i> {% get_hit_count for article %}<br> <i class="far fa-arrow-alt-circle-down"></i>500 </p> </div> {% endfor %} models.py class Subject(MPTTModel): name = models.CharField( max_length=100, unique=True, verbose_name=_("category name"), help_text=_("format: required, max-100"), ) slug = models.SlugField( max_length=150, null=False, unique=False, … -
Connection timed out when trying to send an email using the send_mail method
I am having trouble when it comes to sending emails using the send_mail method from the django.core.mail module. The contents of the project email settings are as follows. # --snip-- # Email Settings EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'mukukachilu@gmail.com' EMAIL_HOST_PASSWORD = 'myfakepassword' EMAIL_PORT = 587 EMAIL_USE_TLS = False EMAIL_USE_SSL = False # --snip-- This is what I am doing in the Django shell. Python 3.9.7 (default, Sep 10 2021, 14:59:43) [GCC 11.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django.core.mail import send_mail >>> from django.congf import settings >>> send_mail('Test Subject', 'Test message', settings.EMAIL_HOST_USER, ['c.mukuka@makeitworkds.com'], fail_silently=False) After the send_mail method hangs for a long time, I am getting this Traceback below. Traceback (most recent call last): File "<console>", line 1, in <module> File "/root/djangoenv/lib/python3.9/site-packages/django/core/mail/__init__.py", line 61, in send_mail return mail.send() File "/root/djangoenv/lib/python3.9/site-packages/django/core/mail/message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "/root/djangoenv/lib/python3.9/site-packages/django/core/mail/backends/smtp.py", line 102, in send_messages new_conn_created = self.open() File "/root/djangoenv/lib/python3.9/site-packages/django/core/mail/backends/smtp.py", line 62, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "/usr/lib/python3.9/smtplib.py", line 255, in __init__ (code, msg) = self.connect(host, port) File "/usr/lib/python3.9/smtplib.py", line 341, in connect self.sock = self._get_socket(host, port, self.timeout) File "/usr/lib/python3.9/smtplib.py", line 312, in _get_socket return socket.create_connection((host, port), timeout, File … -
How to check if the logged in user is present in groups in class based views(viewsets.ModelViewSet)?
I have a class based view class JobViewSet(viewsets.ModelViewSet): queryset = Job.objects.all() serializer_class = JobSerializer permission_classes = (IsAuthenticated,) I have 2 group of users(implemented using django.contrib.auth.models Group), 'company' and 'customer'. On each view, I have to check if the user belongs to a certain group. Is it possible to do it using custom permission_classes. Thank you. -
How to connect to local network database from docker container
I'm trying to connect to an express database on sql server accesible throughout 192.168.0.130:1433 on local network from Docker Django container. I'm on a Mac and from local host i have ping $ ping 192.168.0.130 64 bytes from 192.168.0.130: icmp_seq=0 ttl=128 time=5.796 ms 64 bytes from 192.168.0.130: icmp_seq=1 ttl=128 time=2.234 ms But inside docker container get timeout error. docker-compose.yml: version: '3.7' services: ... django: container_name: djangonoguero_django_ctnr build: context: . dockerfile: Dockerfile-django restart: unless-stopped env_file: ./project/project/settings/.env command: python manage.py runserver 0.0.0.0:8000 volumes: - ./project:/djangonoguero depends_on: - postgres ports: - 8000:8000 networks: - djangonoguero-ntwk networks: djangonoguero-ntwk: driver: bridge Anybody could help me please ? Thanks in advance. -
sort django queryset using a temporary field which is not listed in model
My model is as follows: class People(models.Model): name = models.charfield(max_length = 200) surname = models.charfield(max_length = 200) In my function: people_list = People.objects.all() for each in people_list: if some_conditions: each.level = 1 else: each.level = 2 I need to sort the people_list using level variable I've added. I get FieldError when trying to do people_list = people_list.order_by('level') -
How do I get Sentry reference ID in html template using sentry-sdk?
Since the raven is deprecated I need an alternative way to display Sentry reference ID in my html template. The previous version looks like this from the example: <p>You've encountered an error, oh noes!</p> {% if request.sentry.id %} <p> If you need assistance, you may reference this error as <strong>{{ request.sentry.id }}</strong>. </p> {% endif %} How do I do this now? I tried to use sentry_sdk.capture_exception() or sentry_sdk.last_event_id() method. The first one returns None in my template, the second one looks like it's now what I am looking for. -
error can not Creating a Docker Container with django project
i trying to creating container for django project so but an error show with SECRET KEY in settings.py file when i run docker command docker run --publish 8000:8000 python-django error with SECRET_KEY show that i am unable to build docker container settings.py file ... # UPDATE secret key load_dotenv(find_dotenv()) SECRET_KEY = os.environ['SECRET_KEY'] .... -
Using token only in POST and not in GET http request (Django DRF) + not caching
I'm using authentification with Django (DRF), and it's working. But, I would like to use the Token only with POST request and not GET requests. Is it possible ? My code : Settings : # REST API "rest_framework", "rest_framework.authtoken", and : REST_FRAMEWORK = { "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.IsAuthenticated",), "DEFAULT_AUTHENTICATION_CLASSES": ( # "rest_framework.authentication.BasicAuthentication", # "rest_framework.authentication.SessionAuthentication", "rest_framework.authentication.TokenAuthentication", ), } If I add this line, or not, it's the same : class BlaBlaViewSet(APIView): #permission_classes = (IsAuthenticated,) So, how can I do that in the "post" function and not in "put" function, please ? Have a nice day :) F. -
Fetch API to update JSON data
This is JSON data I am getting from APIs working through Python. I am appending all the username data to one JSON file, if existing user is changing their revenue value in front end now how to update their values using Python script? montly_details:[ { "user name":"John", "revenue":"90", "expenses":"30", "profits":"60" } { "username":"kite", "revenue":"120", "expenses":"60", "profits":"60" } { "username":"noel", "revenue":"150", "expenses":"70", "profits":"80" } { "username":"victor", "revenue":"180", "expenses":"30", "profits":"150" } ] -
How to store data from xml to database and than to see it on web?
Sorry for my question but i am begginer in it and this is my first project. i am solving the issue of how to store data from xml file to database and than see it on web page.I would like to use django as web builder and sql as database. But my xml file is store on my local pc and need to see this data on the web page. What is the best way how can I do it? When you image the situation, i own gym and it is self-service it mean I have terminal outside and every client use your own card for entrance, it is recorded in xml on my local pc and I need that every client will be able to see it thru web page where, when was in gym etc...but when i deploy my web "django" page to server how can i do it that web will takes data from xml file and storage it into databse on server?? Thank you for yours responses. -
Django 4 template check if user is authenticated using async view
Is there any way to check if a user is authenticated in the Django template using async view? I am having the errors SynchronousOnlyOperation when I do {% if user.is_authenticated %} in my template. I know there is the option DJANGO_ALLOW_ASYNC_UNSAFE but the doc says it's not safe. So I am wondering if there is a safer method. -
How do i do a temperature conversion in Django with radio buttons?
I'm working with API using python(Django) but I need help with converting the temperatures from Celsius to Fahrenheit and vice versa with a radio button. -
Django DeleteView Redirect to Second Previous Page
I have my generic deleteview. The user can visit here from the generic updateview, because only button is there. I like to redirect the user to previous page after deletion but the previous page is the updateview and it'll be gone with the deletion. Is there any way to send the user to second previous page after deletion ? class ActionDeleteView(generic.DeleteView): # action-deleteview model = models.Action template_name = 'crm/action_delete.html' def get_success_url(self): # for the message message = f'{self.get_object()} is deleted successfully!' messages.success(self.request, message) previous = self.request.META.get('HTTP_REFERER') print('***************** previous: ', previous) return reverse_lazy('action-listview') NOTE: The print(previous) in the code returns the updateview -
Reset Heroku DB now some of my schemas aren't migrating
New to heroku - I had some major problems with a migration from my local django app to Heroku prod so decided to destroy my heroku db with heroku pg:reset - this all seemed to go to plan, I then ran heroku run python manage.py migrate to attempt to recreate my schemas. The following were migrated: Apply all migrations: account, admin, auth, contenttypes, sessions, sites, socialaccount But none of my models.py tables went up - eg the following crucial schema was not migrated: class mapCafes(models.Model): id = models.BigAutoField(primary_key=True) cafe_name = models.CharField(max_length=200) cafe_address = models.CharField(max_length=200) cafe_long = models.FloatField() cafe_lat = models.FloatField() geolocation = models.PointField(geography=True, blank=True, null=True) venue_type = models.CharField(max_length=200) source = models.CharField(max_length=200) cafe_image_url = models.CharField(max_length=200, null=False) # class Meta: # # managed = False def __str__(self): return self.cafe_name Installed Apps: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'testingland', 'rest_framework', 'bootstrap_modal_forms', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'widget_tweaks', ] Any advice? -
what is initial steps to run project which was already developed code. how to do for first time
i have old code which is on live , my manager gave code in zip file. which is developed python 2.7 and Django 1.11 i downloaded and created environment. when i started install requirement.txt file errors were come. ERROR: No matching distribution found for alabaster==0.7.10 (from -r fedDjango/SAML_val/Samlvalidate/requeriments.txt (line 1)) d:\pro - portal\portal\venv\lib\site-packages\pip_vendor\urllib3\util\ssl_.py:139: InsecurePlatformWarning: A true SSLContext object is not available. Thi s prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings InsecurePlatformWarning, -
Python getting blanck files from django server using docker
The problem I have is difficult to explain, so I am sorry if my question is too big. I am creating an API with python and django REST Framework, and one of the functionalities we need is to upload a file so another client can download it. The way I do this, I get it from the request with file_details = request.FILES.get('file'). Then I upload the file with the request python library like this. import requests url = "server_url" payload = {'memberId': '7d2d92fb-a21c-40a5-9e0d-f4f299edb468', 'memberType': 'professional'} file = [ ('file',(file_details.name, file_details.read(), file_details.content_type)) ] headers = {} response = requests.request("POST", url, headers=headers, data=payload, files=file) When I try this in local (on my machine), it works fine. I run our docker container and make the request with the file, and everything works perfectly. Then I download the file from the server and the file is also ok. The problem is that when I upload the code to the server and I make the postman request directly to it, it seems that is correctly uploaded, but when I try to download it I get a blank pdf file. Do you know how to solve this problem? Thanks in advance for your help. -
How to filter from auth_group_permissions table Django
How to filter from auth_group_permissions table Django. actually, I don't know by which model I can filter from auth_group_permissions. from django.contrib.auth.models import Group, Permission from django.contrib.contenttypes.models import ContentType I only get this model from Django documentation but I don't get any from for auth_group_permissions table. please anyone helps me. -
how to create range slider in django and javascript
how to create a range slider in Django and javascript? also for data stuff I'm using an API instead of a database I want to create a range slider like that (video demo): https://itslachiteaching.wistia.com/medias/v4cx2mncw8 #views.py def slider(request): form = SliderForm() context = { "slider": form, } return render(request, 'slider.html', context) #forms.py from django_range_slider.fields import RangeSliderField class SliderForm(forms.Form): range_field = RangeSliderField(minimum=10,maximum=102) #slider.html <div>form {{ slider.as_p }}</div> -
django: JOIN two SELECT statement results
MYSQL - working fine SELECT * FROM (SELECT ...) u LEFT JOIN (SELECT ...) e ON (u.id = e.employee_id) DJANGO u = user_with_full_info.objects.values( 'id' ).filter( branch = team['branch__id'], team = team['team__id'], position__lt = team['position__id'], valid = 1 ) d = staff_review.objects.values( 'employee' ).annotate( last_date=Max('date'), dcount=Count('employee') ).filter( month = month() ) e = staff_review.objects.values( 'performance__name', 'performance__style', 'employee__user__id', 'employee__user__salary_number', 'employee__user__last_name', 'employee__user__mid_name', 'employee__user__first_name', 'date' ).filter( month = month(), employee__id__in = Subquery(u.values('id')), date__in = Subquery(d.values('last_date')), ).order_by( 'employee__id' ) With MYSQL I got: | employee_id | performance_id | | -------- | -------------- | | 3 | 2 | | 1 | 3 | | 4 | NULL | With Django I got: | employee_id | performance_id | | -------- | -------------- | | 3 | 2 | | 1 | 3 | How can I fix that?