Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display information about linked models fields in the django admin
These are my models: class Partner(models.Model): name = models.CharField(max_length=200, verbose_name="Organisation name") class ResearchActivity(models.Model): title = models.CharField(max_length=200) partner = models.ManyToManyField(ActivityPartner, blank=True) I'd like, in the Django administration forms, to have a field in my Partner edit form representing the ResearchActivity linked to that Partner. Can this be achieved by adding a field to my Partner model (say, naming it linked_partner) and then edit my admin.py like so: @admin.register(ActivityPartner) class ActivityPartnerAdmin(admin.ModelAdmin): search_fields = ['academic',] autocomplete_fields = ['partnership_type', 'relationship_type', 'academic_links'] def get_changeform_initial_data(self, request): return {'live_contract': ResearchActivity.objects.all().filter(linked_partner__id=request.ResearchActivity.partner.id)} ? -
Django: How can I change the design of a foreign key when using forms.py?
This is my patient model and forms: class Patient(models.Model): def __str__(self): return f"{self.first_name} {self.last_name}" doctor = models.ForeignKey(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) sex = models.CharField(max_length=20) phone = models.IntegerField() birth_date = models.DateField() class PatientForm(forms.ModelForm): BIRTH_YEAR_CHOICES = [] for years in range(1900,2021): BIRTH_YEAR_CHOICES.append(str(years)) sex_choice = [('1', 'Homme'), ('2', 'Femme')] sex = forms.ChoiceField(widget=forms.Select(attrs={'class':'form-control'}), choices=sex_choice) doctor = forms.ModelChoiceField(widget=forms.Select(attrs={'class': 'form-control'}),queryset=Patient.objects.all()) first_name = forms.CharField(widget= forms.TextInput(attrs={'class':'form-control'})) last_name = forms.CharField(widget= forms.TextInput(attrs={'class':'form-control'})) phone = forms.CharField(widget= forms.TextInput(attrs={'class':'form-control'})) birth_date = forms.DateField(widget=forms.SelectDateWidget(years=BIRTH_YEAR_CHOICES,attrs={'class': 'form-control'})) class Meta: model = Patient fields = '__all__' def __init__(self, *args, **kwargs): super(PatientForm, self).__init__(*args, **kwargs) self.fields['birth_date'].input_formats = ('%Y-%m-%d') And this register.html: <form method="POST">{% csrf_token %} <div class="input-group"> <span class="input-group-text">Prénom:</span> {{form.first_name}} </div> <div class="input-group"> <span class="input-group-text">Nom:</span> {{form.last_name}} </div> <div class="input-group"> <span class="input-group-text">Sex</span> {{form.sex}} </div> <div class="input-group"> <span class="input-group-text">Telephone</span> {{form.phone}} </div> <div class="input-group"> <span class="input-group-text">Date de naissance</span> {{form.birth_date}} </div> <div class="input-group"> <span class="input-group-text">Docteur</span> <select name="doctor_choice"> {% for doctor in doctors %} <option value="{{doctor.pk}}">{{doctor.first_name}} {{doctor.last_name}}</option> {% endfor %} </select> </div> The attrs={'class':'form-control'} is working at all the fields except the doctor field which is a ForeignKey in Patient model. So when I search about it I found that they use doctor = forms.ModelChoiceField but still dosen't work and 'class':'form-control' isn't working yet -
How can I test a function that takes record as a parameter?
I need to write a test for a function post_log_filter(record) in the file my_logging.py #my_logging.py import os import sys import traceback log_format = '[%(levelname)s] %(asctime)s %(context)s %(pathname)s:%(lineno)d: %(message)s' log_time_format = '%Y-%m-%dT%H:%M:%S%z' def post_log_filter(record): # filter out undesirable logs logs_to_omit = [ {'filename': 'basehttp.py', 'funcName': 'log_message'}, # annoying logging any response to sys.stderr (even if status is 200) {'filename': 'options.py', 'funcName': 'construct_change_message'}, # logging `Key not found` if a checkbox was unchecked and isn't present in POST data ] if any([bool(record.__dict__.viewitems() >= r.viewitems()) for r in logs_to_omit]): return False return True The test that I have written is: test_my_logging.py from my_logging import * import collections import mock from mock import patch import logging LOGGER = logging.getLogger(__name__) log_format = '[%(levelname)s] %(asctime)s %(context)s %(pathname)s:%(lineno)d: %(message)s' log_time_format = '%Y-%m-%dT%H:%M:%S%z' class TestMyLogging(TestCase): def test_post_log_filter(self): self.assertEqual(True, post_log_filter(logging.LogRecord(None, None, None, None, msg=None, args=None, exc_info=None, func=None))) def test_post_log_filter_false(self): record = logging.Formatter([ {'filename': 'basehttp.py', 'funcName': 'log_message'}, # annoying logging any response to sys.stderr (even if status is 200) {'filename': 'options.py', 'funcName': 'construct_change_message'}, # logging `Key not found` if a checkbox was unchecked and isn't present in POST data ]) self.assertEqual(False, post_log_filter(record)) I am testing it for two cases. For True: No matter what I pass for post_log_filter(), I get … -
Which field is this Django field and how to use it?
This can be found in Django Admin, under Groups table. Picture: https://imgur.com/a/Of9ZASM As I see, it is a <select> html tag with the multiple option (<select multiple>). How can we achieve it in custom tables, and how can we handle them? I looked up the django documentation, but it's not that documented (if I found the right one). -
How can I hide (not disable) in Django admin the action add model button in ModelAdmin list view?
I am aware of the following questions which are pretty different: Django Admin - Disable the 'Add' action for a specific model Disable link to edit object in django's admin (display list only)? My question is a little different: how can I disable the action button in the model list view, but retain the add functionality and links for all other Django parts (for example OneToOne relations and inlines). The code: def has_add_permission(self, request): return False disables completely the add functionality of ModelAdmin (Django 3.2+, not tested in early versions). -
Simplest way to convert python console app to web app
I'm working on text game project in Python. Currently i have finished console app + sqlite database. Now I want to convert console app to web app - it will be the first web app in my life. I want to create a simple GUI. With main logo, background image, several buttons and text zones. Example of simple GUI project: simple gui project I would like the logic of the application to be based on the code already created for console application. For example, by replacing the current console functions (for example print) with a function that returns data in the form of JSON. But without changing the internal logic of the function already written in Python. Is it possible? What is the easiest way (and what technologies?) to do that? -
Running a function asynchronously in django management command
I would like to run an API call asynchronously in a while loop inside a Django management command. My main function can't be async, I only want one subfunction to be async and the calling function not awaiting for it's completion. Just calling this async function doesn't work as it doesn't run. -
Django: When running filter with m2m values, the query takes a very long time
There are about 300,000 rows of data in the DB, and it takes a very long time to issue a query when executing a filter with m2m values. How is it possible to make it faster? Also, is it better to use raw SQL for m2m? # models.py class Tag(models.Model): name = models.CharField(unique=True, max_length=100) class Video(models.Model): title = models.CharField(max_length=300) tags = models.ManyToManyField(Tag, blank=True) # all slow query (2-3seconds) Video.objects.filter(tags__in=tags) Video.objects.filter(tags__name='tag_name') Tag.objects.annotate(count=Count("Video")) -
I want to store my primarykey values into foreignkey field
This is my models class Tasklist(models.Model): clientname= models.CharField(max_length=100,null=True,blank=True) task = models.CharField(max_length=100) startdate = models.DateField(default=timezone.now, blank=True, null=True) enddate = models.DateField(blank=True, null=True) assignee = models.CharField(max_length=30) status = models.CharField(max_length=30) fstatus = models.BooleanField(default=False) def __str__(self): return self.task + " - Task - " + str(self.fstatus) class edit_page(models.Model): old_id = models.ForeignKey(Tasklist,on_delete=models.CASCADE) updatedate = models.DateField(blank=True, null=True) time_from = models.TimeField(blank=True, null=True) time_to = models.TimeField(blank=True, null=True) messagelogs = models.TextField(blank=True, null=True) def __str__(self): return self.messagelogs This is My Views page def edit_task(request, task_id): if request.method == "POST": updatedate=request.POST.get("updatedate","") time_from=request.POST.get("time_from","") time_to=request.POST.get("time_to","") messagelogs=request.POST.get("messagelogs","") test_list=edit_page(updatedate=updatedate,time_from=time_from,time_to=time_to,messagelogs=messagelogs) test_list.save() task = Tasklist.objects.get(pk=task_id) form = TaskForm(request.POST or None, instance = task) if form.is_valid(): form.save() messages.success(request,("Task Edited ")) return redirect('email_updatetask', (task_id)) return redirect('todolist') else: task_obj = Tasklist.objects.get(pk=task_id) return render(request, 'edit.html', {'task_obj': task_obj}) can u pls how can i store my primary keys into the second foreign key field via HTML files.... -
In Django modal how can i able to store both Integer and Float? It should return both accurate without converting
In Django i have model called MachineStatus and i have a field called machine heat. Here, my machine heat will be in integer ex: 6 celcius and also it will be in 6.5 celcius. How can i do this with integer and float dynamically? class MachineStatus(models.Model): heat = models.IntegerFiled(default=0, null=True, blank=True) -
Queryset containing related Object with same foreignkey
e.g. I've a person with an address class Persons(models.Model): adress = models.ForeignKey(Adress, on_delete=models.DO_NOTHING, blank=True, null=True) class Adress(models.Model): some_data = models.IntegerField() and i have another related data in antoher model like this class Places(models.Model): adress = models.ForeignKey(Adress, on_delete=models.DO_NOTHING) how can i get a queryset now of both persons and places if adress is set in persons? -
Display: table-cell not aligning with the line numbers
I have been trying to build a html page which shows a code block with line numbers. I have used CSS table-cell display property to display the line along with line number in cell format. But the line gets displayed after the line number and I want it to be aligned in the same line. CSS Grid display works properly however with Chrome it doesn't support more than 1000 lines. Please help me resolve this issue. pre { counter-reset: line 0; display: table-cell; grid-template-columns: min-content 1fr; grid-auto-rows: 1em; gap: 0.3em; } .line-number { text-align: right; } .line-number::before { counter-increment: line; content: counter(line); white-space: pre; color: #888; padding: 0 .5em; border-right: 1px solid #ddd; } <pre> <span class="line-number"></span> <code>Code</code> <span class="line-number"></span> <code>Code</code> <span class="line-number"></span> <code>Code</code> <span class="line-number"></span> <code>Code</code> <span class="line-number"></span> <code>Code</code> <span class="line-number"></span> <code>Code</code> <span class="line-number"></span> <code>Code</code> <span class="line-number"></span> <code>Code</code> <span class="line-number"></span> <code>Code</code> <span class="line-number"></span> <code>Code</code> <span class="line-number"></span> <code>Code</code> <span class="line-number"></span> <code>Code</code> </pre> -
Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. Can anyone asssist
Hello how to resolve this ERROR: Command errored out with exit status 1: command: /usr/bin/python2.7 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-3zeNQM/mysqlclient/setup.py'"'"'; file='"'"'/tmp/pip-install-3zeNQM/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-41RbUT cwd: /tmp/pip-install-3zeNQM/mysqlclient/ Complete output (10 lines): sh: 1: mysql_config: not found Traceback (most recent call last): File "", line 1, in File "/tmp/pip-install-3zeNQM/mysqlclient/setup.py", line 17, in metadata, options = get_config() File "setup_posix.py", line 44, in get_config libs = mysql_config("libs_r") File "setup_posix.py", line 26, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) EnvironmentError: mysql_config not found ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. -
How do I ensure my Profile Image is uploaded during registration?
I am trying to implement a simple Custom-User-Registration using django-rest-framework, django-allauth and dj-rest-auth. When I update my user details and add an Image the Image gets uploaded to the correct folder, but when I select the image during registration, the image is not uploaded. What am I doing wrong? This is my models.py from django.db import models from django.contrib.auth.models import AbstractUser GENDER_SELECTION = [ ('M', 'Male'), ('F', 'Female'), ] class CustomUser(AbstractUser): # email attribute is inherited from AbstractUser gender = models.CharField(max_length=20, choices=GENDER_SELECTION) phone_number = models.CharField(max_length=30) image = models.ImageField(upload_to='profile/', blank=True) This is my forms.py from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm, UserChangeForm class CustomUserCreationForm(UserCreationForm): class Meta: model = get_user_model() fields = ('email', 'username', 'phone_number', 'gender', 'image',) class CustomUserChangeForm(UserChangeForm): class Meta: model = get_user_model() fields = ('email', 'username', 'phone_number', 'gender', 'image',) This is my serializers.py from django.db import transaction from rest_framework import serializers from dj_rest_auth.registration.serializers import RegisterSerializer from dj_rest_auth.serializers import LoginSerializer as RestAuthLoginSerializer from users.models import GENDER_SELECTION from users.models import CustomUser class CustomRegisterSerializer(RegisterSerializer): gender = serializers.ChoiceField(choices=GENDER_SELECTION) phone_number = serializers.CharField(max_length=30) image = serializers.ImageField(max_length=None, use_url=True, allow_null=True, required=False) # Define transaction.atomic to rollback the save operation in case of error @transaction.atomic def save(self, request): user = super().save(request) user.gender = self.data.get('gender') user.phone_number = self.data.get('phone_number') user.image … -
How to login to Web Application with Golang
I'm a newbie go developer. I want to login into my django web application, here's my code for login into my web app (writen in Python): import requests from sys import argv as sys_argv from sys import exit as sys_exit from json import dumps as json_dumps def print_response(response): print("URL: %s\nStatus Code: %s\nCookies: %s\nHTTP Header:\n%s\n%s\n%s\nResponse:\n%s" %(response.url, response.status_code, response.cookies.get_dict(), "-"*20, json_dumps(response.headers.__dict__["_store"], indent=4), "-"*20, response.text)) # The URL try: url = sys_argv[1] except IndexError: print("Usage: %s <url>" %(sys_argv[0])) sys_exit(1) # Session session = requests.Session() # Form-Based Authentication if len(sys_argv) > 2: response = session.get(url) print_response(response) username = sys_argv[2] password = sys_argv[3] # Authentication header auth_header = {"user": username, "pass": password, "submit": "submit"} try: # Adding csrftoken required by django auth_header["csrfmiddlewaretoken"] = response.cookies["csrftoken"] except KeyError: pass response = session.post(url, data=auth_header) else: response = session.get(url) print_response(response) That code works fine. I've recreate that code in go. Here's the problem if i use the go application, when I login into my flask application it works fine, but if I login into my django application, it fails by sending me django RuntimeError (it doesn't happen if I login with my browser or my python application). So I think I have to add csrftoken just like in my … -
How to print data in template django of a diffrent table joined by foreign key?
Hello Everyone i have Two model first one is as following: class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() bargainprice = models.FloatField(default=0) discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) slug = models.SlugField() description = models.TextField() image = models.ImageField() and i am getting this model data using the following view: class ItemDetailView(DetailView): model = Item template_name = "product.html" and in product.html i am accessing Item objects like this: <span class="mr-1"> <del>₹ {{ object.price }}</del> </span> <span>₹ {{ object.discount_price }}</span> {% else %} <span> ₹ <span id="pp">{{ object.price }}</span></span> and so on.. everything working fine up here. but problem arises when i created the following model: class BargainModel(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) itemId = models.IntegerField() bprice = models.FloatField() i joined this with foreign key as mentioned. **what i want to do is print the " bprice " in the product.html of the same user but i am not able to do it ** can anyone help me with this i am new to Django. Thanks in advance -
Django which template to extends with if block
I have two distincts template which must be extended in three diffrents page. Is there a solution to extends a template with if block? I tried this without success. {% if 'project' in request.get_full_path %} {% extends 'index.html' %} {% elif 'network' in request.get_full_path %} {% extends 'base.html' %} {% elif 'zoneset' in request.get_full_path %} {% extends 'base.html' %} {% endif %} -
'AnonymousUser' object has no attribute 'company'
Greeting, I am trying to add to User form a new CharField named company but even when the field is filled the data are not saved... I tried the following with no success as I got the error in the title. views.py def register(request): if request.method == "POST": form = NewUserForm(request.POST) if form.is_valid(): user_frm = form.save(commit = False) user_frm.company = request.user.company user_frm.save() username = form.cleaned_data.get('username') messages.success(request, f"Registration Complete! User: {username}") username = form.cleaned_data.get('username') login(request, user_frm) return redirect("main:homepage") else: for msg in form.error_messages: messages.error(request, f"{msg}:{form.error_messages[msg]}") return render(request = request, template_name = "main/register.html", context={"form":form}) form = NewUserForm return render(request, "main/register.html", context={"form":form}) forms.py class NewUserForm(UserCreationForm): email = forms.EmailField(required=True) company = forms.CharField( max_length= 500) class Meta: model = User fields = ("username", "email", "company", "password1", "password2") def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) user.email = self.cleaned_data["email"] user.company = self.cleaned_data["company"] if commit: user.save() return user -
django -celery worker not receiving tasks
I am trying to send emails via Django celery but the tasks are not getting received by the celery. settings.py CELERY_BROKER_URL = 'redis://127.0.0.1:6379' CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = "UTC" tasks.py @app.task(name="send_activation_email") def send_activation_email(user): to = user.email user_id = user.id subject = 'Activate Your %s Account' % user.get_user_role_display() text_content = '' uid = urlsafe_base64_encode( force_bytes(user_id)) token = account_activation_token.make_token(user) c = ({'user': user, 'user_type': user.user_role, 'base_url': base_url, 'token': token, 'uid': uid, 'text_content': text_content}) html_content = get_template('mail/user/invite.html').render(c) msg = EmailMultiAlternatives( subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() views.py class SignUpView(generics.ListAPIView): authentication_classes = () permission_classes = () renderer_classes = (JSONRenderer, ) def post(self, request, user_role="employee",format=None, version=None): user = UsersSerializer(data=request.data,context={"user_role": user_role}) if user.is_valid(): t_user = user.save() send_activation_email.delay(t_user) message_data = custom_http_messages( code=200, message='You have successfully created your account.,data=user.data) return Response(message_data, status=message_data['code']) else: message_data = custom_http_messages( code=400, message='', data=user.errors) return Response(message_data, status=message_data['code']) Getting error it is working without the .delay function ie without celery. also the celery terminal is not receiving any tasks. -
billiard.exceptions.WorkerLostError: Worker exited prematurely: signal 9 (SIGKILL) without Docker
[2021-10-27 02:05:09,365: ERROR/MainProcess] Process 'ForkPoolWorker-5' pid:12871 exited with 'signal 9 (SIGKILL)' [2021-10-27 02:05:09,412: ERROR/MainProcess] Task handler raised error: WorkerLostError('Worker exited prematurely: signal 9 (SIGKILL).',) Traceback (most recent call last): File "/home/eps88-epixel/.local/share/virtualenvs/multi-purpose-platform-v-13-mfAjRgrr/lib/python3.6/site-packages/billiard/pool.py", line 1267, in mark_as_worker_lost human_status(exitcode)), billiard.exceptions.WorkerLostError: Worker exited prematurely: signal 9 (SIGKILL). Why does Django Celery show this error in the log? -
Make django auto convert to setting timezone
I've enabled USE_TZ as True and added TIME_ZONE as Asia/Calcutta in settings.py So when I am inputting a date like datetime(24, 11, 2021) it is stored in db as 2021-11-23T18:30:00+00:00 which is fine. But when I am getting the date in shell, it is not converting back in IST and just giving me datetime.datetime(2021, 11, 23, 18, 30, tzinfo=<UTC>) and whenever I have to display the date, it is showing 23 instead of 24 and I have to convert it manually everywhere. But strangely in django admin it is showing me IST dates but not in django shell or anywhere else. Is this the only way or I can have auto IST converted dates somehow? -
Django email: was connection to SMTP server established?
What I try to check if the connection was already opened, and if not, open it. I do connection = mail.get_connection() connection.open() to get the connection and open it. Then I send the emails and close it under some condition. Is there a way to check if the connection has already been opened? -
Difference between 'python -m pip install <package-name>' and 'pip install <package-name>'
I'm running into an issue where I'm trying to run a Django application within a virtual environment but it kept showing me errors regarding missing packages that need installation although I did install them previously using pip install <package-name>. The issues couldn't be resolved until I used python -m pip install <package-name> to install the missing packages. My question is what is the difference between the two commands? Does one of the commands install packages to the virtual environment and the other one does that globally? I'm confused. Side Note: Also when running pip freeze shows different installed packages than those showing when I run python -m pip freeze. -
Does it make sense to use django and npm in the same project?
I'm learning Django, I'm using Bootstrap etc. but I want to more customize for my website which build is bootstrap. I keep search and I saw that, if I want to customize bootstrap I should use bootstap-sass downloaded with npm. Well, my question is "Does it make sense to use django and npm in the same project?" or "Should I use a different method?" -
Django Database giving empty column where data is present in excel on uploading?
I am uploading an excel, where data is present. All the columns are filled in excel. But when I am uploading it in django, for multiple columns no data is coming in the django database. Here is my model.py class data(models.Model): sno = models.IntegerField(null=True) Date = models.DateField(null=True) Premium = models.FloatField(null=True) Count = models.IntegerField(null=True) Time = models.TimeField(null=True) Date_time = models.CharField(max_length = 100,null=True) Close = models.IntegerField(null=True) Premium_percentage = models.FloatField(null=True) Day = models.CharField(max_length=100) Here is the excel which I am trying to upload Sno Date Total_premium Count Time Date_time Close Premium% Day 479544 2021-10-13 360.65 2 14:22:00 2021-10-13 14:22:00 38735.25 0.93% Wednesday 479545 2021-10-13 357.7 2 14:23:00 2021-10-13 14:23:00 38727.3 0.92% Wednesday 479546 2021-10-13 356.35 2 14:24:00 2021-10-13 14:24:00 38739.7 0.92% Wednesday 479547 2021-10-13 353.85 2 14:25:00 2021-10-13 14:25:00 38750.4 0.91% Wednesday 479548 2021-10-13 355.65 2 14:26:00 2021-10-13 14:26:00 38730.25 0.92% Wednesday 479549 2021-10-13 354.6 2 14:27:00 2021-10-13 14:27:00 38723.15 0.92% Wednesday Here is the data that I am getting in the database enter image description here Columns which are coming empty are - SNO, PREMIUM, PREMIUM_PERCENTAGE.