Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
How to avoid "a lot of {%include%} gives a lot of <footer>"?
When I need to use a lot of {%include%} (content) in html templates - do unnecessary extensions appear for each content inclusion? Effects are also applied to each subsequent inclusion of content... When I can add content inclusion to the first html template expander, everything is fine. But when I use "pagination" I need to send "page=posts" to paginator.html. I can't find a way to send this variable to blog.html from layout.html... And I think that in the future I will have the same problems, and therefore it should be solved. layout.html <div class="container body-content"> <div id="content"> {% block content %} {% endblock %} </div> </div> <div class="container body-content"> <footer> <hr/> <p>&copy; {{ year }}. Сайт</p> </footer> </div> blog.html {% extends "app/layout.html" %} <!--♕--> {% block content %} <h2>{{ title }}</h2><br> {% for post in posts %} <hr> <div class=""> <h2> {{post.title}} </h2> <p> {{post.posted}} </p> </div> <p> <a href="{% url 'blogpost' parametr=post.id %}">{{ post.description }}</a> </p> {% endfor %} {% include "app/pagination.html" with page=posts %} {% endblock %} pagination.html {% extends "app/blog.html" %} <!--♕--> {% block content %} <div class="pagination"> <span class="step-links"> {% if page.has_previous %} <a href="?page={{ page.previous_page_number }}">Предыдущая</a> {% endif %} <span class="current"> Страница {{ page.number }} … -
How to open db.sqlite3 in Visual studio for django project
I want to use the db.sql 3 but when I open it is not reading the file. Moreover, I also downloaded SQLite extension but when I again click on db.SQLite 3 is nothing showing there. So please help me regarding this. -
Filter query on first many-to-many item
I would like the first! artist for the song to come from NL or BE. At the moment I'm querying all artists for a song. This is my query. Song.objects.filter(artists__country__code__in=['NL', 'BE']) and these are my models: class Song(Timestamps): uuid = models.UUIDField('UUID', unique=True) name = models.CharField('Name', max_length=255, blank=True) artists = models.ManyToManyField(Artist) ... class Artist(Timestamps): uuid = models.UUIDField('UUID', unique=True) name = models.CharField('Name', max_length=255, blank=True) country = CountryField(blank=True, null=True) ... I know that I can access the first item of the many-to-many field like this: song.artists.first() But I don't know how to do this in the query filter. Any ideas? Thanks in advance. -
Problem with a select that filters the other
I did all the filtering correctly from the frontend point of view, but in the backend I cannot save the data. This is the error: select a valid choise. That choice is not one of the available choices. I can't understand where the error is, I think in the fact that 'group_single' is passed in post from my view and therefore is not seen by the form. if 'gruppo_single' in self.data: try: gruppo_id = int(self.data.get('gruppo_single')) print("<----------ciao sono qui ------>", gruppo_id) self.fields['dati_esercizio'].queryset = models.Esercizi.objects.filter(gruppo_id = gruppo_id) except (ValueError, TypeError): pass else: print("<----------errore ------>") models.py class Gruppi(models.Model): nome_gruppo = models.CharField(max_length=100) class Esercizi(models.Model): nome_esercizio = models.CharField(max_length=100) gruppo = models.ForeignKey( Gruppi, on_delete = models.CASCADE, related_name = 'gruppo' ) class Schede(models.Model): nome_scheda = models.CharField(max_length=100) data_inizio = models.DateField() data_fine = models.DateField() utente = models.ForeignKey( User, on_delete = models.CASCADE, related_name = 'utente' ) class DatiGruppi(models.Model): giorni_settimana_scelta = [ ("LUNEDI","Lunedì"), ("MARTEDI","Martedì"), ("MERCOLEDI","Mercoledì"), ("GIOVEDI","Giovedì"), ("VENERDI","Venerdì"), ("SABATO","Sabato"), ("DOMENICA","Domenica") ] giorni_settimana = MultiSelectField( choices = giorni_settimana_scelta, default = '-' ) dati_gruppo = models.ForeignKey( Gruppi, on_delete = models.CASCADE, related_name = 'dati_gruppo' ) gruppi_scheda = models.ForeignKey( Schede, on_delete = models.CASCADE, related_name = 'gruppi_scheda' ) class DatiEsercizi(models.Model): serie = models.IntegerField() ripetizione = models.IntegerField() peso = models.DecimalField( max_digits = 4, decimal_places = 1, blank = …