Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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)) -
How to pre-fill a field in a ModelForm with the field's default value and not include it in the form itself
I have a Post model which has a field called author, I was able to set the current user as it's default, But when I'm trying to not include it in the form related to it, It fails and gives me different errors. Here's the code: models.py: def get_file_path(instance, filename): file_extension = filename.split('.')[-1] return f'user_{instance.author}/{instance.pub_date.strftime("%Y/%B/%a-%M")}/logo.{file_extension}' class Post(models.Model): title = models.CharField(max_length=75) body = models.TextField() logo = models.ImageField(upload_to=get_file_path, blank=True) author = models.ForeignKey(User, default=get_user_model(), on_delete=models.CASCADE) pub_date = models.DateTimeField(default=datetime.now()) forms.py: class PostForm(forms.ModelForm): class Meta: model = Post fields = ('title', 'body', 'author', 'logo') widgets = { 'title': forms.TextInput(attrs={'class': 'form-control bg-dark border border-secondary text-light'}), 'body': forms.Textarea(attrs={'class': 'form-control bg-dark border border-secondary text-light'}), 'author': forms.Select(attrs={'class': 'form-control bg-dark border border-secondary text-light'}), 'logo': forms.ClearableFileInput(attrs={'class': 'form-control bg-dark border border-secondary text-light'}), } views.py: class PostCreateView(LoginRequiredMixin, CreateView): login_url = 'login' model = Post form_class = PostForm template_name = "posts/new_post.html" How can I not include the field in the form and the page, But have it use it's own default value? NOTE that I don't want to create a field and make it hidden! -
Use pikepdf on django document object
I have a django project where the user uploads a pdf bank statement after which I want to parse it using pikepdf. Problem: The standard use case with pikepdf is to do pikepdf.open(_path_) to open a file at some location but in my case the file is being uploaded by a client and hence it is returned in the request.POST as a file object django.core.files.uploadedfile.InMemoryUploadedFile. Since it is not stored at some path I obviously can't invoke pikepdf.open(_path_), which is a problem because my file is seen as a django.core.files.uploadedfile.InMemoryUploadedFile and not a pikepdf._qpdf.Pdf Question: How can I "convert the django.core.files.uploadedfile.InMemoryUploadedFile to a pikepdf._qpdf.Pdf during runtime so that I can use other pikepdf methods? My code: here is my django code in case it helps: models.py from django.db import models # Create your models here. class Document(models.Model): docfile = models.FileField(upload_to='documents/%Y/%m/%d') forms.py from django import forms class DocumentForm(forms.Form): docfile = forms.FileField( label='Select a file', help_text='max. 42 megabytes' ) views.py def uploadbs(request): if request.method == 'POST': form = forms.DocumentForm(request.POST, request.FILES) newdoc = Document(docfile = request.FILES['docfile']) <<< convert newdoc to pikepdf object >>> -
How to import a Postgres database into a docker container?
I'm trying to import PostgreSql dump to docker container, but it doesn't work Dockerfile: FROM postgres COPY postgres.sql /docker-entrypoint-initdb.d/ version: "3.9" docker-compose.yml services: db: build: ./DB volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=gamenews - POSTGRES_USER=postgres - POSTGRES_PASSWORD=321678 web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" environment: - POSTGRES_NAME=gamenews - POSTGRES_USER=postgres - POSTGRES_PASSWORD=321678 depends_on: - db structure: -
Django + DRF + Celery: execute celery_task.delay() only after database transaction completed (model.save() reached the database)
I tried to use the on_commit method as they tell us in the docs, but I still get ModelDoesNotExistError inside the task launched via delay(). views.py: class SomeViewset(viewsets.ModelViewset): ... @action(detail=True, methods=['post']) def some_action(self, request, *args, **kwargs): m = MyModel() with transaction.atomic(): m.save() transaction.on_commit(lambda: my_fav_task.delay(m.id, param2, param3)) return Response({"success": True, "operation_id": m.id}, status=status.HTTP_200_OK) tasks.py: @shared_task def my_fav_task(operation_id, **params): print(operation_id) # We get new id print(MyModel.objects.all()) # No newly created object here operation = MyModel.objects.get(id=operation_id) # Error here -
Does the Django REST Framework have something like a UML Component Diagram?
I have an idea of how I can use DRF to enhance an existing Django application. I see in the documentation how the DRF can interact with Djanco routers and even create a custom router. In most MVC Frameworks the router can route requests from the controller to Model services or to View services. But in Django I read that there really isn't a "controller" per se and the Views ride on the Django infrastructure to connect to the models. If I wanted to follow a Microservices architecture the the DRF to change the orchestration of dataflow between the views and the models it would seem logical that I would modify the router(s) as the DRF documentation hints at. A UML Component Diagram or Data Flow Diagram or Sequence Diagram would help a lot. Thanks. -
want to convert my sql query into django orm query
This is my query SELECT form_fields.label_name, entry_details.value, entry_details.entry_id FROM form_fields join entry_details on entry_details.field_id = form_fields.id WHERE form_fields.id in (21401, 21402) and entry_details.entry_id = 79; I am a entry level developer having problem to convert this qery into djago query.....please help me -
Django - count number of inline elements in class based view
I have 2 models: Product and ProductComponent. How can I count the number of components in each product so when I want to loop products in the template it will give me the title and the number of components per product? class ProductComponent(models.Model): name = models.CharField(max_length=255) related_product = models.ForeignKey(Product, on_delete=models.CASCADE') @property def count_components(self): return self.component_name.count() class Product(models.Model): title = models.CharField(max_length=400) views.py class TestView(ListView): template_name = "test.html" model = Product def get_context_data(self, **kwargs): context = super(TestView, self).get_context_data(**kwargs) context['product_list'] = Product.objects.filter(?) return context I managed to do something like this in admin but only in the ProductComponent admin page but not in the Product admin page. admin.py class TestViewAdmin(ImportExportModelAdmin): resource_class = TestViewAdminResource list_display = ('get_component_count',) def get_component_count(self, obj): return obj.related_product.related_product.count() What I want to do is to create a loop of products with a number of components that are related to this product. {% for product in product_list %} {{product.title}} - {{product.count_components}} {% endfor %} I'd appreciate any advice on how to achieve something like that. -
using Azure Application Insights in a dockerized Django
i'm trying to embed Azure’s Application Insights in a dockerized Django/AngularJS environment to cover the data flow from end to end. In order to do so, I Added opencensus corresponding libraries to my requirements.txt file: opencensus-ext-azure opencensus-ext-django opencensus-ext-requests opencensus-ext-logging opencensus-ext-postgresql Edit the logging section in my settings.py: LOGGING = { 'disable_existing_loggers': False, 'formatters': { 'default': { 'format': '%(asctime)s - %(levelname)s - %(processName)s - %(name)s\n%(message)s', }, }, "handlers": { "azure": { "level": "DEBUG", "class": "opencensus.ext.azure.log_exporter.AzureLogHandler", 'connection_string': os.getenv('CONNECTION_STRING'), }, "console": { "level": "DEBUG", "class": "logging.StreamHandler", "stream": sys.stdout, }, }, "loggers": { 'my-app’s-name’: { "handlers": ["azure", "console"] }, }, 'version': 1 } And initialized a Tracer instance to my views.py: from opencensus.ext.azure.trace_exporter import AzureExporter from opencensus.trace import config_integration from opencensus.trace.samplers import AlwaysOnSampler from opencensus.trace.tracer import Tracer import logging logger = logging.getLogger("my-app-name") logger.setLevel(logging.DEBUG) tracer = Tracer( exporter=AzureExporter( connection_string = os.getenv('CONNECTION_STRING') ), sampler=AlwaysOnSampler()) Now I have several questions Where and how should I create a span? Can I implement it before a function returns its result? I.e. @login_required(login_url='login') def query_xyz(request): if request.method == 'GET': work_date_str = request.GET.get('workDate') work_date = parser.parse(work_date_str).date() if work_date_str is not None else datetime.now().date() column = [i.replace(' ', '_') for i in request.GET.getlist('column')] filters = json.loads(request.GET.get('filters')) if request.GET.get('filters') else None limit = … -
How to select another array of data by subscript in a django for loop
I have a problem when transfering two list to a html in django. I hope that it will be a:1b:2Each of two data is paired. But it does not work. There have some demo codes, showing the same error. Absolutly,it has no error log,because the {{l2s.order}} is null,and the system does not throw error.Maybe my poor English makes it confusing,If there are any where no description clearly, please point out, I'll add the appropriate information。 Thanks for your help. # fake view def test(request): l1s = ["a","b","c","d","e","f"] l2s = ["1","2","3","4","5","6"] return render(request,'fake.html',locals()) # fake html {% for l1 in l1s% } {% with order=forloop.counter0 %} {{l1}}-{{l2s.order}} {% endfor %} -
It is not possible to migrate a new user element to the django table
I am faced with the problem that it is not possible to migrate the new user value to the database table. At first there were errors on related_name, but I fixed it, and now that this value cannot be zero, at the same time, if I write that null=True, then the user cannot be displayed in the records in the future. class Writehelp(models.Model): users = models.ForeignKey(User,on_delete = models.CASCADE,related_name='helpedman',null=False,verbose_name='Автор') titles = models.CharField(max_length=200, verbose_name='Заголовок', blank=True) descriptions = models.TextField(blank=True, verbose_name='Описание') createdtimes = models.DateField(auto_now_add=True, db_index=True, verbose_name='Дата создания') prices = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name='Цена') course = models.IntegerField(null=True, blank=True, verbose_name='Курс') semestr = models.IntegerField(null=True, blank=True, verbose_name='Семестр') subjects = models.CharField(max_length=200, null=True, blank=True, verbose_name='Предмет') institutes = models.CharField(max_length=200, null=True, blank=True, verbose_name='Институт') However, when I migrated this model, there were no problems: class UploadFile(models.Model): user = models.ForeignKey(User,on_delete = models.CASCADE,related_name='file_created' ,verbose_name='Автор') title = models.CharField(max_length=200, verbose_name='Заголовок',blank=True) # uploadedfile = models.FileField(upload_to='files/',null=True, verbose_name='Файл') description = models.TextField(blank=True, verbose_name='Описание') createdtime = models.DateField(auto_now_add=True, db_index=True, verbose_name='Дата создания') price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name='Цена') number_course = models.IntegerField(null=True, blank=True, verbose_name='Курс') number_semestr = models.IntegerField(null=True, blank=True, verbose_name='Семестр') subjectt = models.CharField(max_length=200, null=True,blank=True,verbose_name='Предмет') type_materials = models.CharField(max_length=200,null=True,blank=True, verbose_name='Тип работы') institute = models.CharField(max_length=200, null=True,blank=True, verbose_name='Институт') -
Can someone please explain this django code to me?
I don't understand order_qs[0] and the order.items.filter. I mean items is not a class manager, so I don't understand how it is able to work. Then, I thought only list can be accessed by index with [0], and besides that should only return one item. It seems order_qs[0] contains more than one item def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) order_item = OrderItem.objects.get_or_create( item=item, user = request.user, ordered = False ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] #check if the order item is in the order if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() else: order.items.add(order_item) The models: class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.item.title}" class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add= True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) def __str__(self): return self.user.username -
'SearchUsers' object has no attribute 'count'
I have problem with this it keeps saying: 'SearchUsers' object has no attribute 'count' class PaginatedElasticSearchAPIView(APIView, LimitOffsetPagination): serializer_class = None document_class = None @abc.abstractmethod def generate_q_expression(self, query): """This method should be overridden and return a Q() expression.""" def get(self, request, query): try: q = self.generate_q_expression(query) search = self.document_class.search().query(q) response = search.execute() print(f'Found {response.hits.total.value} hit(s) for query: "{query}"') results = self.paginate_queryset(response, request, view=self) serializer = self.serializer_class(results, many=True) return self.get_paginated_response(serializer.data) except Exception as e: return HttpResponse(e, status=500) from django_elasticsearch_dsl import Document, fields from django_elasticsearch_dsl.registries import registry @registry.register_document class UserDocument(Document): class Index: name = 'users' settings = { 'number_of_shards': 1, 'number_of_replicas': 0, } id = fields.IntegerField() class Django: model = User fields = [ 'first_name', 'last_name', 'username', ] #views from elasticsearch_dsl import Q class SearchUsers(PaginatedElasticSearchAPIView): serializer_class = UserSerializer document_class = UserDocument def generate_q_expression(self, query): return Q('bool', should=[ Q('match', username=query), Q('match', first_name=query), Q('match', last_name=query), ], minimum_should_match=1) #urls from django.urls import path from search.views import SearchUsers urlpatterns = [ path('user/<str:query>/', SearchUsers.as_view()), ] I'm facing this issue for the last 3 days. Searched for the similar question on StackOverflow but nothing helped me. Any Help, Would be appreciated. Thanks in Advance :) -
How to implement an Unsubscribe Newsletter button using Django
I have implemented a Subscribe to newsletter feature in my project and its working completely fine. I wanted to implement Unsubscribe the newsletter button beside it. I'm not able to figure it out on how to do it? Could someone help me out with this! Thanks in advance!! Here is my code: views.py def subscribe(request): if request.method=='POST': form=SubscribersForm(request.POST) if form.is_valid(): form.save() messages.success(request,'Subscription Successful') return redirect('/subscribe') else: form=SubscribersForm() context={ 'form':form } return render(request,'base/subscribe.html',context) urls.py path('subscribe/',views.subscribe,name='subscribe') subscribe.html {% load crispy_forms_tags %} {% block content %} <!-- Add code from body here --> <div class="container"> <div class="row mt-5 pt-5"> <div class="col-md-4 offset-md-4"> {% for message in messages %} <div class="alert alert-success"> {{ message }} </div> {% endfor %} <div class="card" style="width:150%; justify-content:center; align-items:center;"> <div class="card-body"> <h3 class="sub-text">Subscribe to Newsletter</h3> <hr> <form method="POST"> {% csrf_token %} {{form|crispy }} <input class="btn btn-success btn-block mt-5" type="submit" value="Subscribe"> <input class="btn btn-danger btn-block mt-5" type="submit" value="Unsubscribe"> </form> </div> </div> </div> </div> </div> {% endblock %} models.py class Subscribers(models.Model): email=models.EmailField(null=True) date=models.DateTimeField(auto_now_add=True) def __str__(self): return self.email forms.py class SubscribersForm(forms.ModelForm): email = forms.EmailField(label='Email', widget=forms.EmailInput(attrs={'class': 'form-control my-2','placeholder': 'Enter your Email','type': 'email','name': 'email'})) class Meta: model=Subscribers fields=['email',] -
Can we edit right side actions bar in Django admin
I am currently working on a Django Application. I have used Django Jazzmin (a drop-in theme for django admin). I have customised Django admin upto a certain extent according to my needs. However, I want to edit the available actions when Admin navigates to the user model. As you can see in the screenshot below there are only four options available which are 'Save', 'Delete', 'Save and add another' and 'Continue editing'. However, I want to create one more action Fetch Data that makes an API call with current user's id as parameter and fetch the related data of the user to update existing database. Can we do this by changing admin actions? Or there is a better alternative or approach to achieve this solution?