Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST API, after put/patch request, data cannot be seen in the get request anymore
My problem is after a put/patch request on api, I cannot see my products anymore at http://127.0.0.1:8000/api/products/ but I can still see them if i specify their id like so http://127.0.0.1:8000/api/products/1/ serializer.py class ProductSerializer(serializers.HyperlinkedModelSerializer): sku = serializers.SerializerMethodField() class Meta: model = Product fields = ['id', 'prodType', 'product_name', 'field1', 'field2', 'field3', 'sku', 'stock'] read_only_fields = ('id',) def get_sku(self, Product): fields = "" if(Product.id != ''): fields += str(Product.id).replace(" ","") + '/' if(Product.prodType != ''): fields += Product.prodType.replace(" ","") + '/' if(Product.product_name != ''): fields += Product.product_name.replace(" ","") + '/' if(Product.field1 != ''): fields += Product.field1.replace(" ","") + '/' if(Product.field2 != ''): fields += Product.field2.replace(" ","") + '/' if(Product.field3 != ''): fields += Product.field3.replace(" ","") + '/' return fields views.py class ProductViewSet(viewsets.ModelViewSet): """ API endpoint that allows product to be viewed """ queryset = Product.objects.all() serializer_class = ProductSerializer permission_classes = [permissions.AllowAny] -
"django-admin.py startproject" is not working
I am new to python and django framework. I am using python 3.7.2 and am using django version 2.1.4 When i use the command django-admin.py startproject hello it says tht file aldready exists But i had deleted the file long time back screenshot_1 when i tried to run django admin.py with a new project name(which is a project name i have not used), even though command was executed the project was not created screenshot 2 I tried using with path "C:\Users\mohit\AppData\Local\Programs\Python\Python37-32\Scripts\django-admin.py" too , but then also same above error was caused like the screenshots inserted above -
social_django returns the superuser instead of the current user when logging in
I've been trying to implement Facebook authentication using the social-auth-app-django library. Everything was working as expected --when logging in, a welcome message with the username would show up. The problem now is that when I create a superuser and login with Facebook the username of the superuser shows up instead of the current user (the one that I login in with Facebook). And when I delete the superuser and try to login again with Facebook the logging in stops. No errors appear but the signup page stays the same and nothing happens. So things go like this: 1- Logging in with Facebook for the first time works fine. "Welcome Hajar" shows up on the home page. 2- When creating a superuser with a username Admin and logging in with my Facebook account. "Welcome Admin" shows up on the home page. It doesn't show my Facebook username anymore. 3- When deleting the superuser and logging in again the application stops working. I keep clicking login with Facebook but nothing happens. Here is some of the code. # settings.py INSTALLED_APPS = [ ... 'core', 'social_django',] MIDDLEWARE = [ ... 'social_django.middleware.SocialAuthExceptionMiddleware',] AUTHENTICATION_BACKENDS = [ 'social_core.backends.facebook.FacebookOAuth2', 'django.contrib.auth.backends.ModelBackend',] LOGIN_URL = 'login' LOGIN_REDIRECT_URL = 'home' LOGOUT_URL … -
SAPB1 and django integration
im working on a new project where by i wish to be able to build a django project around an existing SAPB1 application that is in production. My goal of doing so is to be able to extract certain information from SAP database and sync them with my django database as well as write certain things into the SAP database from my django program. An example is , i would wish to generate a payment voucher from my program , and write it into the SAP data base. Is there a suitable API for such a task? I have done certain research and it seems like my client's SAPB1 does not have python RFC feature. A possible alternative would be the DI API , however most materials are written in c# which is not my expertise , therefore would love to hear your advise! thanks! -
App in docker container runs again and exits with message - fileds may not be blank
I have a django app which runs fine on local. But when I build the docker image and run the app from within the container, it runs fine and return status 200, but after some time it again returns status 400 with message, input fields are blank. Operations to perform: Apply all migrations: admin, auth, authtoken, contenttypes, sessions Running migrations: No migrations to apply. No changes detected Performing system checks... System check identified no issues (0 silenced). March 25, 2020 - 12:09:24 Django version 1.11.23, using settings 'TestSop.settings' Starting development server at http://0.0.0.0:8016/ Quit the server with CONTROL-C. [25/Mar/2020 12:09:35] "GET /TestSopApiView/ HTTP/1.1" 405 12315 [25/Mar/2020 12:09:41] "GET /TestSopApiView/ HTTP/1.1" 405 12315 [25/Mar/2020 12:10:03] "POST /TestSopApiView/ HTTP/1.1" 200 205 [25/Mar/2020 12:11:23] "POST /TestSopApiView/ HTTP/1.1" 400 189 {"field1":["This field may not be blank."],"field2":["This field may not be blank."],"field3":["This field may not be blank."],"field4":["This field may not be blank."]} This is my Dockerfile- FROM python:3.7 #Create Directory in Container ADD . /TestSop WORKDIR /TestSop COPY entrypoint.sh entrypoint.sh RUN pip install -r requirements.txt EXPOSE 8016 RUN apt-get -y update && apt-get -y upgrade && apt-get install -y curl && apt-get install -y jq RUN chmod +x /TestSop/entrypoint.sh RUN touch /TestSop/TestSop.log RUN chmod 777 … -
How to test functions that request data from external endpoints in django
I am trying to test my functions on my django api that perform external requests to external api. How can i test the following scenarios: success, failed, and exceptions like timeout The following is a simplified functionality def get_quote(*args): # log request try: response = requests.post(url, json=data) # parse this response except: # log file :) finally: # log_response(...) return parsed_response or None None: response can be success, failed, can timeout. I want to test those kind of scenarios -
Is there a way to trace only specific function?
I'm currently using patch_all with django web framework and it works fine. However, I would only like to log specific endpoints/traces based on some conditions. Is this possible? Or would I need to implement manual instrumentation across all my different endpoints for this? -
How do I populate db with Many-to-Many (with "through") Relationship?
I am new to Django and I am completely confused about how to add data to a db with a many-to-many relationship. What I'm working on is a small flashcard app that allows users to learn a list of words (language learning). But I'm not sure how I should add words for a particular Student Course combo. models.py class Language(Model): name = CharField(max_length=60) class Course(Model): name = CharField(max_length=60) description = TextField() language = ForeignKey(Language, on_delete=SET_NULL, null=True) class Word(Model): word = CharField(max_length=60) freq_rank = IntegerField() language = ForeignKey(Language, on_delete=PROTECT) class StudentCourse(Model): course = ForeignKey(Course, on_delete=CASCADE) student = ForeignKey(User, on_delete=CASCADE) words = ManyToManyField(Word, through='courses.WordProgress') class WordProgress(Model): student_course = ForeignKey(StudentCourse, on_delete=CASCADE) word = ForeignKey(Word, on_delete=CASCADE) last_review = DateTimeField(auto_now_add=True) next_review_sec = IntegerField(default=60) I have added data to Language, Course, Word, and User. But where I get stuck is how I can initialize a course with a set of words. How is ManyToManyField populated? I've seen some suggestions that it should be an array? In my case, should it be an array of words? i.e. {course: 1, user: 1, words: [1, 2, 3]} Or is this populated in some other way? Also, does through have an impact on any of this? Thanks for your help … -
Django - Do I need to check for IntegrityErrors when validating a ModelForm?
I"ve got a simple question: Do I need to listen for IntegrityErrors when I am already checking a submitted ModelForm's integrity with is_valid? My code looks like this at the moment and I am thinking about removing the try catch: def edit_object(request, object_id): o = get_object_or_404(ObjectModel, pk=object_id) if request.method == 'POST': form = ObjectForm(request.POST, instance=o) try: if form.is_valid(): form.save() return HttpResponseRedirect(reverse('namespace:startpage') else: return render(request, 'namespace/editpage.html', {'form': form,}) except IntegrityError: return render(request, 'namespace/editpage.html', {'form': form,}) return render(request, 'namespace/editpage.html', {'form': ObjectForm(instance=o),}) Since I never even save my object if the data is not valid, I should never be able to produce an IntegrityError-exception, right? Thanks in advance. -
Want to Set the footer in pdf on every page using pdfkit with python
I am using pdfkit with python to convert my html page to pdf with dynamic data, everything is working fine but i want to set the footer on every page if the length of the page exceeds the length of A4 size page, my content is dynamic so i cant hard code the length it will always change on runtime, so my concern is if the length of page exceeds than A4 length thne it places footer on both pages and same for more greater number of pages. Here is my code Where 'test' is my dictionary contains data to set in template html = render(request, 'pdf_template.html', {"test": test}) filename = test['product_name'] try: pdfkit.from_string(html.content.decode('utf-8'), filename, options=options) return render(request, 'pdf_template.html', {"test": test}) except Exception as e: return Response({"Status": False, "Message": e.__str__()}) These are my options options = { 'encoding': "UTF-8", 'margin-left': '0.50in', 'margin-top': '0.50in', 'margin-bottom': '0.50in', 'margin-right': '0.50in', 'orientation':'portrait', 'page-size':'A4' } -
Django: Add record to the database table if it is not present already
I am learning Django Rest Framework. I have been working on a small project where I am working on 4 models(database tables). The models are 1. Game 2. GameCategory 3. Player 4. PlayerScore. The table Game is having 5 columns in which category is the foreign key which links the tables Game and GameCategory. Below is the JSON payload for the API. "url": "http://127.0.0.1:8000/games/3/", "category": "Shooting", "name": "PUB G", "release_date": "2016-11-29", "played": true The table GameCategory has one column name. My current code is in such a way that if I am inserting a record into the table Game with a category which is not present in the table GameCategory I will get the following error message. "category": [ "Object with name=ABC does not exist." ] But I want it to be in a way that, when Game data is provided with the value for a category which does not exist in the GameCategory then that category should automatically be added to the GameCategory table, Sorry if it is a too basic question. I searched everywhere couldn't find the answer and also I am for this framework also to the web development. Thanks in advance.! -
Django: is_valid() method is always false why?
Everytime i get the stu_name variable value from form without using is_valid() function then stu_name is always return value enter by user but with is_valid() stu_name is always None.I do some experiments and i found that is_valid() is always return false but why? This is views.py file code. from django.shortcuts import render from django.http import HttpResponse from .models import student from .forms import student_data def my_data(request): stu_name=None myform=student_data(request.POST) if (request.method=="POST" and myform.is_valid()): stu_name=myform.cleaned_data['user'] else: myform=student_data return render(request,'show.html',{'student':stu_name}) This is my html file where the form code is written. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div> <form action="/payment/show/" method="POST"> {% csrf_token %} <label for="">Name</label> <input type="text" name="user" required> <label for="">ID</label> <input type="number" required> <label for="">Address</label> <input type="text" required> <button type="submit">Add Me</button> </form> </div> </body> </html> forms.py file code. from django import forms class student_data(forms.Form): name=forms.CharField(widget=forms.TextInput,max_length=20) id=forms.IntegerField(widget=forms.NumberInput,max_value=6) address=forms.CharField(widget=forms.TextInput,max_length=50) -
Is it possible to refer to button in this way?
Is it possible to turn to a certain button on an HTML page and dictate certain actions to it and if no how? views.py if request.method == 'POST': if request.POST.get('abc'): ...... if request.POST.get('bbc'): ..... html <form action="{% url 'new_channel' %}" method = "post"> {% csrf_token %} <button name="abc" type="submit"></button> ....... <button name="bbc" type="submit"></button> </form> Thanks in advance. -
Flutter Connection refused ,errno = 111
Django is the backend, i checked everything and it works fine.Mongodb is connected too ,tried 10.0.2.2 and localhost option too.Same problem . Can anybody help? E/flutter (26845): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: SocketException: OS Error: Connection refused, errno = 111, address = 127.0.0.1, port = 58759 E/flutter (26845): #0 IOClient.send (package:http/src/io_client.dart:33:24) E/flutter (26845): <asynchronous suspension> E/flutter (26845): #1 BaseClient._sendUnstreamed (package:http/src/base_client.dart:176:38) E/flutter (26845): #2 BaseClient.post (package:http/src/base_client.dart:58:7) E/flutter (26845): #3 post.<anonymous closure> (package:http/http.dart:70:16) E/flutter (26845): #4 _withClient (package:http/http.dart:166:20) E/flutter (26845): #5 post (package:http/http.dart:69:5) E/flutter (26845): #6 _SignupScreenState.createUser (package:socialmediaproject/screens/signup_screen.dart:25:42) E/flutter (26845): #7 _SignupScreenState.build.<anonymous closure>.<anonymous closure> (package:socialmediaproject/screens/signup_screen.dart:152:42) E/flutter (26845): #8 State.setState (package:flutter/src/widgets/framework.dart:1148:30) E/flutter (26845): #9 _SignupScreenState.build.<anonymous closure> (package:socialmediaproject/screens/signup_screen.dart:151:27) E/flutter (26845): #10 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:706:14) E/flutter (26845): #11 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:789:36) E/flutter (26845): #12 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24) E/flutter (26845): #13 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:486:11) E/flutter (26845): #14 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:264:5) E/flutter (26845): #15 BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:236:7) E/flutter (26845): #16 GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27) E/flutter (26845): #17 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:222:20) E/flutter (26845): #18 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22) E/flutter (26845): #19 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7) E/flutter (26845): #20 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7) E/flutter (26845): #21 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7) E/flutter (26845): #22 _rootRunUnary (dart:async/zone.dart:1138:13) E/flutter (26845): #23 _CustomZone.runUnary (dart:async/zone.dart:1031:19) E/flutter (26845): #24 _CustomZone.runUnaryGuarded (dart:async/zone.dart:933:7) E/flutter (26845): #25 _invoke1 (dart:ui/hooks.dart:273:10) E/flutter (26845): #26 _dispatchPointerDataPacket (dart:ui/hooks.dart:182:5) E/flutter (26845): -
ModuleNotFoundError: No module named 'moviepy' in Django although installed
I have installed MoviePy within the virtual environment like this: (env)$: sudo pip install ez_setup Requirement already satisfied: ez_setup in /usr/local/lib/python2.7/dist-packages (env)$: sudo pip install moviepy Requirement already satisfied: moviepy in /usr/local/lib/python2.7/dist-packages Requirement already satisfied: decorator<5.0,>=4.0.2 in /usr/local/lib/python2.7/dist-packages (from moviepy) Requirement already satisfied: numpy in /usr/local/lib/python2.7/dist-packages (from moviepy) Requirement already satisfied: proglog<=1.0.0 in /usr/local/lib/python2.7/dist-packages (from moviepy) Requirement already satisfied: requests<3.0,>=2.8.1 in /home/ac3l1k/.local/lib/python2.7/site-packages (from moviepy) Requirement already satisfied: tqdm<5.0,>=4.11.2 in /usr/local/lib/python2.7/dist-packages (from moviepy) Requirement already satisfied: imageio<2.5,>=2.0 in /usr/local/lib/python2.7/dist-packages (from moviepy) Requirement already satisfied: idna<2.8,>=2.5 in /home/ac3l1k/.local/lib/python2.7/site-packages (from requests<3.0,>=2.8.1->moviepy) Requirement already satisfied: urllib3<1.25,>=1.21.1 in /home/ac3l1k/.local/lib/python2.7/site-packages (from requests<3.0,>=2.8.1->moviepy) Requirement already satisfied: certifi>=2017.4.17 in /home/ac3l1k/.local/lib/python2.7/site-packages (from requests<3.0,>=2.8.1->moviepy) Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /home/ac3l1k/.local/lib/python2.7/site-packages (from requests<3.0,>=2.8.1->moviepy) Requirement already satisfied: enum34 in /home/ac3l1k/.local/lib/python2.7/site-packages (from imageio<2.5,>=2.0->moviepy) Requirement already satisfied: futures in /usr/local/lib/python2.7/dist-packages (from imageio<2.5,>=2.0->moviepy) Requirement already satisfied: pillow in /usr/lib/python2.7/dist-packages (from imageio<2.5,>=2.0->moviepy) The installations are successful as you can see in the outputs above. But when I use moviepy in my models.py of my Django project, then I get: ModuleNotFoundError: No module named 'moviepy' The command pip freeze gives me the following list of installed modules: cffi==1.13.2 cryptography==2.8 dj-database-url==0.5.0 Django==2.2.7 django-extensions==2.2.5 django-filter==2.2.0 django-secure==1.0.1 django-sslserver==0.22 djangorestframework==3.10.3 ez-setup==0.9 Pillow==6.2.1 pkg-resources==0.0.0 pycparser==2.19 pyOpenSSL==19.1.0 pytz==2019.3 six==1.13.0 sqlparse==0.3.0 The moviepy module … -
Djanog loging page [closed]
Hallo, the dropdown list cannot be opened on the login page. I used: the Django authentication system django.contrib.auth, bootstrap-4.2.1.min.js jquery-3.3.1.min.js popper-1.12.9.min.js <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle active" href="#" id="dropdown-projects" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">{% trans 'base.projects' %}</a> <div class="dropdown-menu" aria-labelledby="dropdown-user"> <a class="dropdown-item" href="{% url 'projects:index' %}">{% trans 'base.overview' %}</a> <span class="dropdown-item">------------</span> {% for project in projects %} <a class="dropdown-item" href="{% url 'projects:detail' project.id %}">{{project.project_number}} {{project.unmod_name}}</a> {% endfor %} </div> </li> -
Google Cloud Storage Signed URL with Google App Engine using Django with Search Filters
I have the following model with relevant fields. When I create an api with all the model fields returning correctly, I need to add a dynamic field for the "signed url" for providing access for a particular authorized user along with actual google storage url : class VideoEntityFilterSerializer(serializers.ModelSerializer): class Meta: model = Entity fields = ('uuid', 'description', 'url', 'segment_start', 'segment_end', 'confidence', 'username', 'userid', 'videouuid', 'videotitle') class VideoEntityList(generics.ListAPIView): model = Entity serializer_class = VideoEntityFilterSerializer queryset = Entity.objects.all() filter_backends = [filters.SearchFilter] search_fields = ['videouuid', ] pagination_class = StandardResultsSetPagination How can I achieve this ? -
Intermediate data - Class methods vs functions [closed]
After my app receives data from an external source a lot of functions are called on the data. This to make normalizations, calculations etc. before the data is saved in a Model. What is best practice? To use functions to transform the data e.g. intermed = normalize(intermed intermed = calculate_totals(intermed) To create a special Class with methods e.g. intermed = IntermediateClass() intermed.title.normalize() To create intermediate fields in the ModelClass, that don't get saved to the db. mymodel.calculate_temp_totals() mymodel.save() Any ideas. Thanks in advance. -
CORS headers working on one browser, and not another
I can't work out why I'm getting a CORS failure on one browser and not another. Backend : Django with rest apis & CORS - localhost:8000 Frontend : Elm running on a python simple HTTP server - localhost:1234 Machine 1: Works fine with both Vivaldi and Chrome. But don't see the headers in the inspection Content-Length: 435 Content-type: text/html Date: Wed, 25 Mar 2020 11:41:31 GMT Last-Modified: Tue, 24 Mar 2020 19:48:48 GMT Server: SimpleHTTP/0.6 Python/3.8.1 Machine 2: Works fine with chrome, but Vivaldi gets a CORS error: Access to XMLHttpRequest at 'http://localhost:8000/api/adventures/1' from origin 'http://localhost:1234' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Chrome inspection response headers: Access-Control-Allow-Origin: * Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS Content-Length: 157 Content-Type: application/json Date: Wed, 25 Mar 2020 12:11:00 GMT Server: WSGIServer/0.2 CPython/3.8.0 Vary: Accept, Origin, Cookie X-Content-Type-Options: nosniff X-Frame-Options: DENY Which I found odd - different server!! (the django server???) - so I shut down all python processes (virtual envs, the current server), then started them up again. Then I see it's the same as the other headers, with no cors info, but still works! Content-Length: 435 Content-type: text/html Date: Wed, 25 Mar 2020 … -
React Native (Android) with Django Rest Framework - TypeError: Network Request Failed
Trying to set up fetch request for the first time in react native, but I end up with an error screen. I have already made sure my server is running on my inet address but the device just wouldn't send the fetch request. The Django server is running on 192.168.0.10 (port 8000) which is my inet address. Also, I am using an externally connected Android device (via USB). Registration.js componentDidMount() { fetch('http://192.168.0.10:8000/api/registration1/', { // fetch('http://10.0.2.2:8000/api/registration1/', { method: 'GET', // or 'PUT' headers: { 'Content-Type': 'application/json', Accept: 'application/json', }, }) .then(response => { console.log('I AM IN'); return response.json(); }) .then(data => { console.log('Success:', data); }) .catch(error => { console.error('Error:', error); }); console.log(' COMPONENT DID MOUNT OVER'); } I have enabled http support in my android.manifest file. Android.manifest <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.phone_app"> <uses-permission android:name="android.permission.INTERNET" /> <application android:name=".MainApplication" android:label="@string/app_name" android:icon="@mipmap/ic_launcher" android:roundIcon="@mipmap/ic_launcher_round" android:allowBackup="false" android:usesCleartextTraffic="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity" android:label="@string/app_name" android:configChanges="keyboard|keyboardHidden|orientation|screenSize" android:windowSoftInputMode="adjustResize"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" /> </application> </manifest> Here's the error I get: -
Wagtail-API: django-filter (2.2.0) doesn't seem to work with the api
I tried to get django-filter running with the wagtail-api but it doesn't seem to work. Maybe i did something wrong. Thanks in advance for your help. This my class i used for api/v2: class MyPageClass(PagesAPIEndpoint): model = HomePage PagesAPIEndpoint.filter_backends = (filters.DjangoFilterBackend,) PagesAPIEndpoint.filterset_fields = { 'title': ['icontains'], 'id': ['exact'], } class Meta: fields = ( 'title', 'id', 'tags', ) I tried also this version for the api/v2: class MyPageClass(PagesAPIEndpoint): model = HomePage filter_backends = (filters.DjangoFilterBackend,) filterset_fields = { 'title': ['icontains'], 'id': ['exact'], } class Meta: fields = ( 'title', 'id', 'tags', ) And this is my code for my custom endpoint for the pages: class WebPageListAPIView(ListAPIView): queryset = WebPage.objects.all() serializer_class = PagesSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_fields = { 'profiles': ['exact'], 'tags': ['exact'], } Normally if i use django-filter it will show up the filter button in the api browser but not with the PagesAPIEndpoint. Image without Filter Button based on PagesAPIEndpoint Image with Filter Button based on my own Endpoint -
Python Django safe increment / decrement
I want to build an api for a article amount management system for my store. With this I need to safely increment or decrement the amount of an article and log it with the user who executed it to the database. It should look like this: from django.db import models from django.contrib.auth.models import User class Article(models.Model): name = models.CharField(...) amount_in_store = models.IntegerField(...) ... class ArticleAmountChange(models.Model): article = mdoels.ForeignKey(Article, ...) amount_change = models.IntegerField(...) user = models.ForeignKey(User, ...) ... But how can I guarantee the amount_in_store will always be the sum of all amount_changes for this article and still have a great performance? So I don't want to query over all ArticleAmountChange and sum the amount_changes because after some time of use there will be thousands of ArticleAmountChanges. Can you help me? -
I do not know how to make email confirmation for DRF and JWT
I stack with my challange. I am making DRF registration with JWT, and now need to confirm it with email. I do not have any idea, how to realize it -
Django: reverse_lazy() with a generic view
I have two generic views (CreateView and DetailView). In my CreateView after saving my form I want redirect to the DetailView to display my newly created object. But an error occured : Reverse for 'questions.views.DisplayQuestions' not found. 'questions.views.DisplayQuestions' is not a valid view function or pattern name. How can I call my DetailView with reverse_lazy ? .views: class DisplayQuestions(ListView): model = Question context_object_name = "all_questions" template_name = "questions/home.html" def get_queryset(self): return Question.objects.order_by(self.kwargs['display_type']) @method_decorator(login_required, name='dispatch') class CreateQuestion(CreateView): model = Question template_name = 'questions/nouveau.html' form_class = QuestionForm def get_success_url(self): return reverse_lazy(DisplayQuestion) # <-- This doesn't work !!! def form_valid(self, form): self.object = form.save(commit=False) self.object.profil = self.request.user.profil self.object = form.save() return HttpResponseRedirect(self.get_success_url()) .urls: urlpatterns = [ url(r'^nouveau$', views.CreateQuestion.as_view()), url(r'(?P<display_type>\w+)', views.DisplayQuestions.as_view()),] .forms: class QuestionForm(forms.ModelForm): class Meta: model = Question fields = ('question','categorie',) ``` -
Django Dev Server Module Whitenoise Not found
I'm trying to use Whitenoise in dev as suggested per the docs, but when I run the django dev server with the whitenoise module loaded in INSTALLED_APPS and MIDDLEWARE, as such: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth.backends.ModelBackend', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', ...other MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Yet when I make sure the module is installed using pip install whitenose, I get the error: ModuleNotFoundError: No module named 'whitenoise' Yet when I try pip install whitenoise I get: Requirement already satisfied: whitenoise in /Users/USERNAME/Development/venv/yourdash/lib/python3.7/site-packages (5.0.1) So I'm forced to run during dev without whitenoise. But because of this, I do run into issues as a result of different static files between dev/prod. So how can I ensure whitenoise will run while using the django dev server?