Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to count values for a key inside a dictionary
i´m new here and in python. I think my problem is very simple, but I can´t solve it. I have a form with a checkbox. I send 4 selected options, and the querydict recognizes them. But when I ask it to print the 4 values, it only brings me the last one. This is my html: I send the form and it goes to def dietPlan in views.py: def dietPlan(request): # Obtengo los datos que vienen del formulario querydict=request.POST print((querydict)) print((querydict['opcionesCena'])) print(len(querydict['opcionesCena'])) But, the prints are: <QueryDict: {'csrfmiddlewaretoken': ['qNAKsaNlPOO3UY7X76sNy1bEuidxd4WDvUlwJXD6BYxA1JTkyra0A86eYMHJfJ3B'], 'opcionesCena': ['AlimentoID352', 'AlimentoID356', 'AlimentoID360', 'AlimentoID364']}> AlimentoID364 13 Only recognize AlimentoID364 (the last one of the 4) and it takes the number of characters in AlimentoID364. I need to count how many values are for the key 'opcionesCena': if there are 4, or 5, or whatever. Could you help me? Thanks in advance -
Schedule emails to be sent based on the time provided by the user django
I am trying to schedule emails to send based on the date and time user will provide. I looked into celery beat but I didn't find any thing that can help with dynamic time. I also looked into this post: Gmail Schedule Send Email in Django Can anyone please guide me on how can I send schedule emails based on the time user will provide to the system instead of checking into the system again and again like every five minutes or so to send email. -
Google OAUTH 2.0 doesn't show anything in Microsoft Edge (works fine in Chrome)
When clicking on the Continue With Google button, a popup appears (on my website that I created using Django in Python) as expected in Google Chrome asking which account to continue with etc... By doing the same thing in Microsoft Edge, the popup is blank, there is no content. I'm not sure if it's a problem with my code, my OAUTH account or Microsoft Edge itself. This is the popup in Google Chrome (working as normally) This is the popup in Microsoft Edge (not working at all) I expect the top image to be happening in both browsers. Does anyone have any idea why this isn't working in Microsoft Edge? -
How django process the model fields into form inputs
I would like to understand the lifecycle of how Django identifies my model fields and render them as form fields with the whole metadata that the field needs it to process the user input and also the display of that field. -
i tried to clone a django project from github,i have problem with installing requirements.txt ,when i do this command :pip install -r requirements.txt
while executing this command on terminal :"pip install -r requirements.txt" i get this error: error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [25 lines of output] C:\Users\faouz\OneDrive\Bureau\essalmigarage.venv\Lib\site-packages\setuptools\config\setupcfg.py:508: SetuptoolsDeprecationWarning: The license_file parameter is deprecated, use license_files instead. warnings.warn(msg, warning_class) running egg_info creating C:\Users\faouz\AppData\Local\Temp\pip-pip-egg-info-wy4wmc4q\psycopg2.egg-info writing C:\Users\faouz\AppData\Local\Temp\pip-pip-egg-info-wy4wmc4q\psycopg2.egg-info\PKG-INFO writing dependency_links to C:\Users\faouz\AppData\Local\Temp\pip-pip-egg-info-wy4wmc4q\psycopg2.egg-info\dependency_links.txt writing top-level names to C:\Users\faouz\AppData\Local\Temp\pip-pip-egg-info-wy4wmc4q\psycopg2.egg-info\top_level.txt writing manifest file 'C:\Users\faouz\AppData\Local\Temp\pip-pip-egg-info-wy4wmc4q\psycopg2.egg-info\SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details. -
Email Verification Fail in Django webapp hosted on Elastic Beanstalk with nginx
I was making a web app on Django. I tried to send an email verification link to any new user who registers on my website. The thing works fine when I am hosting it on localhost but not upon hosting on AWS Elastic Beanstalk. The verification link generated fine. And I found a very similar issue. Email Verification Fail in Django webapp hosted on Elastic Beanstalk That answers to the case of appach. But I use nginx instead of appach. settings.py ACCOUNT_AUTHENTICATION_METHOD = 'username_email' ACCOUNT_USERNAME_REQUIRED = True ACCOUNT_EMAIL_REQUIRED = True LOGIN_REDIRECT_URL = 'timeline:index' ACCOUNT_LOGOUT_REDIRECT_URL = 'account_login' ACCOUNT_LOGOUT_ON_GET = True ACCOUNT_EMAIL_SUBJECT_PREFIX = '' ACCOUNT_DEFAULT_HTTP_PROTOCOL = 'https' ACCOUNT_UNIQUE_EMAIL = True DEFAULT_FROM_EMAIL = 'tnajun@gmail.com' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' ACCOUNT_EMAIL_VERIFICATION = "mandatory" DEFAULT_AUTO_FIELD = 'django.db.models.AutoField' urls.py from django.contrib import admin from django.urls import path, re_path, include from django.contrib.staticfiles.urls import static from . import settings from django.views.generic import RedirectView urlpatterns = [ path('admin/', admin.site.urls), path('', include('timeline.urls')), path('contact/', include('contact_form.urls')), path('accounts/email/', RedirectView.as_view(pattern_name='timeline:index')), path('accounts/inactive/', RedirectView.as_view(pattern_name='timeline:index')), path('accounts/password/change/', RedirectView.as_view(pattern_name='timeline:index')), path('accounts/confirm-email/', RedirectView.as_view(pattern_name='timeline:index')), path('accounts/', include('allauth.urls')), path('accounts/', include('accounts.urls')), re_path(r'^accounts/confirm-email/[^/]+/', RedirectView.as_view(pattern_name='timeline:index'), kwargs=None), ] python3.7 Django==3.2.4 django-allauth==0.44.0 I tied ACCOUNT_EMAIL_VERIFICATION = "none" on EB and it works fine but that is not what I want. -
Permissions to edit only one field in a Model. Django
I am developing an app which will have different types of users, and the objective is that in a specific Model, it is completed in a community way. Example: 3 types of users: UserTotal, UserParcial, UserBase. Class object name ModelFamily, has 10 fields defined (int,char,date) I need all users to be able to see the class in the admin panel, but depending on which one I can only edit some fields. How could I solve it? I don't have views at the moment, I'm managing everything from the Django Admin panel. Thank you very much for your time! I tried to change the permissions from admin but it is at Object level, not object field. -
redirect Django not working blank response
I tried using reverse, no issues there are in django and when i see the response it is simply blank from django.shortcuts import render from django.http import HttpRequest from django.http import HttpResponse from django.http import JsonResponse from django.shortcuts import redirect def Aviation (request): return render(request, 'Aviation/Aviationtest.html') def SendInformations (request): #a lot of uninteresting code return redirect(reverse("Aviation")) here's my urls.py file from django.urls import path from . import views urlpatterns = [ path("", views.Aviation, name="Aviation"), path("let_me_send_informations", views.let_me_send_informations, name="let_me_send_informations"), path("Informations", views.Informations, name="Informations"), path("SendInformations", views.SendInformations, name="SendInformations") ] I tried using reverse, the complete path, not using reverse and i am sure the directories are set well -
why is django-dbbackup in .psql.bin format? Can I decode it?
I just installed django-dbbackup.. All working as per the doc (linked). One thing slightly puzzles me. Why does it dump into a binary format which I don't know how to read? (.psql.bin). Is there a Postgres command to de-bin it? I found by Googling, that it's possible to get a text dump by adding to settings.py DBBACKUP_CONNECTOR_MAPPING = { 'django.db.backends.postgresql': 'dbbackup.db.postgresql.PgDumpConnector', } This is about 4x bigger as output, but after gzip'ping the file it's about 0.7x the size of the binary and after bzip2, about 0.5x However, this appears to be undocumented, and I don't like using undocumented for backups! (same reason I want to be able to look at the file :-) -
Loading static files in template(background-image: url())-Django
I'm building a template and I want to set an image as background with "background-image: url()". Can anyone help me how can I load the image in the url()? Directory: HTML file(template): <div class="card-inner card-started active" id="home-card"> <!-- Started Background --> <div class="slide" style="background: url('/static/images/bg.jpg');"></div> <!--Where background is gonna load--> <div class="centrize full-width"> <div class="vertical-center"> <!-- Started titles --> <div class="title"><span>Daniel</span>Johansson</div> <div class="subtitle"> I am <div class="typing-title"> <p>a <strong>web developer.</strong></p> <p>a <strong>blogger.</strong></p> <p>a <strong>freelancer.</strong></p> <p>a <strong>photographer.</strong></p> </div> <span class="typed-title"></span> </div> </div> </div> </div> CSS file(layout.html): .card-inner.card-started { text-align: center; } .card-inner.card-started .slide { position: absolute; overflow: hidden; left: 0; top: 0; width: 100%; height: 100%; background-color: #262628; background-repeat: no-repeat; background-position: center center; background-size: cover; } .card-inner.card-started .slide:after { content: ''; position: absolute; left: 0; top: 0; width: 100%; height: 100%; background: #181818; opacity: 0.6; } Setting.py: STATIC_URL = 'static/' STATICFILES_DIR = [ path.join(BASE_DIR, 'static'), ] STATIC_ROOT = path.join(BASE_DIR, 'static') homepage_app/urls.py: urlpatterns = [ path('', views.home) ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) POV: This code had a pre loader that I deleted It, I thought that maybe the problem is there. pre loader HTML: <div class="preloader"> <div class="centrize full-width"> <div class="vertical-center"> <div class="spinner"> <div class="double-bounce1"></div> <div class="double-bounce2"></div> </div> </div> </div> </div> I tried … -
I'm struggling to resolve 2 seemingly ireconsilable dependancy clashes
I have 2 libraries which a code base I'm trying to load and run locally use: django-storages==1.10.1 django-pyodbc-azure==2.1.0.0 The problem I have is I either get this error: django-storages 1.13.2 requires Django>=3.2, but you have django 2.2 which is incompatible., or this one if I try to resolve the first error: django-pyodbc-azure 2.1.0.0 requires Django<2.2,>=2.1.0, but you have django 2.2.1 which is incompatible. Resolving one causes a upgrade or downgrade of Django which triggers either one or the other of the above errors. How do I resolve this? Thanks! -
How to count posts that each hashtag has in django queryset
class Post(models.Model): post_uuid=models.UUIDField( default=uuid.uuid4, editable=False) language = models.ForeignKey( Languages, default=2, on_delete=models.CASCADE) is_post_language = models.BooleanField(default=True) description = models.CharField(max_length=400, null=True, blank=True) hash_tag = models.ManyToManyField('HashtagName', through='Hashtag', related_name='hash_tag', blank=True) created_on = models.DateTimeField(default=timezone.now) def __str__(self): return '{}'.format(self.post.id) class HashtagName(models.Model): Hashtagname = models.UUIDField(default=uuid.uuid4, editable=False) hashtag_name = models.CharField(max_length=150, null=False, unique=True) created_on = models.DateTimeField(default=timezone.now) def __str__(self): return self.hashtag_name class Hashtag(models.Model): hashtag_uuid = models.UUIDField(default=uuid.uuid4, editable=False) tag_name = models.ForeignKey(HashtagName,on_delete=models.CASCADE) posts = models.ForeignKey(Post, on_delete=models.CASCADE) created_on = models.DateTimeField(default=timezone.now) def __str__(self): return self.hashtag_uuid I have these classes. Im making one api to get the list of trending hashtag What im trying to do is when someone type #planet And i have list of these below hashtag #planetearth Used in 7 posts #planetjuypiter used in 5 posts #planetmercury used in 3 posts Etc That starts with the keyword i have passed from frontend. So i want to get the list of top 10 hashtag that starts with the keyword I passed from front end and based on in how many posts they are used. -
Django not parsing Unity WWWForm multipart/form-data
I have a django backend (3.2.15) with django rest framework (3.13.1) and I have an endpoint where I post a string and a file. When I use postman, it works fine, but using Unity WWWForm library, it doesn't. The problem that I see, is that when I receive the post from Unity, for some reason, is not parse correctly, for instance, if I send only the string value, the request.POST value is set as <QueryDict: {'personal_account': ['13123123123\r\n--e2FxgWvU1dzZvTibOpwyxx07RvZnbNzj2BhnBpUY--\r\n']}> instead of <QueryDict: {'personal_account': ['13123123123']}> as it works with postman. When I include the file in the form, request.POST and request.FILE are simply empty. Here is my code: Unity: List<IMultipartFormSection> formData = new List<IMultipartFormSection>(); formData.Add(new MultipartFormFileSection("file", file, AccountsManager.Instance.uiTransferNotificationsBuy.fileName, "image/jpeg")); formData.Add(new MultipartFormDataSection("string", string)); UnityWebRequest www = UnityWebRequest.Post(url, formData); byte[] boundary = UnityWebRequest.GenerateBoundary(); www.SetRequestHeader("Content-Type", "multipart/form-data; boundary = " + System.Text.Encoding.UTF8.GetString(boundary)); www.SetRequestHeader("x-api-key", apiKey); www.SetRequestHeader("Authorization", PlayerPrefs.GetString("IdToken")); www.downloadHandler = new DownloadHandlerBuffer(); yield return www.SendWebRequest(); Django is a default create method from ModelViewSet Couldn't find any reported issues in both projects. Any idea what might be the issue? Thanks -
I need to make this time task for my advertisement website
I have created_at in django table. How can I gather a week with recent datetime. I need to do it + 7 days. Just tell me how can I do it. I need to get 7 days -
GSMA mobile money api integration for mobile payment
I want to integrate GSMA mobile money with my python code. Didn't find any github repo for the same, also there is no SDK for python on GSMA developer portal. Can anyone help ? -
Permisos para editar unicamente un campo en un Modelo. Django
estoy desarrollando una app la cual va a tener distintos tipos de usuarios, y el objetivo es que en un Modelo puntual, se complete de manera comunitaria. Ej: Tengo una app que tiene creados 3 tipos de usuarios: UsuarioTotal, UsuarioParcial, UsuarioMinimo. Una clase que es ModeloFamilia, que consta de 10 campos (int, char, date, etc) Puedo hacer que UsuarioParcial vea todo el modelo, pero unicamente pueda editar los 4 primeros campos del mismo? UsuarioTotal pueda ver/editar todo. Y UsuarioMinimo, solo pueda editar 1 campo que coincide con uno de los de UsuarioParcial? Como podria resolverlo? de momento no tengo vistas, estoy manejando todo desde el panel de Admin de Django. Muchas gracias por su tiempo! Probé cambiar los permisos desde admin pero es a nivel Objeto, no campo de objeto. -
I want to use product foreign key but it is too slow
class Item(models.Model): title = models.CharField(max_length=100) model = models.CharField(max_length=100, blank=True, null=True) sku = models.CharField(max_length=100, blank=True, null=True) ean = models.CharField(max_length=100, blank=True, null=True) price = models.FloatField(blank=True, null=True) inventory = models.IntegerField(blank=True, null=True) sales_price = models.DecimalField(decimal_places=2, max_digits=15, blank=True, null=True) web_shop_price = models.DecimalField(decimal_places=2, max_digits=15, blank=True, null=True) bb_price = models.DecimalField(decimal_places=2, max_digits=15, blank=True, null=True) discount_price = models.FloatField(blank=True, null=True) categorie = models.ForeignKey(Categorie, on_delete=models.CASCADE, null=True, blank=True) # slug = models.SlugField(blank=True, null=True) description = models.TextField(blank=True, null=True) image = models.ImageField(upload_to='images', null=True, blank=True) As you can see, This is not a small amount of queries. class SaleItem(models.Model): invoice_id = models.PositiveIntegerField(auto_created=True) product = models.ForeignKey(Item, on_delete=models.CASCADE) I have about 15000+ Item models registered in database. therefore when i use the foreign key in SaleItem model, it takes too much time, drops performance. I am using Jawsdb(a 10$ plan) and Mysql. I think other than the huge data, its because the ram of the database is shared. This is taking my life. I need help seriously. -
Updating records in Django based on date
I have a model in Django called Marketplaces, which has attributes Name, Status and date. The default value for Status is "Open". I want it so that the Status of a Marketplace object is updated from "Open" to "Completed" after the date has passed. models.py: class EventStatus(models.TextChoices): Open = "Open" Closed = "Closed" Completed = "Completed" Archived = "Archived" class Marketplace(models.Model): Creator = models.ForeignKey(User, on_delete=models.CASCADE) Name = models.CharField(max_length=100) date = models.DateTimeField(default=timezone.now) Status = models.CharField(max_length=9, choices=EventStatus.choices, default=EventStatus.Open) def __str__(self): return self.Speaking_Event_Name def status(self): return EventStatus.Completed if timezone.now() > self.date else self.Status I tried creating a function for it, and it does not seem to work. I am unsure if I am in the correct path or not and I have been stuck for a week. -
Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last):
please help trying to runserver and getting this error, this error starts from moving the project folder. even i try undo button. still having the same issue. is any solution to get back normal. -
The session between Django and database
I wrote the database settings of PostgreSQL in settings.py as shown below : "settings.py" DATABASES = { 'default':{ 'ENGINE':'django.db.backends.postgresql', 'NAME':'postgres', 'USER':'postgres', 'PASSWORD':'admin', 'HOST':'localhost', 'PORT':'5432', } } <Questions>: When starting Django server as shown below, does the session between Django and PostgreSQL start and keep connected without disconnected? kai@DESKTOP-QVRCPAL MINGW64 ~/django-project/ (main) $ python manage.py runserver 0.0.0.0:8000 Watching for file changes with StatReloader Performing system checks... When reloading Django server by changing file contents, does the session between Django and PostgreSQL disconnect and connect again? C:\Users\kai\django-project\store\views.py changed, reloading. Watching for file changes with StatReloader Performing system checks... When stopping Django server with CTRL + C as shown below, does the session between Django and PostgreSQL disconnect? kai@DESKTOP-QVRCPAL MINGW64 ~/django-project/ (main) $ -
What is the equivalent of "success" and "complete" from jQuery to Javascript
I currently have a working solution of an ajax jquery where on success it sets an interval of a function for 1 second. On complete it clears the interval and it works perfectly fine. However, i am trying to convert this working ajax jquery to pure javascript and i am having difficulties working out how to convert "success" and "complete". What i have tried is using "onreadystatechange" and check if the ready state is equal to 4 (as the operation is done) and set the interval function and outside the if statement is to clear the interval. Doing this current method does not work as the interval keeps going on each second and i am not sure if it is because my clearInterval function is not getting used or if it is because the readystate is always at 4 so the setInterval function keeps getting run. jQuery(Working perfectly): $(document).on('submit','#post-form',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:'/sendValue/', data:{ value:$('#value').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, success: function success(){ setInterval(displayNewValue, 1000) }, complete: function complete(){ clearInterval(success); }, }); document.getElementById('value').value = '' }); function displayNewValue(){ var test = $("#content"); test.scrollTop(test[0].scrollHeight) } Javascript: document.addEventListener('DOMContentLoaded', () =>{ const post_form = document.getElementById('post-form'); post_form.addEventListener('submit', function(event){ event.preventDefault(); let request = new XMLHttpRequest(); request.open("POST", "/sendValue/", true); … -
How do I solve this "TemplateDoesNotExist" problem
Keeping getting this error when i try running my Django application, The templates folder is inside the project folder so its on same level with app folder I have tried importing os and added os.path.join(SETTINGS_PATH, 'templates') to the TEMPLATE DIR but not working -
Django: Ajax call giving error even when everything is OK
I am using ajax to get details of variant and it is running correctly but ajax show error;As you can see in the error log, status is ok and I am receving data in responseText This is my function ajax is calling -
Django sitemap category page location not working
I made sitemap to my site but i have some problems. First problem is end of the sitemap.xml page, lots of codes in it, but how can i remove these lines. Here is my sitemap https://www.endustri.io/sitemap.xml And here is the codes which i wanna remove... And Second problem is I have category page forexample: https://www.endustri.io/kategori/makine/ When i make sitemap class like this class CategorySitemap(Sitemap): changefreq = 'weekly' priority = 0.8 def items(self): return Category.objects.all() def lastmod(self, obj): return obj.date_added In sitemap my category links be like this https://www.endustri.io/makine/ but it must be like this https://www.endustri.io/kategori/makine/ How can i fix this? Here is my model.py from django.db import models from django.contrib.auth.models import User from tinymce import models as tinymce_models from django.urls import reverse class Category(models.Model): title = models.CharField(max_length=255) slug = models.SlugField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Categories' def __str__(self): return str(self.title) def get_absolute_url(self): return reverse('detail', args=[str(self.slug)]) class Post(models.Model): category = models.ForeignKey(Category, related_name="posts", on_delete=models.CASCADE) title = models.CharField(max_length=300) slug = models.SlugField(max_length=300) intro = models.TextField() body = tinymce_models.HTMLField() description = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) featured_photo = models.ImageField(null=True, blank=True, upload_to="blog/") date_added = models.DateTimeField(auto_now_add=True) num_reads = models.PositiveIntegerField(default=0) def __str__(self): return str(self.title) def get_absolute_url(self): return reverse('detail', args=[str(self.slug)]) And sitemaps.py from django.contrib.sitemaps import Sitemap from … -
DJANGO HTML and Python - How to display list in horizontal view with proper spacing
I am trying to make a personal website to track my list of rentals so that everywhere i go, i can view who are still not paid. (btw, i am not an IT person.. just trying to be techie and see how far i can go with it..) i have a csv file, it contains the following information. serial number, name, address, age, monthly_rent, unpaid_months, total_unpaid i am able to show it in the html, but it not aligned properly. Here's what i tried HTML `RENT {% for dt in data %} {{ dt }} {% endfor %} ` VIEWS.PY ` out = [] * 4 count = 0 rental_list = open('rent/static/rentals.txt', 'r') while True: line = rental_list.readline() if not line: break display = line.replace(',', ' ') if not count == 0: out.append(display) count += 1 rental_list.close() return render(request, 'main.html', {'data' : out})` i have two records as test. it shows like this unfortunately 0001 AAA BBB CCC DDD EEE FFF 0002 GGG HHH III JJJ KKK LLL I wanted it to be flexible, like in a specific coordinates like this when i add the headers. SN NAME ADDRESS RENT UNPAID(MOS) TOTAL UNPAID AAA. BBB CCC DDD EEE <button> If …