Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django. Non-ascii field doesn't create slug. I expect to get transliteration, but getting an empty field and error
I have simple Model with title and slug fields. I want to accept non-Latin characters as a title and transliterate them into Latin slug. Specifically, I want to transliterate Cyrillic characters, say 'Привет, мир!' into Latin 'privet-mir'. Instead of slug I'm getting following error: Reverse for 'blog_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['blog/(?P[-a-zA-Z0-9_]+)/$'] Django Version: 3.1.5 Python Version: 3.9.1 Exception Type: NoReverseMatch Exception Value: Reverse for 'blog_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['blog/(?P<slug>[-a-zA-Z0-9_]+)/$'] Model from django.db import models from django.template.defaultfilters import slugify class Post(models.Model): title = models.CharField(max_length=70) slug = models.SlugField(null=False, unique=True, allow_unicode=True) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) return super().save(*args, **kwargs) def __str__(self): return self.title admin.py from django.contrib import admin from .models import Post class PostAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('title',)} admin.site.register(Post, PostAdmin) urls.py from django.urls import path from . import views app_name = 'blog' urlpatterns = [ path('', views.BlogList.as_view( template_name=app_name + "/blog_list.html"), name='blog_list'), path('<slug:slug>/', views.BlogDetail.as_view( template_name=app_name + "/blog_detail.html"), name='blog_detail'), ] views.py from .models import Post from django.views.generic import ListView, DetailView class BlogList(ListView): model = Post class BlogDetail(DetailView): model = Post blog_list.html (for each post) <a href="{% url 'blog:blog_detail' blog.slug %}">{{ blog.title }}</a> blog_detail.html (short) <h1>{{ blog.title }}</h1> NoReverseMatch at /blog/ -
Learning django but i get an error in a simple poll app
I'm trying to learn django from scratch. So I found a tutorial online:Tutorial simple poll app and I followed it and it just replies: in the terminal: Not Found: /polls/ [30/Jan/2021 00:12:39] "GET /polls/ HTTP/1.1" 404 1957 On the http://localhost:8000/polls/ web page: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ The current path, polls/, didn't match any of these. I went over all the syntax and it all matches up. please help me I don't know how to solve this probleme -
My register form will not save the image to my S3 Bucket
I am losing my mind and not sure whats going on. I created a register page and everything saves except for image. However if the user does log in even though the image didn't save. In the profile template they can upload it and it will save just fine. I need it to save on my register form. I also know this isn't idea for a user experience but this way is needed so a admin can set up users. I know my AWS S3 is set up correct with my IAM and in my settings.py file. I'm going to have my code below. View def register(request): # techs = Employee.objects.all() # empFilter = EmployeeFilter(request.GET, queryset=techs) # techs = empFilter.qs # copyTech = techs[0] if request.method == 'POST': user_form = UserRegisterForm(request.POST) if user_form.is_valid(): user_form.save() user_id = User.objects.get(username=user_form.cleaned_data['username']) user_profile = Profile.objects.get(user=user_id) pdb.set_trace() profile_form = ProfileRegisterForm(request.POST, request.FILES, instance=user_profile) if profile_form.is_valid(): profile_form.save() return redirect('clearview:login') else: profile_form = ProfileRegisterForm() user_form = UserRegisterForm() context = { 'user_form': user_form, 'profile_form': profile_form, } return render(request, 'users/register.html', context)enter code here form class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class ProfileRegisterForm(forms.ModelForm): CROP_SETTINGS = {'size': (300, 300), 'crop': 'smart'} locationName = … -
Sending additional info in post request
I am trying to implement a form with a "Contacts" datalist, I need to get the id number of the contact in order to process it in the db in Django but I don't want the id to be shown to the user, I want the datalist to have the "normal" info. The datalist code is the following: <div class="form-group"> <label class="form-label" for="contactOptions">Contact:</label> <input class="form-control" name="contact" list="contactOptions" placeholder="Type contact"> <datalist id="contactOptions"> {% for contact in contact_options %} <option> {{contact.id}}: {{ contact.info }} </option> {% endfor %} </datalist> </div> To sum up: Want to populate the datalist with the info of the contacts except the id. Need to get the contact id when using request.post in the views in Django. I have a JS file to manipulate the HTML if required. -
Populate Django SearchVectorField with bulk_create()
I'm trying to use the performance SearchVector, using SearchVectorField in model but it seems it is not possible to populate SearchVectorField on insert for some reason. All documentation I read only gives me either .annotate(search=SearchVector('...')) or .update(search_vector=SearchVector('...')) and I don't want to use either. Using annotate approach would be slower. Using "performance" update approach I need to first create the record and do a second query to populate the SearchVectorField. Because I'm using .bulk_create() it would make sense to insert SearchVector results on the fly since I have all the values already and not create another query to update SearchVectorField but for some reason it is not possible. Is it really not possible or am I missing something? -
Django Rest Framework: set serializer context for serializer that is not serializer_class
I'm having an issue in one of my viewsets where I need to use a different serializer for one particular endpoint. The issue is that I need to access the context and the method get_serializer_context on my viewset is not being called for this endpoint that uses a different serializer than the one defined in the viewset aswell. How can I call this method or find some other way of setting the context for this serializer in this endpoint? -
django extra fields on profile page
I already created a Django App, registration, login, and profile and edit profile pages. Everything is working fine, and now I need to add on the profile page more fields, such as phone number, home address, office address, city, estate, how can I add those fields in the profile and allow the user to fill in the data and store it on the database? Thank you! -
Django + Heroku + Cloudinary (for static files) not showing
I am using cloudinary as my static files storage. When I deploy to heroku, all the static files get uploaded successfully. However, when I visit my admin section, the css is "not found". Apparently it is loading the file with the wrong hash. Example, if the actual file is "base.98at7sdt7.css", what gets loaded is "base.8799894d3e.css" which obviously doesn't exist so it returns a 404. Any idea on what could be wrong? -
Why does text exceed bootstrap boundary?
I have some text and its inside an bootstrap media-body. When I load, the page the text passes the media box and overflows it, like so: Image Problem As you can see the text exceeds the boundary. So how would I fix that. My code is this: {% extends "blog/base.html" %} {% block content %} <article class="media content-section"> <a href="{% url 'user-posts' post.author.username %}"> <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}"> </a> <div class="media-body"> <div class="article-metadata"> <title>Post: "{{ object.title }}"</title> <a class="mr-2" href="{% url 'user-posts' object.author.username %}">{{ object.author }}</a> <small class="text-muted">{{ post.date_posted|date:"F d, Y" }} | Appropriate for ages {{ post.appropriate_for_ages }} and up | <i class="fa fa-map-marker"></i> {{ post.location }}</small> &nbsp;{{ post.blog_view }} views {% if object.author == user %} <div> <a class="btn btn-secondary btn-sm mt-1 mb-1" href="{% url 'post-update' object.id %}">Update</a> <a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'post-delete' object.id %}">Delete</a> </div> {% endif %} </div> <h2 class="article-title">{{ object.title }}</h2> <p class="article-content">{{ object.content|safe }}</p> <hr> <div class="article-footer"> <style>.content-likes {display: inline-block;padding-right: 5px; }</style> <h4 class="content-likes">{{ post.likes }}</h4><h5 class="content-likes">likes</h5><br> {% if user.is_authenticated %} <a href='{% url "like_post" post.id %}'><i class="fa fa-thumbs-up" style="font-size:36px; color:green"></i></a> <a href='{% url "dislike_post" post.id %}'><i class="fa fa-thumbs-down" style="font-size:36px; color:red"></i></a> {% else %} <a onclick="alert('In order to … -
DeserializationError when adding fixture on server (loaddata)
I am trying to add my data to database in my server. I use exactly the same JSON file in my local machine and it works. But when I do the same in server it gives me Deserialization Error. The JSON file is so big that I can't show it here but I am sure there is no typo. I did all migrations and database works - I can add object from admin dashboard. How can I solve this error? The error I get: Traceback (most recent call last): File "/home/testuser/myprojectt/myvenv/lib/python3.8/site-packages/django/core/serializers/json.py", line 69, in Deserializer objects = json.loads(stream_or_string) File "/usr/lib/python3.8/json/__init__.py", line 357, in loads return _default_decoder.decode(s) File "/usr/lib/python3.8/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python3.8/json/decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/testuser/myprojectt/myvenv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/testuser/myprojectt/myvenv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/testuser/myprojectt/myvenv/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/home/testuser/myprojectt/myvenv/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = … -
SMTPSenderRefused when sending email from Django app using Google Workspace
I'm getting the following error message when trying to send an email from my Django app using a Google Workspace account: Error message Screenshot of my Django settings: Django settings Access for less secure apps is enabled for this account in the Google Workspace settings. The IP address from which the email is sent is added to the Google Workspace relay settings (sorry for German screenshot): Relay settings What is missing? Google Support seems unable to help me. Thanks! -
Change label color of Django user form
I added a user module to my project and I used the default Django user model for that. I've to change the styling to suit my other pages. The background color is black. The problem is default labels and error messages (eg: "username", "password", "Enter the same password as before for verification") generated by Django is also black and not visible now. How to change the label colors so that they are visible again? I'm a newbie to both development & StackOverflow, apologies if I have used incorrect terms or tags in my question. Thanks in advance.screenshot of the login form (highlighted is my problem -
Failing to display json into html with ajax
I am implementing a 'load more' button for my posts. With ajax this is what I'm doing to display the loaded posts into my html: success:function(res){ var _html=''; var json_data=$.parseJSON(res.posts); $.each(json_data,function(index,data){ _html+='<div class="post-box col-md-1">\ <div class="info-box mb-4">\ <div>\ {% if '+data.fields.cantidad+' == 1 %}\ <h3>'+data.fields.donador+'</h3><text>te donó '+data.fields.cantidad+' '+data.fields.objeto+'.</text>\ {% else %}\ <h3>'+data.fields.donador+' </h3><text>te donó '+data.fields.cantidad+' '+data.fields.objeto+'s.</text>\ {% endif %}\ <br>\ <text>'+data.fields.whenpublished+' </text>\ {% if '+data.fields.message+' != "" %}\ <hr>\ <text>'+data.fields.message+'</text>\ {% endif %}\ </div>\ </div>\ </div>'; }; This is my model: class Donacion(models.Model): creador_d = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) creation_date = models.DateTimeField(auto_now_add=True, blank=True) message = models.CharField(max_length=300, null=True, blank=True) donador = models.CharField(max_length=30, null=True, blank=True) cantidad = models.IntegerField() objeto = models.CharField(max_length=30, null=True, blank=True) def whenpublished(self): now = timezone.now() diff = now - self.creation_date if diff.days == 0 and diff.seconds >= 0 and diff.seconds < 60: seconds= diff.seconds if seconds == 1: return "Hace " + str(seconds) + " segundo" else: return "Hace " + str(seconds) + " segundos" if diff.days == 0 and diff.seconds >= 60 and diff.seconds < 3600: minutes= math.floor(diff.seconds/60) if minutes == 1: return "Hace " + str(minutes) + " segundo" else: return "Hace " + str(minutes) + " minutos" if diff.days == 0 and diff.seconds >= 3600 and diff.seconds < … -
Django collectstatic is not pushing to AWS S3
Please Help i have searched and reconfigured my project so many times i have created new aws accounts but still having the same issue python manage.py collectstatic keeps reverting to old folder i used for testing after configuring my aws s3 bucket for django this way # AWS service variables AWS_SECRET_KEY_ID = config('AWS_SECRET_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = 'd1l47x08equ47x.cloudfront.net' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None AWS_LOCATION = 'static' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' nothing happens when i run collect static Please someone help -
Django creating a web site with fully coded html
I have a project where I have to design the web page and create a login system for the user. I wrote a fully build HTML, CSS and javascript web design and now I have to connect with Django to build a login system. I know it's a bit a simple question but is it so hard to build the templates for fully made HTML? I searched everywhere for such an example like that but in every video I watch people starting the web design from to top. -
Is it mandatory to use sessions in Django to stop one user's information being displayed to another?
Hi I'm very new at Django and I'm sorry if this is a stupid question. I have created an application using Django where I have a form accepting information using the POST method. In views.py I then get the information I want and store it in a variable to be displayed back to the page. However, when I deployed this to heroku, I noticed anyone who accessed the webpage would enter their name and their name would be visible to everyone. I didn't store it in a database, it's only stored in a variable. How do I make it so that all user entered by a user stays on only their page when they access it? Do I need to use sessions? -
How to create a server side timer/countdown in Django Channels?
Lets say I am building a pub-quiz app with Django Channels (Websockets). There are 10 questions and each question has a time limit and a button to add extra 5 seconds. I know a possibility would be to haver the timer client-side, but I need it to be server-side to avoid tampering with the Js causing problems since there are many players involved. How can I create a timer in Django, server-side? Once the timer is up, it would need to call a function to fetch the next question. I would know how to do it with a while loop: While True: if datetime.now() == question_end_time: fetch_next_question() But from what I have read this does not seem to be a good idea due to blocking the thread. Is there any other way how to check every second if the time for the question is up and is so, call a function? Thanks in advance. -
Django Routing w/ subApplication
What I have: a Django Project that is acting as a REST API through Django Rest Framework. a number of Django Apps that are controlling the logic of my Postgres DB. What I am trying to do: Create a new Django App that represents a Service / Integration with Robinhood Within ^^ I want to structure my logic in subApplications in order to separate all logic for a user vs a transactions vs a transfers etc ... This entire Django App & all subApplications are APIs ONLY ... they will never need models / migrations but they will eventually communicate with the other Django Apps CODE STRUCTURE: Main Django Project ├── APP_holdings ├── APP_logs ├── APP_unique ├── APP_users ├── ⭐️⭐️ DJANGO │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-38.pyc │ │ └── wsgi.cpython-38.pyc │ ├── asgi.py │ ├── fixtures │ │ ├── platforms.json │ │ └── symbols.json │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── EXAMPLE.env ├── Pipfile ├── Pipfile.lock ├── Procfile ├── README.md ├── ⭐️⭐️ SERVICE_robinhood │ ├── README.md │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── models.py │ ├── tests.py │ ├── urls.py │ ├── ⭐️⭐️ user │ │ ├── __init__.py … -
Django view not getting ajax request
I have a script in my template that tries to send data to a django view during onbuttonclick event. My problem is that the request doesn't seem to make it to the view. The browser console sees the request properly and all, but the django view does't even return true when i call request.is_ajax(). request.method returns GET instead of POST, and the data is empty. This behavior is persistent regardless of the request type. html <a onclick="setGetParameter(this)" pid="some_id">Some Text</a> .js <script> var csrftoken = Cookies.get('csrftoken'); function setGetParameter(el){ var stuff = $(el).attr('pid'); $.ajax({ type: 'POST', headers: { "X-CSRFToken": csrftoken }, url: '/view_url/', data: {'datatopass': stuff}, success: function(response){ alert(response); } }); } </script> urls.py path('view_url/', views.test), path('', views.home), views.py def test(request): output = request.is_ajax() return HttpResponse(output) -
How to index a resampled pandas dataframe by datetime?
I am using the django_pandas package to obtain a Pandas dataframe from stored Django models. df = qs.to_dataframe(['time', 'price_open', 'price_high', 'price_low', 'price_close'], index='time') Now I want to access the dataframe by a datetime, however, this does not work. Printing df looks like this, where the time column has a weird position: If I do print(df.keys()) I get the following results: Index(['price_open', 'price_high', 'price_low', 'price_close', ], dtype='object') but I more expected time. Also, df.columns does not contain time but only the other columns. How can I access df by a given datetime? Why is time not the key for df? Thanks! -
Allow REST api access only by personal webiste (not other requests servcices)
I know this question was asked before but I didn't found a feasible solution for my problem, I implemented CORS inside my Django application in order to restrict the domain access and also used CSRF tokens for secure data transfer against unsecured HTTP methods, but still I can make requests to an API via postman or other HTTP services, how can I avoid that? NOTE: my app doesn't make use of users with oAuth system and more, it makes a POST request to the database in order to get a token (app term specific) regardless of the person who is making the request, but I want only my website to make such request and NO MORE, how to do that? -
How to POST a data into the restricted REST API url without logging in as a user?
In my Django app. I use django.contrib.auth as authentication for users, I also have django rest framework APIs. I have enabled. 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.SessionAuthentication', ), Since, I can only access the API data by logging in through the user account, but on my project. I have a sensor(IoT) that have to POST into the api 127.0.0.1/api/data/, How can I authenticate my sensor(IoT) to POST request into the API url without expiring session? or How to POST a data into the restricted REST API url without logging in as a user? Thanks! -
should admin-only fields be extracted into a dedicated model which has a OneToOne relation to the original model?
I have the following model class User(AbstractUser): # other fields... billing_active = models.BooleanField( _('Billing active'), default=True, help_text=_( 'designates whether the user should be charged' ) ) billing_start = models.DateField(_('Billing cycle start')) billing_end = models.DateField(_('Billing cycle end')) billing_charge = models.DecimalField( _('Charge'), max_digits=5, decimal_places=2, help_text='amount to be charged' ) by looking at those prefixes billing_* it seems that fields should belong to a new object, it seems OK since it's just a database representation. But billing_active and billing_charge are admin fields and can't be changed by user, would it be good to create a new model UserBillingSettings which contains all those fields? then I could use django's builtin permissions system: class User(AbstractUser): # fields ... class UserBillingSettings(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='billing_settings') # billing fields -
Is it possible to group by field name using django orm?
I have two models: class ExampleOne(models.Model): # some fields class ExampleTwo(models.Model): example_one = models.ForeignKey( "App.ExampleOne", on_delete=models.CASCADE, related_name="examples", ) field_one = ... field_two = ... And I created this view for my endpoint: class MyViewSet(viewsets.ViewSet): def list(self, request): queryset = ExampleOne.objects.all().values( "id", "examples__field_one", "examples__field_two", ) return Response({"data": queryset}) That return this: { "data": [ { "id": 1, "examples__id": 1, "examples__field_one": foo, "examples__field_two": bar, }, { { "id": 1, "examples__id": 2, "examples__field_one": foo, "examples__field_two": bar, }, { "id": 2, "examples__id": 3, "examples__field_one": foo, "examples__field_two": bar, } But I wanted a way to group by the first model. It's possible? I wanted something like this: { "data": [ { "1": [ { "examples__id": 1, "examples__field_one": foo, "examples__field_two": bar, }, { "examples__id": 2, "examples__field_one": foo, "examples__field_two": bar, }, ], "2": [ { "examples__id": 3, "examples__field_one": foo, "examples__field_two": bar, }, ] } } It's possible? All information I find about grouping involves values (count, sum, ...). But I just wanted to group by one field (model one id). -
How to change email settings in django dynamically
I want to make an email sender app that took user email and password and send an email to multiple recipients. I am not sure whether it is possible to do because we have to provide Email_HOST_USER in settings. If anyone can help me with explanation please?