Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django2 vs django3 how to write path instead of url
so I'm trying to type this in django3 with path url(r'^tag/(?P<slug>[-\w]+)/$', TagIndexView.as_view(), name='tagged') I tried tag/slug but I guess it didn't work. -
Hosting platforms for python django api with docker
What is the best platform to host a python django api with a react front end and also have a docker setup that runs jobs in the background which populates my data -
Solutions for tracking time user spent on a context
I working on case management system. We have operation staffs working on filling out/processing data for a case. The system is built using React on frontend and Django on backend. The URL for a single case is like this pattern: /case//< action name> I'm looking for a solution (open source or commercial) to track user activities and eventually calculate how much time a user spends on a case, e.g: how much time in total operation staffs spend on a specific case, and how much time on average operation staffs spend on a single case, etc. Right now I'm looking into Real User Monitoring(RUM) solutions like Datadog RUM. The data structure can be used to achieve what I want but the challenge is there is no way to extract those raw data or stream it to another database to do further calculations. Am I going in the right direction? Really appreciate any suggestion. -
What's the pros and cons of having a model for each Product Attribute?
I have a two generic models in my app: ProductAttributes and ProductAttributesValue (besides Product and ProductCategory, which are not relevant for this discussion). These two models contain respectively all the different attributes and their values. For example, "brand" as an Attribute, and "nike" and "addidas" as its Attribute Values. I'm running into an issue with this setup, though, as I want to create a page for each brand. I think this would be easier, if brands did not share model with other attributes, like color, size etc., which I do not want to create unique pages for. There may also be other scenarios. In general, what's the pros and cons of having a unique model for each Product Attribute, versus having a shared model? Note: I want to still be able to have long URLs that contain one category and several attribute values, like domain.com/shoes/red/nike -
CSS not work without ".min.css" as the name format
I'm currently using bootstrap on django but somehow one of the CSS below does not work this doesn't work: https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.css this works!! https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css I ensure them they have the same version of bootstrap. This is my static file code on my base template html: <!-- THIS DOES NOT WORK --> {% load static %} <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"> <!-- THIS WORKS --> {% load static %} <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> my static dirs contains both of the file. does anyone know why the .min.css works? or any other possible causes on why the .css file does not work? I want to use the .css not the min. -
django-oauth-toolkit : Test Custom TokenView
I am trying to write a unit test for a custom implementation of the django-oauth-toolkit TokenView The reason for inheriting from the TokenView is to require a 2FA token before generating the access token. Below is what the view looks like class CustomTokenView(TokenView): @method_decorator(sensitive_post_parameters("password")) def post(self, request, *args, **kwargs): meta = request.META grant_type = urllib.parse.parse_qs(request.body.decode("utf-8")).get("grant_type")[0] if grant_type == "password": """ Users trying to log in with email and password. """ try: email = urllib.parse.parse_qs(request.body.decode("utf-8"))["username"][0] except KeyError: return JsonResponse(data={"message": "Email is required", "status": "0"}, status=400) try: token = urllib.parse.parse_qs(request.body.decode("utf-8"))["token"][0] except KeyError: return JsonResponse(data={"message": "Token is required", "status": "0"}, status=400) email = simplefunctions.remove_unicode(email) user_obj = CustomUser.objects.filter( email=email, is_active=True, is_staff=True, is_account_disabled=False).first() if user_obj is None: return JsonResponse(data={"message": "Invalid Email", "status": "0"}, status=400) else: application_log.debug(f"User {user_obj.email} tried to login with password. Request header data {meta}") if token: if not services.UserService.is_valid_2fa_token(user_obj, token): return JsonResponse(data={"message": "Invalid Token", "status": "0"}, status=400) return super().post(request, *args, **kwargs) return JsonResponse(data={"message": "Invalid grant type", "status": "0"}, status=400) I can extract each request data and perform validation on them but returns an error when the return super().post(request, *args, **kwargs) is called. What my test looks like from oauth2_provider.settings import oauth2_settings from oauth2_provider.models import get_access_token_model, get_application_model from django.contrib.auth import get_user_model from django.utils import … -
Django - Select don't save form
I have a form with categories (MultipleChoiceField), but I need "select categories". I'm having trouble with widget categories. When I remove the "categories" widget (from the code below), save the form without a problem. But when I use this widget form don't save. I tried a lot of combinations. choices = Category.objects.all().values_list('name', 'name') class ZeroForm(forms.ModelForm): class Meta: model = IdeaPage fields = ['title','categories'] widgets = { 'categories': forms.Select(choices=choices, attrs={'class': 'form-control'}), } -
how to fix memory leak issue ''Possible EventEmitter memory leak detected''?
I am working on React App, when I run it on localhost it takes significate time to load the homepage, and even with I just refresh the page( takes about 5 seconds to load) and some time is not from the first refresh, I have got this warning lately, I am familier with the term the memory leak theoretically, but not in-depth when come to debug it. and I am running Django server on the backend if this helps! (node:18208) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 _cacheReadyToWrite listeners added to [Browserify]. Use emitter.setMaxListeners() to increase limit -
How to automatically index new data in elasticsearch and django
as the title describes I am using django and elasticsearch and currently everytime I want to index new data I run the command python manage.py search_index --populate I want to index new data automatically anyone has a clue how can I do this? -
What's causing the tuple and get error in the django?
I am learning from the book Django3 by example. I am having a problem and I am unable to debug it. I am unable to understand what does this mean? I am displaying list of posts on a page. This error happens when I click the particular post to view whole of the blog post. Here is my error: - Traceback (most recent call last): File "/mnt/g/Programming/django/blog/my_env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/mnt/g/Programming/django/blog/my_env/lib/python3.8/site-packages/django/utils/deprecation.py", line 96, in __call__ response = self.process_response(request, response) File "/mnt/g/Programming/django/blog/my_env/lib/python3.8/site-packages/django/middleware/clickjacking.py", line 26, in process_response if response.get('X-Frame-Options') is not None: Exception Type: AttributeError at /blog/2022/1/19/what-is-model/ Exception Value: 'tuple' object has no attribute 'get' my views.py from django.shortcuts import render, get_object_or_404 from .models import Post # Create your views here. def post_lists(request): posts = Post.published.all() return render(request, 'blog/post/list.html', { 'posts': posts}) def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug = post, status='published', publish__year=year, publish__month=month, publish__day=day) return(request, 'blog/post/detail.html', {'post': post}) My models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published') ) title = models.CharField(max_length=250) slug = … -
I can't create a django project
I typed django-admin startproject myproject in command pallet and it gave me this error message: 'django-admin' is not recognized as an internal or external command, operable program or batch file. I would realy appreciate some explination or tips. Thank you! -
is there any way to save child model class with pandas in save method of parent model class while saving parent model class in django
i want to save an excel file to a model class and its detail into another one by pandas without using pandas to do it in view engine = create_engine('sqlite:///db.sqlite3') class Excel(models.Model): name = models.CharField(max_length=150, unique=True) excel = models.FileField(upload_to=set_name_and_folder_file) class ExcelDetail(models.Model): title = models.CharField(max_length=100) extract_excel = models.ForeignKey(ExtractExcel, on_delete=models.CASCADE, default=None) @receiver(post_save, sender=ExtractExcel) def my_save_handler(sender, **kwargs): instance = kwargs['instance'] if instance.id is None: id__max = ExtractExcel.objects.aggregate(models.Max('id'))['id__max'] if id__max is None: id__max = 0 instance.id = id__max + 1 df = pd.read_excel( rf'{instance.excel.path}') count_col = df.shape[0] df['extract_excel_id'] = [instance.id for i in range(count_col)] #above: to add a column named extract_excel_id to df for Foreign Key df.to_sql(ExcelDetail._meta.db_table, con=engine, index=true) when i save the Excel file to Excel model by admin, the error is shown that is like following error: (sqlite3.OperationalError) database is locked [SQL: INSERT INTO extract_excel_file_exceldetail (title, extract_excel_id) VALUES (?, ?)] [parameters: ((1, 9), ('title2', 9), (4, 9), ('title4', 9), ('w', 9), ('w', 9), ('amir', 9), (12, 9))] (Background on this error at: https://sqlalche.me/e/14/e3q8) it says 'database is locked' i think that a conflict is made up in database connection that is between django and engine above. what should i do? -
Django: How to save a OneToOneField
I have code that should assign a "bio" to each user. Until now, every time a user is created, a UserProfile is also created, where "Bio", "Birthday"... are in it. models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) phone_number = models.CharField(max_length=12, blank=True) birth_date = models.DateField(null=True, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() forms.py from django import forms from django.contrib.auth import get_user_model from .models import Profile non_allowed_usernames = ['abc'] User = get_user_model() class RegisterForm(forms.Form): username = forms.CharField() email = forms.EmailField() password1 = forms.CharField( label='Password', widget=forms.PasswordInput( attrs={ "class": "form-control", "id": "user-password" } ) ) password2 = forms.CharField( label='Confirm Password', widget=forms.PasswordInput( attrs={ "class": "form-control", "id": "user-confirm-password" } ) ) def clean_username(self): username = self.cleaned_data.get("username") qs = User.objects.filter(username__iexact=username) if username in non_allowed_usernames: raise forms.ValidationError( "This is an invalid username, please pick another.") if qs.exists(): raise forms.ValidationError( "This is an invalid username, please pick another.") return username def clean_email(self): email = self.cleaned_data.get("email") qs = User.objects.filter(email__iexact=email) if qs.exists(): raise forms.ValidationError("This email is already in use.") return email class LoginForm(forms.Form): username = forms.CharField(widget=forms.TextInput( attrs={ "class": "form-control" })) … -
Django server does not start, the site does not work when starting dockerfile
I'm training in the dockerfile assembly, I can't understand why it doesn't work. Python django project GitHub: [https://github.com/BrianRuizy/covid19-dashboard][1] At the moment I have such a dockerfile, who knows how to create docker files, help me figure it out and tell me what my mistake is. FROM python:3.8-slim RUN apt-get update && \ apt-get install -y --no-install-recommends build-essential ENV PYTHONUNBUFFERED=1 ADD requirements.txt / RUN pip install -r /requirements.txt EXPOSE 8000 CMD ["python", "manage.py", "runserver", "127.0.0.1:8000"] -
How to check if request user is in a models class
Lets say you have a class with name Car_club and in the class is members, which is a manytomany field to the User. Then you want to limit some part of the page for only members. class Car_club(models.Model): members = models.ManyToManyField(User, on_delete=CASCADE Lets say in the html there is parts where only the members of that class should see, how to manage that? -
How to exclude certain fields from a Model.save() in Django?
I tried solutions mentioned here but my model is inherited and it sometimes fails because when you set update_fields, it makes sure that something has updated. But that might not always be the case. Is there some other way where I can explicitly exclude certain fields from saving. Is there something available in the framework I can use. I would like to do something like if flag: super.save(exclude_fields=[field_1, field_2...]) else: super.save(*args, **kwargs) -
How to join two custom m2m tables - Django
I have the following: class Primera(models.Model): name = models.CharField(_("name"), max_length=50) def __str__(self) -> str: return self.name class PrimeraSegunda(models.Model): primera = models.ForeignKey(Primera, verbose_name=_("primera"), on_delete=models.CASCADE, related_name='primera_segunda_pri') segunda = models.ForeignKey('Segunda', verbose_name=_("segunda"), on_delete=models.CASCADE, related_name='primera_segunda_seg') amount = models.DecimalField(_("Amount"), max_digits=6, decimal_places=2, default=0) created_at = models.DateTimeField(_("Created at"), auto_now_add=True) class Segunda(models.Model): name = models.CharField(_("name"), max_length=50) primera = models.ManyToManyField(Primera, through=PrimeraSegunda, verbose_name=_("Clase Primera"), related_name='segundas') def __str__(self) -> str: return self.name class SegundaTercera(models.Model): segunda = models.ForeignKey(Segunda, verbose_name=_("segunda"), on_delete=models.CASCADE, related_name='segunda_tercera_seg') tercera = models.ForeignKey('Tercera', verbose_name=_("tercera"), on_delete=models.CASCADE, related_name='segunda_tercera_ter') amount = models.DecimalField(_("Amount"), max_digits=6, decimal_places=2, default=0) created_at = models.DateTimeField(_("Created at"), auto_now_add=True) class Tercera(models.Model): name = models.CharField(_("name"), max_length=50) segunda = models.ManyToManyField(Segunda, through=SegundaTercera, verbose_name=_("Clase Segunda"), related_name='terceras') def __str__(self) -> str: return self.name What I want to be able to do, is join both custom m2m tables to have access to their fields and also do calculations with the "amount" fields in both of the tables. Below you will find a sql statement equivalent: select st.* , ps.* from test_app_segundatercera as st join test_app_primerasegunda as ps on st.segunda_id = ps.segunda_id where st.tercera_id = 1 So far I have something like this: obj1 = PrimeraSegunda.objects.filter(segunda__segunda_tercera_seg__tercera=1).select_related() But I can't access the field in "SegundaTercera" pls help! -
On django framework, how can Put forms on footer
I am using django frame work for first time for a project. I have seperate header.html, footer.html and others page I want to put a newsletter subscription form in footer. Now how can I save the files on database. How can I call that particular form from every page.. I tried calling on footer.html, base.html and index.html everytime this doesn't works. Here's my model.py class NewsletterUser(models.Model): email = models.EmailField(max_length=254, null=False) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email And Views.py def subscription(request): if request.methods == "POST": email = request.POST['emailsubscription'] ins = NewsletterUser() ins.save() return render(request, 'footer.html') -
Django CORS from chrome extension
I'm deploying a Django app that will use help from a chrome extension to add some info to the app without the need to have it open on my browser, it worked ok when I made test on my computer but now I get the following django error: "Forbidden (Origin checking failed - chrome-extension://theIDfrommyextension does not match any trusted origins.): /smoke/add/" This is strange because I have the following CORS HEADERS configuration: CORS_ALLOW_ALL_ORIGINS = True CSRF_TRUSTED_ORIGINS = ['chrome-extension://*'] CORS_ALLOW_HEADERS = ( 'x-requested-with', 'content-type', 'accept', 'origin', 'authorization', 'x-csrftoken' ) I tought that with that configuration it should work because as far as I know I'm allowing CORS from all origins (I know that allow all CORS is insecure but is with test purposes) (I used django-cors-headers: https://pypi.org/project/django-cors-headers/): This is how I make fetch from my extension: function makeRequest(value) { // Send data to server url = 'https://my-test-app.herokuapp.com/smoke/add/'; let request = new Request(url, { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'text/plain', 'X-CSRFToken': value.csrftoken, }, body: JSON.stringify({ info: value, }), }); return request; } serverRequest = makeRequest(contactData); fetch(serverRequest) .then((response) => response.json()) .then((data) => { if (data.error !== undefined) { sendResponse({ error: 'Ocurrió un error' }); } else { // data['leadId'] = data.contact.lead; … -
Connect to Sybase database from Django
I tried to connect to Sybase database from Django using sqlanydjango, but I have stuck. One answer saying that sqlany-django is no longer maintained; it was last updated in May 2016. What is the other possibility to connect to Sybase database? -
how to conditional render html element in a Django template
I am using django server to send user email notifications, I came into a place where I need to say if this elemet doesn't exist add margin/space underneath the text <tr style="padding:0;margin:0;" height="30"> <td width="190" style="font-family:Roboto;color:#000000;font-weight:bold">Date</td> <td width="400" style="font-family:Roboto;color:#000000;">{{ processed_datetime|date:"d/m/Y H:i" }}</td> <!--I want to say here if there is no other party email add this element underneath --> {% if ! counterpart.email} <!--not sure about this line syntax --> <tr style="padding:0;margin:0;" height="20"> <td width="190" height="20" style="font-family:Roboto;color:#000000;font-size:24px;line-height:32px;"></td> </tr> -
How to add custom title to django form fields?
I wanna add my own title to django form fields like this image. My models.py file from django.db import models from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): ad_soyad = models.CharField(max_length=255, default="") tarih = models.CharField(max_length=255, default="") dogum_tarihi = models.CharField(max_length=255, default="") dogum_yeri = models.CharField(max_length=255, default="") medeni_hali = models.CharField(max_length=255, default="") birinci_evlilik = models.CharField(max_length=255, default="") ikinci_evlilik = models.CharField(max_length=255, default="") bosanma_tarihi = models.CharField(max_length=255, default="") ogrenim_durumu = models.CharField(max_length=255, default="") meslek = models.CharField(max_length=255, default="") kan_grubu = models.CharField(max_length=255, default="") boy = models.CharField(max_length=255, default="") kilo = models.CharField(max_length=255, default="") max_kilo = models.CharField(max_length=255, default="") max_kilo_tarih = models.CharField(max_length=255, default="") author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() def __str__(self): return self.title + '|' + str(self.author) def get_absolute_url(self): # return reverse('article-detail', args=(str(self.id))) bu kod olursa yazı ekledikten sonra o eklenen yazıya gidiyor return reverse('home') And my forms.py file from django import forms from .models import Post class PostForm(forms.ModelForm): class Meta: model = Post fields = 'all' #field = ('title', 'author') yapılabilir widgets = { 'title': forms.TextInput(attrs={'class': 'form-control'}), 'author': forms.Select(attrs={'class': 'form-control'}), 'body': forms.Textarea(attrs={'class': 'form-control'}), 'ad_soyad': forms.TextInput(attrs={'class': 'form-control'}), 'tarih': forms.TextInput(attrs={'class': 'form-control'}), 'dogum_tarihi': forms.TextInput(attrs={'class': 'form-control'}), 'dogum_yeri': forms.TextInput(attrs={'class': 'form-control'}), 'medeni_hali': forms.TextInput(attrs={'class': 'form-control'}), 'birinci_evlilik': forms.TextInput(attrs={'class': 'form-control'}), 'ikinci_evlilik': forms.TextInput(attrs={'class': 'form-control'}), 'bosanma_tarihi': forms.TextInput(attrs={'class': 'form-control'}), 'ogrenim_durumu': forms.TextInput(attrs={'class': 'form-control'}), 'meslek': forms.TextInput(attrs={'class': 'form-control'}), 'kan_grubu': forms.TextInput(attrs={'class': 'form-control'}), 'boy': forms.TextInput(attrs={'class': 'form-control'}), 'kilo': forms.TextInput(attrs={'class': … -
Django rest framwork - how to prevent 1062, "Duplicate entry"
at my Django application (DRF only), I'm trying to create a new object where one of the fields is setup like this: resource_name = models.CharField(verbose_name="Resource Name", blank=False, null=False, max_length=50, unique=True) If I now try to create an Object with the same resource_name twice, I'm always running into the following exception: django.db.utils.IntegrityError: (1062, "Duplicate entry 'test_ressource123' for key 'resource_name'") Is there any good solution that I can apply to all kinds of these situations? Would be awesome to simply make the API response that the object already exists, kinda strange that this is not already a built-in of DRF. Can I maybe overwrite the def create function call of the serializer ? Any good advice welcome. -
Reverse for 'location-posts' for django
I'm trying to list all the posts on the same page that are shared in the same location. (when i create a post so if the location is "manhattan" when I click on the location of a post in the main page it will show me all the posts that have been shared in the same location by all users. I've watched some tutorials and I managed to list specific user's posts in the same page (nothing to do with location just by username) and I thought it would be fairly similar but didnt work. i guess theres something wrong with the way i use urls.py or the def so it gives me Reverse for 'location-posts' with arguments '('',)' not found. 1 pattern(s) tried: ['post/(?P<loc>[^/]+)$'] error so these are the related parts of my code: views.py class LocationPostListView(ListView): model = Post template_name = 'blog/location_posts.html' context_object_name = 'posts' paginate_by = 199 def get_queryset(self): user = get_object_or_404(User, loc = self.kwargs.get('loc')) return Post.objects.filter(location = user).order_by('-date_posted') urls.py from .views import PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView, UserPostListView, LocationPostListView . . . path('post/<str:loc>', LocationPostListView.as_view(), name="location-posts"), location_posts.html <a class="mr-2" href="{% url 'location-posts' post.location.loc %}">{{ post.location }}</a> also: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = … -
How to select a group when registering a new user in Django
So whenever I create a new user I would like to select a group (executive or employee). What is the right way to do this? *The groups are already made in the Django Admin environment.