Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to return 404 status code with react and django-rest-framework
I'm using react as frontend with a Django rest framework as server side to provide api to the frontend. To handle the routing of the urls, react-router is used. To handle a urls not matching any paths in the react-router, I'm using the following code: <Route component={my404component} /> This does work but it returns status code 200, how can I return 404 instead for SEO purposes? I've heard some responses that I have to use a server, but how do I do this with a django-rest-framework? Or is this related to my nginx? -
How can increment only last digits of string and save in modelsin django
I want my own serial no. Which is like this BILLNO20212201 where last two digits get increment automatically if fist serial no was BILLNO20212201 then second willbe BILLNO20212202 wise versa And this want to be save in database I generate code Bill_str = "BILLNO" today_date = str(today.day) today_year = str(today.year) Bill_no = Bill_str+today_date+today_year Print(Bill_no) How can i increment no in it and create and save bill no in database? -
Django move variable in template for <img src="">
I have a variable contain url my file image m='media/abc2021x07x13/ch00002_01000000025099767142400187070_29H75756.jpg' return render(request, 'new_template/view_image.html',{'form1': m}) and move to template to display {% load static %} <img src="{% static '{{form1}}' %}" width="1440" height="948" / it can't display but when i try this, it can display {% load static %} <img src="{% static 'media/abc2021x07x13/ch00002_01000000025099767142400187070_29H75756.jpg' %}" width="1440" height="948" /> -
How can you seperate admin from normal site login sessions in django?
I have created a web app but I want to separate the /admin and the site session,in that whenever I login into the site,it doesn't automatically login to the /admin part of the site. Any advise or solution to the above? -
Django - Choose item for each M2M field
class Product(models.Model): '''for example > apple, tomato, smart phone, watermelon, laptop ''' name = models.CharField(max_length=255) class Box(models.Model): ''' Lets say box types are : Small Box, Medium Box, Large Box''' box_name = models.CharField(max_length=255) class Orders(models.Model): products = models.ManyToManyField(Product) '''choose many item at the same moment, lets say apple & laptop & tomato and for each item choose box. Expected process (In one time and same time) : APPLE - Small Box, LAPTOP - Large Box, Tomato - Medium Box ''' I tried everything but I couldnt get success. I tried intermediate models with fk but it didnt work too. -
DRF pagination with ordering
Have trouble with pagination and ordering at the same time. Problem is that one instance can be returned by view multiple times: for example on page 9 and then on page 11. View: from rest_framework import filters, viewsets from django_filters.rest_framework import DjangoFilterBackend from django_filters import FilterSet from django_filters.filters import CharFilter class TariffFilter(FilterSet): concat_code = CharFilter(field_name='concat_code') class Meta: model = Tariff fields = { 'id': ['in', 'exact'], 'title': ['exact', 'icontains', 'in'], .... } class TariffPagination(PageNumberPagination): page_size = 10 page_size_query_param = 'page_size' class TariffListViewSet(viewsets.ModelViewSet): pagination_class = TariffPagination serializer_class = tariff_serializer.TariffSerializer filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter,) filterset_class = TariffFilter ordering_fields = ['id', 'title', ...] search_fields = ['title', ...] def get_queryset(self): concated_code = Concat(...., output_field=CharField()) queryset = Tariff.not_deleted_objects.annotate(concat_code=concated_code) return queryset Serializer: class TariffSerializer(serializers.ModelSerializer): element = TariffElementSerializer() service = ServiceElementSerializer() class Meta: model = Tariff fields = ('pk', 'title', 'code', 'element', 'service', 'concated_code', ) Where is problem? example problem query: http://127.0.0.1:8000/api/?ordering=-title&page=2 -
Inserting objects inside a foriegn key relationship in Django
I have a recipe, and it has a list of steps, related like so: class Recipe(Model): name = CharField() class Step(Model): recipe = ForeignKey('Recipe', related_name='steps') Now when editing the recipe, I want to be able to insert a new step between two others. But when I create a new step, it always get added to the end of recipe.steps. Using recipe.steps.set([step_1, step_2, step_3]) doesn't work, as apparently set() only works on nullable fields. I'd like to avoid having to change the model just to support this, but I can't seem to find a way to do this otherwise. -
How do get request.user in django models.py
I want to do some checks in Django models.py and need to get the logged-in user, like request.user as it is used in views.py. I want to append the username to this return statement if the condition is met like this below: class Store(models.Model): item_name = models.CharField(max_length=120, default='', blank=True, null=True) created_by = models.CharField(max_length=15, default='', blank=True, null=True) def __str__(self): item_user = self.item_name + ' - ' + self.created_by if request.user in item_user: return item_user else: return item_name -
Link directly to an App View in Django Baton Menu
Using Baton, I want to link directly to a particular view in an app. Can fudge it by just hard-coding the URL: BATON = { "SITE_HEADER": "My App", "MENU": ( { "type": "app", "name": "core", "label": "Management", "icon": "fa fa-cog", "models": ( {"name": "client", "label": "Clients"}, {"name": "invoice", "label": "Invoices"}, ), }, { "type": "free", "name": "docs", "label": "Documentation", "icon": "fa fa-info", "url": "https://www.myurl.com/docs/", }, ), Tried using "view" or "views" the way Models is done: { "type": "app", "name": "docs", "label": "Documentation", "icon": "fa fa-info", "view": {"docs_general"}, }, And { "type": "app", "name": "docs", "label": "Documentation", "icon": "fa fa-info", "views": ({"docs_general"}), }, Doesn't seem to be documented. -
GeoDjango PointField | JSON serializer | coordinates
So I have this problem in my app. When I try to create user that have attribute "location" that is a GeoDjango PointField, only value set as 'default' is saved... When I send request with postman, that 'location field' is ignored. In installed apps: ... djangorestframework-gis, django.contrib.gis ... Postgis is installed and database is created with postgis extension. This is part of models.py User object class User(AbstractBaseUser): ... location = models.PointField(geography=True, spatial_index=True,default=Point(0.0, 0.0, srid=4326)) ... This is what I tried as JSON: { "location": "POINT(-120.18444970926208 50.65664762026928)" } { "location": { "type":"Point", "coordinates": "[34.000, 21.000]" } } { "location": { "type":"Point", "coordinates": { "lng":"21.000", "lat":"32.000" } } } In the DB,location fields is populated with default coordinates that`s are 0.0, 0.0. DB GeoHash --> 0101000020E610000000000000000000000000000000000000 I do not know what I am doing wrong and that is frustrating.... I think that my JSON is wrong and that`s way serializer save default. -
Django Using conditional in template based on foreginKey value?
I'm wondering if you can use conditions to change what is shown from the template based on a foreignKey. On my project, users will choose a muscle group they want to workout (Chest, Back, Legs, etc.), meaning each workout has a foreginKey to a large muscle group. I want to make it so if a user chooses a workout that has a foreignKey to Legs, that the template will be unique vs. if the workout was a Chest exercise. Any way to do this? -
Test req POST django
why return erro if trying this: error: TypeError: expected string or bytes-like object def test_post_redeem(self): data={ "title": "post redeem", "image": self.file, "amount": 1, "description": "descr", } user={ "username":'test', "email": "test@fanhub.com.br", "password":"have_senha", } client = APIClient() client.force_authenticate(user=self.user) response = self.client.post('/redeem',user, data,format='json') self.assertEqual(response.status_code, 200) else if trying response = self.client.post('/redeem',user, data,format='json') return this error : AssertionError: 400 != 200 I no have idea with this error -
Empty Response even if there should be data [Django] [DRF]
I'm currently having this issue and i can't figure out what and where am i getting it wrong. I was hoping if the community can shed some light to the right path. I'm new to Django and was hoping to learn this framework so that i can use this on all of my projects. This is my serializers: class ItemTypeSerialzier(ModelSerializer): class Meta: model = ItemType fields = ['id','name'] class SupplierSerializer(ModelSerializer): class Meta: model = Supplier fields = ['id','name', 'address', 'phone', 'email_address',] class ItemSerializer(ModelSerializer): item_type = serializers.SerializerMethodField() def get_item_type(self, obj): queryset = ItemType.objects.filter(id=obj.id,is_deleted=False) serializer = ItemTypeSerialzier(queryset, many=True) print(serializer.data) return serializer.data supplier = serializers.SerializerMethodField() def get_supplier(self, obj): queryset = Supplier.objects.filter(id=obj.id,is_deleted=False) serializer = SupplierSerializer(queryset, many=True) return serializer.data class Meta: model = Item fields = ['id', 'name', 'description','quantity', 'item_type', 'supplier'] Here are my models: class ItemType(models.Model): name = models.CharField(max_length=50) is_deleted = models.BooleanField() dt_created = models.DateTimeField(auto_now_add=True, editable=False) def __str__(self): return self.name class Meta: db_table = 'item_type' class Supplier(models.Model): name=models.CharField(max_length=100) address = models.CharField(max_length=200, null=True, blank=True) phone = models.CharField(max_length=11, null=True, blank=True) email_address = models.CharField(max_length=50, null=True, blank=True) is_deleted = models.BooleanField() dt_created = models.DateTimeField(auto_now_add=True, editable=False) def __str__(self): return self.name class Meta: db_table = 'supplier' class Item(models.Model): item_type = models.ForeignKey(ItemType, on_delete=CASCADE, related_name='item_type') supplier = models.ForeignKey(Supplier, on_delete=CASCADE, related_name='supplier') name = models.CharField(max_length=50) … -
How do i change the default file upload button in django
I want to style my file upload button for my django project using bootstrap but its not just working Here is the code I tried <button class="btn btn-primary" action="{{ form.picture }}">Upload picture</button> What I want to do is, I want the button to link to the file upload so it brings a pop up for a user to select pictures but the button should be styled in bootstrap Thanks for your contribution -
set_cookie() got an unexpected keyword argument 'SameSite'
set_cookie() got an unexpected keyword argument 'SameSite' this message is getting from console. I was making a django api response.set_cookie(key ='jwt', value = token, httponly=True,SameSite=None,Secure=True) this is my code. Thanks in Advance. -
Django cant seemto link css/js
I know this subject has been discussed before, but ive seen every tutorial and form in stack overflow but cant seem to understand why i cant link my CSS to my HTML file. This is my directory: There are 2 apps, main & settings. For the app named main, i was able to link the html file in from views.py. I am now trying to link css & js to it. I created a static file within the base directory that contains 3 folders, css,js,image. I believe to have taken all the correct steps in order to connect CSS to HTML, but nothing happens. I believe that the mistake is with the reference in the HTML file: <link rel=”stylesheet” href=”{% static 'css/style_login.css' %}”> But from what ive seen, it seems to be correct. Bellow ive shared the settings, views, and HTML File. Settings.py: """ Django settings for auditor project. Generated by 'django-admin startproject' using Django 3.2.4. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path import os PROJECT_DIR = os.path.dirname(__file__) # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # … -
Assigning a foreign key by a unique, non-primary key field in one query
Say I have the following two models: class User(Model): email = models.EmailField(unique=True) class Post(Model): author = models.ForeignKey(User, on_delete=models.CASCADE) Now, let's say that I have a user's email address, and I want to set that user as a post's author. I could do this like so: post = Post() # Just get the ID to avoid having to load a whole model post.author_id = User.objects.values_list('pk', flat=True).get(email=user_email_address) post.save() However, this results in two queries: one to get the user, and one to save the post. I would like to know if there is a way to do this in one query. I do not want to change the to_field of the ForeignKey. -
How can add jquery formBuilder with django
I am trying to add jquery formBuilder in django. the package is available in npm i install and add it. I follow the documentation but nothing show on page html {% extends 'home.html' %} {% load static %} {% block title%} {% block head %} <meta charset="UTF-8"> <title>Form Build</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script> jQuery($ => { const fbTemplate = document.getElementById('build-wrap'); $(fbTemplate).formBuilder(); }); </script> {% endblock head %} {% endblock title%} {% block content%} <div class="build-wrap"></div> {% endblock %} -
Django: Hotel Reservation database start_date and end_date
I have a Django model that looks something like this Class Reservation(models.Model): room = models.ForeignKey(Room) start_date = models.DateTimeField(default=timezone.now, null=True) end_date = models.DateTimeField(default=timezone.now, null=True) person = models.ManyToManyField(Person, related_name="people") A Room can have multiple reservation and a reservation can take multiple people. I want to the availability spaces in a given room over the next 30 days. availability is simply total number of people a room can take - total number of people in active rentals. This is so that users booking a new rental know how many people a room can take. -
How to prevent Error: 403 in ModelAdmin.autocomplete_fields?
ModelAdmin.autocomplete_fields looks to be very simple to implement into the Django admin: class UserAdmin(admin.ModelAdmin): autocomplete_fields = ['material'] admin.site.register(User, UserAdmin) class MaterialAdmin(admin.ModelAdmin): search_fields = ['name'] admin.site.register(Material, MaterialAdmin) It renders the field correctly (as a search field instead of a dropdown), but the search field says "The results could not be loaded" and inspect shows: */admin/autocomplete/ 403 (Forbidden) jquery.js:9203 I assume there is a csrf issue receiving data from the Material model. I looked into ways to exempt this request from csrf but couldn't figure out how to do it through ModelAdmin.autocomplete_fields. I tried using django-autocomplete-light as well and couldn't get it working. -
Running python code after sweet alert button press - Django
I want to run a python code such as print('test') after the user clicks the ok button in the bellow code. How exactly do I do that? Not sure if I need a view or if I can do it straight from JS function showAlert() { swal({ title: "Accept Donation", text: "Are you sure you would like to accept the donation titled {{donation.title}}, which was posted on {{donation.date}} by {{donation.user}}?", icon: "info", buttons: true, }) .then((ok) => { if (ok) { swal("Donation successfully accepted, please contact {{donation.user}} at {{donation.phonenumber}}, for instructions as to when and where you should pick up the donation", { icon: "success", }); } }); } -
How to call a static file from a block styling url in django properly
I have the following line: <div class="slide-item" style="background: url('{%static 'images/landing/slide/slide1.jpg'%}');"> .This correctly gets the image I intend but VSCode marks it as an error with the following messages: at-rule or selector expected ) expected. I am not sure how this can be fixed and I already tried double quotes with no success. All my html files are in the templates folder and my css,js and images on the static folder. The page works correctly but the fact that is marked as an error makes me wonder if there is a better way. -
Django - model formset - front end validation not working
I'm working with a model formset. this is my form: class UnloadForm(forms.ModelForm): class Meta: model = Unload fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['fieldContract'].queryset = FieldContract.objects.filter(applicativeContract__contract__is_active=True).order_by('applicativeContract__contract__internal_code', 'applicativeContract__internal_code', 'internal_code') self.fields['product'].queryset = Product.objects.all().order_by('name') class BaseUnloadFormset(BaseModelFormSet): def clean(self): super().clean() for form in self.forms: cd = form.cleaned_data whouse = cd['whouse'] company = cd['company'] product = cd['product'] quantity = cd['quantity'] movement_date = cd['movement_date'] helper = StockHelper(product, whouse, company, movement_date) if quantity > helper.stock: raise ValidationError(f'Attenzione quantità massima disponibile di {product}: {helper.stock}') return cd UnloadFormSet = modelformset_factory( model = Unload, fields = '__all__', extra = 5, form = UnloadForm, formset=BaseUnloadFormset ) class UnloadFormSetHelper(FormHelper): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.form_tag = False self.layout = Layout( Row( 'whouse', 'fieldContract', 'company', 'product', 'quantity', 'movement_date', ) ) self.render_required_fields = True the problem occurs, when I've added the clean method in the BaseUnloadFormset. Since all fields in the model are required, for example not stating the movement_date would prompt a front-end validation. Unfortunately, although the source code of the web page shows that the field is actually required, forgetting the movement_date would send the form to the back-end and eventually the system would crash since there is no movement_date in the cleaned_data dictonary, thus raising a KeyError. … -
How does fetch send the auth token in the request
I've developed an API with django rest framework, my frontend is built in vue js, so I have to use fetch to communicate with the API. function apiService(endpoint, method, data) { const config = { method: method || 'GET', body: data !== undefined ? JSON.stringify(data) : null, headers: { 'content-type': 'application/json', 'X-CSRFToken': CSRF_TOKEN } }; return fetch(endpoint, config) .then(data => getJson(data)) .catch(err => err) }; I've noticed that this code works properly, but I have a doubt on the fact that, because I've added the authentication permission on the api, I would have to send a token in the request, because I'm not conneccting from a browser. So, how this token is send to the api, if I don't send it. -
SimpleJwtAuthentication problem ...Even after presence of user ,url not giving token
i am using this model extending from abstractuser but even after successfully creating user i am not able to get the tokens.... Tokens are genrerated only for those which i created through python manage.py createsuperuser ..others not working. why???? i am using simplejwt authentication. models.py from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class user_model(AbstractUser): email=models.CharField(max_length=200,blank=True) age=models.CharField(max_length=200,blank=True) dob=models.CharField(max_length=200,blank=True) phone=models.CharField(max_length=200,blank=True) def __str__(self): return self.username urls.py from django.contrib import admin from django.urls import path,include from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, ) urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('signup/',include('userdata.urls')), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('loggedIn/',include("notes.urls")), ]