Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to redirect back to current page in Django once a button is clicked?
Currently this view redirects back to homepage. def wishlist(request, title_slug): obj = get_object_or_404(Listing, slug=title_slug) profile = Profile.objects.all().filter(user=request.user).first() profile.wishlist.add(obj) return HttpResponseRedirect('/') I have this button in list view and detail view: <a href="{% url 'listing:wishlist' listing.slug %}"> <i class="fas fa-heart"></i> </a> No matter where the user adds an item to wishlist, it should be redirected back to that list view or detail view. Thank you -
How to validate google recaptcha(site need to verifiy) if i am using django as backend & angualarjs as frontend
For google recaptcha v2 validation we need to send the POST request with recaptcha token respons with secret key to google server api i.e.https://www.google.com/recaptcha/api/siteverify from backend only. For recaptcha implemenation i have used the ng-recaptcha module as i am getting the valid recaptcha response token in angularjs How do I get value of recaptcha token response from angular to django for sending post request. How angular communicate with django within same Application ? -
Creating user without username (or with auto-generated username)
I want to create a registration page that doesn't ask for an username, since i'm not planning on using it (i only need email and password). However, i'm not sure how to tell django that username is not mandatory. I'm having trouble registering users because they all get the same username (blank). My user model: class User(AbstractUser): departments = models.ManyToManyField(Department) def __str__(self): return f'{self.first_name} {self.last_name}' My form for registering: class UserCreateForm(UserCreationForm): class Meta(): fields = ('first_name', 'last_name', 'email', 'departments', 'password1', 'password2') model = get_user_model() The view: class SignUpView(CreateView): form_class = UserCreateForm success_url = reverse_lazy('loginPage') template_name = 'accounts/signup.html' What should i change in order to tell django to ignore the username field for the User model? Is a random auto-generated username a good idea to avoid this problem? If yes, how do i code it? -
Refused to execute *path_to_bundle* as script because "X-Content-Type: nosniff" was given and its Content-Type is not a script MIME type
I'm developing web app using Django as a backend and Vue js as a frontend. I connected them via webpack. When I develop app in Dev mode, everything is good, I don't use chunks, which are created using npm run build. But when it comes to Stage or Prod mode, when DEBUG=False on Django, and npm run build on vue js, to build all static files, I got error Refused to execute http://localhost:8000/static/sections_dist/js/chunk-common.34112dfe.js as script because "X-Content-Type: nosniff" was given and its Content-Type is not a script MIME type. Did not parse stylesheet at 'http://localhost:8000/static/sections_dist/css/chunk-common.677f6644.css' because non CSS MIME types are not allowed in strict mode. maybe I'm using incorrect webpack settings, please help me with that... My webpack.config.js: const BundleTracker = require("webpack-bundle-tracker") const path = require('path') module.exports = { publicPath: "/static/sections_dist/", outputDir: '../loppeonline/static/sections_dist/', chainWebpack: config => { // config.optimization // .splitChunks(false) config .plugin('BundleTracker') .use(BundleTracker, [{filename: '../frontend/webpack-stats.json'}]) config.devServer .public('http://0.0.0.0:8000') .host('0.0.0.0') .port(8080) .hotOnly(true) .watchOptions({poll: 1000}) .https(false) .headers({ 'Access-Control-Allow-Origin': ['*'] }) } } my base.html body, where I render bundles: <body> <div id="app"> </div> {% if not settings.DEBUG %} {% render_bundle 'chunk-common' 'js' 'SECTIONS' %} {% render_bundle 'chunk-vendors' 'js' 'SECTIONS' %} {% render_bundle 'chunk-vendors' 'css' 'SECTIONS' %} {% render_bundle 'chunk-common' 'css' 'SECTIONS' … -
Add extra field in response output in DRF 3.0
I have the following models class Restaurant(models.Model): name_of_the_restaurant = models.CharField(max_length=30, blank=True) opening_time = models.TimeField(auto_now=False, auto_now_add=False) closing_time = models.TimeField(auto_now=False, auto_now_add=False) And class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) city = models.CharField(max_length=30, blank=True) country = models.CharField(max_length=30, blank=True) postal_code = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) favourite_restaurant = models.ManyToManyField(Restaurant, blank=True, related_name='favourite_restaurant', related_query_name='favourite_restaurant') I have defined a serializer for Restaurant model which is mainly : class RestaurantSerializer(serializers.ModelSerializer): class Meta: model = Restaurant fields = '__all__' Now in my ViewSet logic I am doing the following : class RestaurantListView(generics.ListAPIView): serializer_class = RestaurantSerializer def get_queryset(self): queryset = {'Error': 'Please pass valid url parameters'} city = self.request.query_params.get('city', None) postal_code = self.request.query_params.get('postalcode', None) country = self.request.query_params.get('country', None) if city is not None or postal_code is not None: queryset = Restaurant.objects.filter( Q(city=city) | Q(pincode=postal_code)) if country and city is not None and postal_code is None: queryset = Restaurant.objects.filter(country=country, city=city) return queryset def get(self, request, format=None): restaurant_qs = self.get_queryset() ids_list = [restaurant.id for restaurant in restaurant_qs] favourite_restaurant = is_favourite_restaurant(ids_list, self.request.user) serializer = RestaurantSerializer(restaurant_qs, many=True) return Response(serializer.data) where is_favourite_restaurant is a custom function function which returns queryset of FAVOURITE restaurant(s) of a user. Now in the output for this GET request I am getting result as : [ … -
Django language session not existing
I have made a website which supports two languages at the moment. It has been made with django.utils.translation (Using makemessages and compilemessages). The site is working fine locally on my own machine, and translating correctly. When i pull the code on the website server (and restart the app) it gives the following error: `Internal Server Error: /da/ Traceback (most recent call last): File "/home/myname/.virtualenvs/myEnv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/myname/.virtualenvs/myEnv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/myname/.virtualenvs/myEnv/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/myname/myname/myname_django/home/views.py", line 62, in index 'value': get_value(request.session[LANGUAGE_SESSION_KEY]), File "/home/myname/.virtualenvs/myEnv/lib/python3.7/site-packages/django/contrib/sessions/backends/base.py", line 54, in __getitem__ return self._session[key] KeyError: '_language'` So for some reason it cannot find the language session, but i have no clue why -
Reverse for 'janre_detail_url' with keyword arguments '{'slug': 'detectiv'}' not found. 1 pattern(s) tried: ['cards/janre/<str:slug/>$']
Good afternoon. I have the following problem. I tried to fix it in various ways, but nothing helps. I would be happy to help. I read that the problem may be that there is an error somewhere that can't take data from the database, however I don't understand where this might be. I am a novice developer on Django. Thanks! models.py from django.shortcuts import reverse class Post(models.Model): title = models.CharField(max_length=150, db_index=True) slug = models.SlugField(max_length=150, unique=True) body = models.TextField(blank=True, db_index=True) tags = models.ManyToManyField('Tag', blank=True, related_name='posts') date_pub = models.DateTimeField(auto_now_add=True) def get_absolute_url(self): return reverse('post_detail_url', kwargs={'slug': self.slug}) def __str__(self): return self.title class Tag(models.Model): title = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True) def get_absolute_url(self): return reverse('tag_detail_url', kwargs={'slug': self.slug}) def __str__(self): return '{}'.format(self.title) views.py from django.shortcuts import render from django.views.generic import View from django.http import HttpResponse from .models import Card, Janre def card_page(request): cards = Card.objects.all() return render(request, template_name='cards/card_page.html', context={'cards': cards}) def card_detail(request, slug): card = Card.objects.get(slug__iexact=slug) return render(request, template_name='cards/card_detail.html', context={'card': card}) def janres_page(request): janres = Janre.objects.all() return render(request, template_name='cards/janres_page.html', context={'janres': janres}) def janre_detail(request, slug): janre = Janre.objects.get(slug__iexact=slug) return render(request, template_name='cards/janre_detail.html', context={'janre': janre}) urls.py from django.urls import path from .views import card_page, card_detail, janres_page, janre_detail urlpatterns = [ path('', card_page, name='card_page_url'), path('card/<str:slug>/', card_detail, name='card_detail_url'), path('janres/', janres_page, name='janres_page_url'), … -
Django - getting model from another database
Is there a simple method to import model data from another database? Supose i have 2 databases: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'first_db', 'USER': 'admin', 'PASSWORD': '', 'HOST': 'localhost', }, 'second': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'second_db', 'USER': 'admin', 'PASSWORD': '', 'HOST': 'localhost', }, } One app with model in database: second_db class Client(models.Model): first_name = models.CharField(max_length=100, blank=True, null=True) and i wont to get data from this model and load it to default database: first_db data = Client.objects.using('second_db').all() Question: Is there option to do this without creating mirror empty app in default database? With usage of database Router or manually selecting a database with .using() Some related questions: link, link2 -
(admin.E202) 'core.Item_stock' has no ForeignKey to 'core.Item_stock'. in django
**I'm setting up Django admins with: model.py class Item_size (models.Model): size_label=models.CharField( max_length=50) size_catagory=models.ForeignKey('catagory',limit_choices_to={'cat_min__isnull':False}, verbose_name= ("catagory"), on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.size_label class Item_stock (models.Model): product=models.ForeignKey('Item',on_delete=models.CASCADE) size=models.ForeignKey('Item_size',default=0,on_delete=models.CASCADE) size_q=models.IntegerField(default=0) def __str__(self): return self.product.title And at admin.py class ItemStockInstanceInline(admin.TabularInline): model = Item_stock @admin.register(Item_stock) class ItemStockAdmin(admin.ModelAdmin): list_display = ['product', 'size', 'size_q'] inlines = [ItemStockInstanceInline] With this I'm getting the following error: ERRORS: <class 'core.admin.ItemStockInstanceInline'>: (admin.E202) 'core.Item_stock' has no ForeignKey to 'core.Item_stock'. -
Django getting the M2M instances into the save method
im trying to implement a notifications system that will enable me to notify a user if a new object is created in my database. In order to do that , i initially adopted a signals method. However , using the m2m_changed method does not allow me to distinguish between a create or a update scenario. Moreover i have been told that using signals for this is an anti-pattern. That being said , i am now attempting to use the save() method to handle the creation logic of my notifications. Models.py Here is a watered down version of my model class SalesProject(models.Model): sales_project_name = models.CharField(max_length=100) userProfile = models.ManyToManyField('UserProfile', blank=True) customer_information = models.ManyToManyField('CustomerInformation') def save(self, *args, **kwargs): print(self.customer_information.all()) super(SalesProject, self).save(*args, **kwargs) As you can see there are 2 M2M fields here , userProfile and customer_infomation. When the user updates the SalesProject instance by lets say adding a customer_infomation instance to the M2M relation , it does not reflect at print(self.customer_information.all()) as expected , since Django only adds the M2M field after the 'host' object is saved into database. Therefore with this in mind i have 2 questions: From what i understand , it is not possible to know if the m2m_changed signal … -
Cannot connect to postgresql databse from django settings.py on localhost
Forgive me as I this is my first django project using postgresql. For now I just want to connect to a test database which I have set up locally using pgadmin4. When I create the database I am not given the option to add a password, but when I run python manage.py migrate it is insisting on a password. When I then set the password to "password" on pgadmin, django won't accept it. It's probably something really obvious as I am quite new to Django, but I have tried searching and not found the answer to my problem. In settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'test1', 'USER': 'postgres', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '5432', } } Last line of the error when I run python manage.py migrate: django.db.utils.OperationalError: fe_sendauth: no password supplied Any help much appreciated. Craig -
Django Polls App clickable radio buttons?
I've recently finished the Django polls tutorial, now I'm trying to make clickable links out of the radio choices buttons on the detail.html page. I've tried about everything but can't seem to get it to work. Could anyone send me in the right direction? <h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br /> <a href="{% url 'choice' %}"/> {% endfor %} <input type="submit" value="Vote" /> </form> -
Give name to object model in Django Rest Framework
I need help to give name "Product" to every object in "Products" array. But I can't find way to do it. I'm using ViewSets and ModelSerializer What I want: products: [ Product: {id: 1, name: 1}, Product: {id: 2, name: 2}, ] What I have: products: [ {id: 1, name: 1}, {id: 2, name: 2}, ] models.py class Product(models.Model): image = models.FileField(blank=True) name = models.CharField(max_length=120) volume = models.DecimalField(decimal_places=0, max_digits=1000) collection = models.ForeignKey('Collection', on_delete=models.CASCADE) def __str__(self): return self.name serializers.py class ProductSerializer(serializers.ModelSerializer): collection = CollectionInProductSerializer() combination = CombinationInProductSerializer(many=True) recomendations = RecomendedProductSerializer(many=True) class Meta: model = Product fields = '__all__' -
Django - Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`
Why i am getting this error? Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'NoneType'> how do i solve this ? my Homepage/api/views.py from rest_framework import status from rest_framework.response import Response from rest_framework.decorators import api_view from Homepage.models import EducationLevel from Homepage.api.serializers import EducationLevelSerializer @api_view(['GET', ]) def api_detail_educationlevel(request): try: education = EducationLevel.objects.all() except EducationLevel.DoesNotExist: return Response(status=status.HTTP_400_BAD_REQUEST) if request.method == "GET": serializer = EducationLevelSerializer(education) return Response(serializer.data) Homepage/api/serializers.py from rest_framework import serializers from Homepage.models import EducationLevel class EducationLevelSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = EducationLevel field = ('Sequence', 'Description', 'Status') my Homepage/api/urls.py from django.urls import path from Homepage.api.views import api_detail_educationlevel app_name='educationlevel' urlpatterns = [ path('', api_detail_educationlevel, name="detail"), ] my main urls.py urlpatterns = [ path('api/educationlevel/', include('Homepage.api.urls', 'educationlevel_api')), ] -
How to call asynchronous function in Django?
The following doesn't execute foo and gives RuntimeWarning: coroutine 'foo' was never awaited # urls.py async def foo(data): // process data ... @api_view(['POST']) def endpoint(request): data = request.data.get('data') // How to call foo here? foo(data) return Response({}) -
Integrate legacy MongoDB into Django
I have an existing MongoDB that has over 18k objects. Each object is of 23 fields, some of them have a multilevel nesting. I don't have experience working with Mongo in Django RF but from my experience working with SQL, I know I need to have models defined. There is an introspect function in Django that can create models.py from a legacy DB but it does not seem to work with NoSQL. My question is: how can I introspect my existing MongoDB into a Django model? if the first method is not an option, what is the right way to solve this issue in Django? -
Cannot loaddata to Django (MySQL) DB
I'm trying to load django data which I took backup using the below command ./manage.py dumpdata --exclude auth.permission --exclude contenttypes > django_db_backup.json When I'm trying to load the data back using ./manage.py loaddata django_db_backup.json I'm getting the below error. django.db.utils.OperationalError: Problem installing fixture 'path/to/django_db_backup.json': Could not load auth.User(pk=5): (1205, 'Lock wait timeout exceeded; try restarting transaction') Can anyone please help me with this? -
multiple form gerated jquery doesn't submit
I'm building a website (e-commerce like) with Django. At some point I display a list of items and for each item there is a form with submit button Order and Quantity picker. I've implemented filter function that delete the html code of my items list and rebuild it with the matching items with jquery. The new forms generated by this function do nothing when the submit button is clicked Here is a part of the code I use in my function (I use an ajax call to generate a json of matching items and then I display them in the table list) : $.each(code_json, function(index, value){ var string = "<tr id="+ value.material +"><td>"+ value.manufNo +"</td><form method='POST' action='/add_to_cart/"+value.material+"/"+ value.node+"/{{language}}'><td><input type='submit' class='btn' value='Commander' style='color:blue;'></td><td><input id='qty' type='number' name='qty' class='form-control' value='1'></td></form></tr>"; $("#header").after(string); }); I know that usually with Django you have to add {% csrf_token %} for each form. However it throw an error page usually when missing and here it doesn't show anything Thank you for your help -
overriding get_fields in ModelAdmin return this fiels on all model
I need to add languages related fields to ModelAdmin, for save as json after. But these fields appear in all the models of my applications. Why? For example with a simple app: models.py: from django.db import models class TestModel2(models.Model): txt_field = models.TextField() class TestModel(models.Model): txt_field = models.TextField() admin.py: from moduleadmin.models import TestModel, TestModel2 from django.conf import settings from django import forms class TestModelAdmin(admin.ModelAdmin): def get_fields(self, request, obj=None): my_fields = super(TestModelAdmin, self).get_fields(request, obj) new_fields = [(lang[0], forms.CharField(max_length=50, required=(lang[0] == settings.LANGUAGE_CODE)) ) for lang in settings.LANGUAGES] for f in new_fields: if f[0] not in my_fields: my_fields.append(f[0]) self.form.declared_fields.update({f[0]: f[1]}) return my_fields admin.site.register(TestModel, TestModelAdmin) admin.site.register(TestModel2) and in settings.py I've added: LANGUAGES = ( ('fr', 'French'), ('en', 'English'), ) So if I try to add one TestModel2 entry, It's ok. But if i go to TestModel add entry form, and return to TestModel2 add, I've the two fields appear in forms. Can you help me? Or maybe there's a better approach? Thanks. -
Changing the way the admin panel looks when I am viewing a model object
I am learning Django and have a question around changing the way something looks in the admin panel. Right now when I click on an object of one of my models it looks like this.. enter image description here I am using an ArrayField with a Postgresql database to allow that. But what I want to do is change it to look like this: enter image description here I believe I need to override something in the admin panel but I am not sure which template it is or if this is possible. -
Queryset ordering for nested objects
I need to build a simple nested comment system in my project with REST api. There are some requirements: The page should contain the pagination of all comments, not just the parent ones. So, if there are 1 comment and 20 nested comments from other users, then on the first page should be displayed, like so: -Comment 1 -- Sub comment 1 -- ... -- Sub comment 9 On the second page: -- Sub comment 10 -- ... -- Sub comment 19 On the third page: -- Sub comment 20 And it should be an optimal solution in terms of the least database access. I was wondering about custom Queryset ordering, when after each comment follows nested comments, like so: // Note, that ids follow in chaotic order { id: 1, text: "Comment 1", parent: null }, { id: 5, text: "Sub comment 1 for Comment 1", parent: 1 }, { id: 6, text: "Sub comment 2 for Comment 1", parent: 1 }, { id: 2, text: "Comment 2", parent: null }, { id: 3, text: "Sub comment 1 for Comment 2", parent: 2 }, { id: 4, text: "Sub comment 2 for Comment 2", parent: 2 }, I've also … -
Custom authentication_classes in Django Rest Framework with Knox
I have a Django Rest Framework API, in this API I use Knox to connect / disconnect my users. I have a view (PollViewSet) which if the user is connected my view returns his personal data, if the user is anonymous my view returns the basic data. So, when an user logs in, Knox create a token for this user for 10 hours, connect my user, and so my view return his personal datas. But after 10 hours, the token is destroyed, and if my user refreshes his web page, he sends the request with an old token. Because of this, my view does not return basic data as an anonymous user, but returns Invalid Token. I would like that if I send an invalid token to my view, my request is treated as an anonymous user and does not trigger an "invalid token" error. I tried to create a custom authentication_classes but I have a problem with the token_key, and that doesn't seem like a good way to do it. I am interested in any help to help me with this problem ! Here my code with the important parts: settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'knox.auth.TokenAuthentication', ) } … -
'WSGIRequest' object has no attribute 'profileaccount'
I am getting the following error and I want to return a model profileaccounts.id but it is not within WSGIRequest. Is there a way to find all the objects with WSGIRequest? ERROR LOG AttributeError at /2/detail/ 'WSGIRequest' object has no attribute 'profileaccount' Views.py class ProfileAccountDetailView(LoginRequiredMixin, DetailView): model = ProfileAccount fields = [ 'first_name', 'family_name', 'email', 'account_active', ] def get_success_url(self): return reverse( "profiles:detail", kwargs={'pk': self.request.profileaccount.id}, ) def get_object(self): return ProfileAccount.objects.get( pk=self.request.profileaccount.id ) -
Using Nibabel in Django
I am making a web app that converts .nii files to png(zip). I have implemented the main logic in python but am facing problems porting it to the web app. So I want to create a form that accepts a .nii file and outputs a zip file containing all the .png slices. So far I've written a simple view: Views.py from django.shortcuts import render from .forms import SharingForms from django.http import HttpResponse import imageio,nibabel,numpy from zipfile import ZipFile from .models import NII def index(request, **kwargs): if request.method == 'POST': form = SharingForms(request.POST,request.FILES) if form.is_valid(): for field in request.FILES.keys(): for formfile in request.FILES.getlist(field): file = NII(file = formfile) file.save() response = HttpResponse(content_type='application/zip') zip_file = ZipFile(response, 'w') image_array = nibabel.load(file).get_fdata() if len(image_array.shape) == 4: # set 4d array dimension values nx, ny, nz, nw = image_array.shape total_volumes = image_array.shape[3] total_slices = image_array.shape[2] for current_volume in range(0, total_volumes): slice_counter = 0 # iterate through slices for current_slice in range(0, total_slices): if (slice_counter % 1) == 0: # rotate or no rotate data = image_array[:, :, current_slice, current_volume] #alternate slices and save as png print('Saving image...') image_name = file[:-4] + "_t" + "{:0>3}".format(str(current_volume+1)) + "_z" + "{:0>3}".format(str(current_slice+1))+ ".png" imageio.imwrite(image_name, data) print('Saved.') zip_file.write(image_name) zip_file.close() response['Content-Disposition'] … -
Django Multi Tenant Schemas Media Files Path
I am using Django with Multi Tenant Schemas. Everything is working well on production, but I am having an issue with image media Path. My web server is an Apache2 installed on Ubuntu 18.04, in the site configuration file I have: ''' ServerName qibot.com.br ServerAlias tenant1.qibot.com.br tenant2.qibot.com.br tenant3.qibot.com.br ServerAdmin webmaster@localhost DocumentRoot /var/www/html Alias /static /var/www/qibot_system/static <Directory /var/www/qibot_system/static> Require all granted </Directory> Alias /media /var/www/qibot_system/media/ <Directory /var/www/qibot_system/media/> Require all granted </Directory> ... </VirtualHost> ''' In this way, if the media (image or video) file is requested, django looks for /var/www/qibot_system/media/ instead of /var/www/qibot_system/media/tenant1 or /var/www/qibot_system/media/tenant2 or /var/www/qibot_system/media/tenant3 My question is, there is a way to set the variable on the end of /var/www/qibot_system/media/XXXXXXXXX to provide right path to django? Best Regards