Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python: create a decorator that combines several others [duplicate]
Imagine we write in Django: @decorator1(p1, p11) @decorator2(p2, p22) @decorator3(p3, p33) def view(request): pass What should be written so I could use: @combined_decorator def view(request): pass And the effect would be the same? I tried: @decorator1(p1, p11) @decorator2(p2, p22) @decorator3(p3, p33) def combined_decorator(view): return view But it didn't work -
Please see the terminal and how to resolve it
Error _ Django I am not able to figure out the error. -
django.db.utils.OperationalError: (1050, "Table ' ' already exists")
I am trying to setup a new project. It has migrations already. I created a new mysql database but while doing migrate I get error like django.db.utils.OperationalError: (1050, "Table ' ' already exists"). Why is that error occurred inside a completely new database ? But the default django app like admin, auth etc. migrated without an issue. DATABASES = { "default": { "ENGINE": "django.db.backends.mysql" "NAME":"mydb", "USER": "myuser", "PASSWORD": "my pwd", "HOST": "localhost", "PORT":3306, "OPTIONS": {"init_command": "SET sql_mode='STRICT_TRANS_TABLES'"}, } } -
Django Heroku Deployment Process
i'am deploying a website built with Django Framework into Heroku and when i try to push my code into the remote after ihad created a Heroku remote with the fallowing command "heroku git:remote -a app-name", after i use "git push heroku master" it return to me this error : === Fetching app code =!= Build failed due to an error: =!= validate step: error converting YAML to JSON: yaml: line 12: could not find expected ':' If this persists, please contact us at https://help.heroku.com/. someone can help me? Thank you! -
Django disable csrf for admin
I need to disable csrf for all admin paths. If I try to import in urls.py from django.views.decorators.csrf import csrf_exempt and then urlpatterns += [path(admin_url, admin.site.urls)] then when I go to admin I get an error TypeError at /core/admin/ 'tuple' object is not callable how to fix it? -
Is there a way to update top level relationship in Django form?
I have below models and form. Brand > Section > Category > Article. I can pull the existing data out of the database however I have hit a wall. I am trying to create a new article or update an existing article but I'm not sure how I can update the brand, then the Section. The Category I can update and it is connected directly to the Article model. I have been thinking about this for a few days now and tried different models but ultimately i can't think of the best way to connect the models and have them update in the model. class Brand(models.Model): def brand_image(instance, filename): return 'uploads/brand/{0}/{1}'.format(instance.title, filename) title = models.CharField(max_length=50, unique=True, blank=True, null=True) image = models.ImageField(upload_to=brand_image, null=True, blank=True) slug = AutoSlugField(populate_from='title', unique_with='title', blank=True, null=True) my_order = models.PositiveIntegerField(default=0, blank=False, null=False) class Meta: ordering = ['my_order'] def __str__(self): return self.title or '' def get_absolute_url(self): return reverse('brand-list', kwargs={'brand_slug': self.slug}) class Section(models.Model): title = models.CharField(max_length=50,unique=True, blank=True,null=True) slug = AutoSlugField(populate_from='title', unique_with='title',blank=True,null=True) brand = models.ForeignKey(Brand, on_delete=models.CASCADE, related_name='section', blank=False, null=False) my_order = models.PositiveIntegerField(default=0, blank=False, null=False) class Meta: ordering = ['my_order'] def __str__(self): return self.title or '' def get_absolute_url(self): return reverse('section-list', kwargs={'section_slug': self.slug}) class Category(models.Model): title = models.CharField(max_length=50, blank=True,null=True) slug = AutoSlugField(populate_from='title', unique_with='title',blank=True,null=True) … -
Authentication credentials were not provided - Django REST
I am making IOS app with Django backend, it was working well, but now im getting error {"detail":"Authentication credentials were not provided."} Django Backend settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated' ), } views.py class ColorTagViewSet(viewsets.ModelViewSet): queryset = ColorTag.objects.all() serializer_class = ColorTagSerializer permission_classes = (IsAuthenticated,) authentication_classes = (TokenAuthentication,) urls.py (in my app) router = routers.DefaultRouter() router.register(r'colortag', views.ColorTagViewSet) urlpatterns = [ path('', include(router.urls)), path('auth/get-token', rest_views.obtain_auth_token), ] Test IOS App ViewController.swift class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() print("requesting") guard let url = URL(string: "http://192.168.0.171:8000/api/v1/colortag") else { print("URL Error") return } let token = "6a02d8d41a8cf143522a587bcee4be2c8b7d75e5" var request = URLRequest(url: url) request.httpMethod = "GET" request.addValue("application/json", forHTTPHeaderField: "Accept") request.addValue("Token \(token)", forHTTPHeaderField: "Authorization") URLSession.shared.dataTask(with: request) { data, response, error in print(String(data: data!, encoding: .utf8)) }.resume() } } I also tried using basic auth, that also didnt work usually i dont ask people on Stackoverflow(or any other forums, google is enough), but i have no idea what to do. Can anyone tell me what is the possible reason of facing this error? -
How to use compiled webpack files on local server
I use python manage.py runserver for django and webpack-dev-server --mode=development for template on local development. Now I was ready for deployment on server, so I did webpack --mode=production, It created the dist directory.... then,,,How can I use this ? Just accessing localhost (manage.py runserver) but no templates appears. -
Django annotation does not group output as intended
The following is my model: class Project(models.Model): name = models.CharField(max_length=1000, null=True, blank=True) date_created = models.DateTimeField(auto_now=True) status = models.CharField(max_length=1000, null=True, blank=True) The status field has about 5 different options (Won, Lost, Open, Pending, Cancelled). I need to know how to get the number of projects with x status in each month in a given time range query. I was able to get the correct data shape using the following annotation- but for some reason, the output given delivers an object for every found status within a month. For instance, if there is at least 1 "Won" and 1 "Open" project found in the same month, two separate objects will return for the same month. Additionally, the status options here are hard-coded and would need to be modified if a new status was added. queryset = list(opps.annotate( month=TruncMonth('date_created'), ).values('month').annotate( total=Count('id'), Win=Count('id', filter=Q(status='Win')), Loss=Count('id', filter=Q(status='Loss')), Open=Count('id', filter=Q(status='Open')), Dormant=Count('id', filter=Q(status='Dormant')), Pending=Count('id', filter=Q(status='Pending')), Cancelled=Count('id', filter=Q(status='Cancelled')), )) Here's a sample of my current output. [{'month': datetime.datetime(2022, 5, 1, 0, 0, tzinfo=zoneinfo.ZoneInfo(key='UTC')), 'total': 1, 'Win': 0, 'Loss': 1, 'Open': 0, 'Dormant': 0, 'Pending': 0, 'Cancelled': 0} {'month': datetime.datetime(2022, 5, 1, 0, 0, tzinfo=zoneinfo.ZoneInfo(key='UTC')), 'total': 1, 'Win': 0, 'Loss': 1, 'Open': 0, 'Dormant': 0, 'Pending': 0, 'Cancelled': 0} … -
Why is my for loop not working in django?
I'm new to Django and I tried to load data into my template using for loop ended up getting the for loop tags written on my template. Views.py from django.shortcuts import render from django.http import HttpResponse from projet.models import Employe # Create your views here. def page(request) : employe = Employe.objects.all() return render(request,'hello.html',{'employe':employe}) Html table template <table class="table"> <tr class="tr"> <th>ID</th> <th>Nom et Prenom</th> <th>Lundi</th> <th>Mardi</th> <th>Mercredi</th> <th>Jeudi</th> <th>Vendredi</th> <th>Samedi</th> <th>Dimanche</th> </tr> { % for i in employe % } <tr> <td>{{ forloop.counter }}</td> <td>{{ i.name }}</td> <td>{{ i.monday }}</td> <td>{{ i.tuesday }}</td> <td>{{ i.wednesday }}</td> <td>{{ i.thursday }}</td> <td>{{ i.friday }}</td> <td>{{ i.saturday }}</td> <td>{{ i.sunday }}</td> </tr> { % endfor % } </table> -
How to find any Django classes' import path
I feel really dumb having to ask this question, but I often find a class I want to use in Django and have a tough time figuring out what its import path is. I end up clicking google result after google result until someone happens to include its path in a question, answer, or comment. Sometimes it's easy and other times it's tough. For example, I was investigating an exception I was seeing about atomic transactions in my unit tests and I learned about a class I wanted to try called TransactionTestCase. My first stop was the Django documentation on the class. You would think that the first thing in the documentation on that class would be where it lives and how to import it, but it's not in the documentation on that page about that class. What does everyone else do? Does there exist a 1-step reliable means of looking up any class's import path? Or does everyone just know it by inference or from reading the paragraphs of documentation and meandering through links in the documentation or use a heuristic by chopping up and searching on components of the camelcase name? What am I missing here? I'm sure … -
Django MultipleChoiceField
I have problem with dynamically executing code for django model with python function exec. My method: def _manage_record(self, record=None, order=None): """Dynamically exec allowed operations to many to many relationship.""" allowed = ("add", "remove") if order is None: raise ValueError("Order for _manage_record can't be None value.") if record is None: raise ValueError("Record to manage can't be None value") if record.__class__ is not self.model: raise ValueError("Record have to be " + str(self.model) + " instance.") if order in allowed: string = "self.partner." + self.relation_name + "." + order + "(record)" exec(string) else: raise Exception("Order " + order + " not allowed.") if i print that string and directly copy it and pass to exec function it will execute properly, but with that string created dynamically nothing happen. Any help? -
filtering objects based on boolean field state
I'm working on a project where a form is filled out. And in that form you have the is_active fields. If the user selects True, it means the account is active and if it is False, it means it is no longer active, and the user can no longer see it. Through the filters I'm trying to present only the forms with the is_active True, but I'm not able to. Follow one of my attempts in my views: class BookingViewSet(viewsets.ModelViewSet): serializer_class = BookingSerializer #queryset = Booking.objects.all() #queryset = Booking.objects.filter(is_active="True") #filter_backends = (filters.DjangoFilterBackend,) #filterset_class = BookingFilter #filterset_fields = ['is_active'] def get_queryset(self): queryset = Booking.objects.all() username = self.request.query_params.get('bookings') if username is not None: queryset = queryset.filter(is_active__username=username) return queryset -
MailInaBox config issue (from expiringdict import ExpiringDict)
So i recently upgraded my mailinabox installation and after that when I try to start the mailinabox service I get this error on the console File "/root/mailinabox/management/auth.py", from expiringdict import ExpiringDict ModuleNotFoundError: No module named 'expiringdict' I have tried and installed the modules manually using pip but it just doesn't work -
to check user password is correct in django rest framework
I'm writing a custom login functionality in the Django rest framework. But I can't check if the password is correct or not. class LoginView(APIView): def post(self, request): username=request.data["username"] password=request.data["password"] user=User.objects.filter(username=username) if user is None: return Response({"response":"No User exist"}) if user.check_password(password): return Response({"response":"correct Password"}) return Response({"data":"done"}) the problem is check_password function is not working.Is there any right way to do that or do I miss something in between? -
how to add form field or model field which support all types characters?
forms.py class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = ('username', 'email', 'password') I want to username support all types character including Bangla. But i get this error -
How to save a model instance asynchronously Django (using the 4.1 Django ORM asynchronous interface)
Recently Django 4.1 has been released with a new asynchronous ORM interface. It's really cool. But I've been using it for a couple of weeks now and I found a usecase that made me stuck. Im trying to replicate this behaviour in an asynchronous context: class Foo(m.Model): """ Stores information about a Foo """ name: Union[m.CharField, str] = m.CharField(max_length=49) foo: Foo = Foo(name='bar') foo.save() First of all, the acreate() method does not solve my issue. I need to first create the model instance and then save it. My guess approach -being consistent with the ORM interface- was to use foo.asave() but the method does not exists. I'm trying to find a cleaner way to approach this rather than the sync_to_async method. Thanks a lot for the help! ❤️ -
get_absolute_url very busy database
When I load a product page, I want other products to be offered on that page. But when generating an absolute url for each product, the database is accessed. Accordingly, if there are 10 products on the page, then there will be + 10 calls to the database How can i reduce the number of queries in the db? It`s my code: models.py class Goods(models.Model): category = models.ForeignKey(Category, related_name='goods', on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=150, db_index=True, verbose_name='название') slug = models.CharField(max_length=150, db_index=True, unique=True, verbose_name='Слаг') def get_absolute_url(self): return reverse('goods_detail', kwargs={"category_slug[enter image description here][1]": self.category.slug, "goods_slug": self.slug}) urls.py path('<slug:category_slug>/<slug:goods_slug>', views.GoodsDetailView.as_view(), name='goods_detail'), views.py class GoodsDetailView(DetailView): model = Goods context_object_name = 'goods' slug_url_kwarg = 'goods_slug' goods_detail.html {% for i in goods.ingredients.all%}<br> <a href="{{ i.get_absolute_url }}"> {{ i }}</a> {% endfor %} *The photo shows an example if I display 4 objects on a page -
dynamic filter with django + ajax + display in templates
I am new to django and js, please, i need help. So, i want to filter model objects without page reload. I form the filter conditions and send to the server via ajax something like this: (Please do not scold for the code, I'm just trying to understand the essence...) bla bla bla : $ajax data: bla method: bla success : (from the server I receive data in json format) document.getElementById(#bla).innerhtml = `....` so here is my question: if i use in innerhtml something like this ${ smth.smth1} - it's not a problem, but if i want to use 'for loop' over related objects : {% for el in smth.smth2.all %} and then use el.smth, JS don't understand me... So how i can loop through the elements from the received data in innerhtml. I will be glad for any hint and help. -
How can I get a parameter of an url with django-rest-framework
I am building a map with different station location. The stations belong to different fields. I have to show all station and, I have all station of a field. At some point my api is called """Markers API URL Configuration.""" # Maps with Django (2) # https://www.paulox.net/2021/07/19/maps-with-django-part-2-geodjango-postgis-and-leaflet/ from rest_framework import routers from map.viewsets import MarkerViewSet router = routers.DefaultRouter() router.register(r"map", MarkerViewSet) urlpatterns = router.urls then the MarkerViewSet is called (viewsets.py) class MarkerViewSet(viewsets.ReadOnlyModelViewSet): """Marker view set.""" #print(self.kwargs.get('idfield')) bbox_filter_field = "location" filter_backends = (filters.InBBoxFilter,) queryset = Stations.objects.filter(station_active=1, map=1) serializer_class = StationsSerializer def get_queryset(self, **kwargs): #field_id = self.kwargs['idfield'] #print("pp:", self.kwargs) return Stations.objects.filter(fields_id_field=1) The code above works, but it only show the markers of the field 1 If I change this to 2 return Stations.objects.filter(fields_id_field=2) It show all station of the field with the id 2 My url is as the follwoing http://127.0.0.1:8080/map/ to print all stations of all fields. If I want to have the stations of the field 1, my url will be http://127.0.0.1:8080/map/1/field and for the field 2 and 4 http://127.0.0.1:8080/map/2/field http://127.0.0.1:8080/map/4/field My problem, I can not not and I do not know of to get the id 1,2,4 or another form my url this does not work #field_id = self.kwargs['idfield'] #print("pp:", … -
Pass different choices in django form select field based on user language preference
I have a django ModelForm which has select field in it and contains dropdown list, which is represented as two separate FIELD_CHOICE pairs. The reason for it is that I want to pass different FIELD_CHOICE pairs on language select. I am using django internationalization and have two LANGUAGE_CODE which I want to use to differentiate and pass respective CHOICE pairs in the select field. Is there any way to do it within the forms.py? -
Using {{}} inside {% if %} in jinja
{% for category in categories %} {% if request.get_full_path == '/?category={{category.0}}' %} {{ category.0 }} <li class="nav-item active"> <span class="sr-only">(current)</span> <a class="nav-link" href="/?category={{ category.0 }}">{{ category.1 }}</a> </li> {% else %} {{request.get_full_path}} /?category={{category.0}} <li class="nav-item"> <span class="sr-only">(current)</span> <a class="nav-link" href="/?category={{ category.0 }}">{{ category.1 }}</a> </li> {% endif %} {% endfor %} I want to highlight navigation buttons, but {% if %} statement cant see {{category.0}} expression inside. Can I use {{}} inside {% if %} statement in jinja? -
Silence a specific Warning in Django / Django Rest Framework
I want to silence a single warning in Django, when using Django Rest Framework with a default PAGE_SIZE setting, but no DEFAULT_PAGINATION_CLASS setting. I am in the exact situation presented by the error message as a case in which I can silence it: I want a PAGE_SIZE setting globally whilst defining pagination_class on a per-view basis, case in which the warning says "you may silence this check." But I haven't figured out how to silence only this warning without silencing other warnings (that'd be done via this method). The warning itself is here in the DRF source code. Any help would be appreciated! -
Django template user in queryset condition
I have the following Post and Follow models: class Post(models.Model): content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) date_modified = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE) @property def followers(self): return self.follow_set.filter(post=self).values_list('user', flat=True) class Follow(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) I tried the following code in shell to check for data in .followers property: >>> from posts.models import Post >>> x= Post.objects.get(id=22) >>> x.followers <QuerySet [1]> What I ultimately want is to check if the authenticated user is among the followers. I have the following template code: {% if user in object.followers %} <a href="#">Unfollow</a> {% else %} <a href="#">Follow</a> {% endif %} The problem I have is that {% if user in object.followers %} always evaluates to False. P.S.: I always log-in the user id=1 (same as the queryset result from above). -
suds.TypeNotFound: Type not found: > '(datetime, http://www.w3.org/2001/XMLSchema, )
When I want to create a simple client with suds, I get an error raise TypeNotFound(query.ref) suds.TypeNotFound: Type not found: '(datetime, http://www.w3.org/2001/XMLSchema, )' I checked the answers that were already in Stack Over Flow and made some changes, but it didn't help Here is my code imp=Import('http://www.w3.org/2001/XMLSchema',location='http://www.w3.org/2001/XMLSchema.xsd') imp.filter.add('http://tempuri.org/') cli = Client(wsdlUrl,doctor=ImportDoctor(imp))