Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Apple SocialLoginView requires something called `id_token`?
My view: I am using the following view for apple 0auth. And I used very similar view for facebook and google auth, and they worked just fine. class AppleLogin(SocialLoginView): adapter_class = AppleOAuth2Adapter callback_url = 'https://www.My_FE_website.com/' client_class = AppleOAuth2Client # client_class = OAuth2Client But in this when the user make a post request to this view, it returns the following err. Error: File "/Users/apple/.local/share/virtualenvs/backend-kawWLPL_/lib/python3.9/site-packages/allauth/socialaccount/providers/apple/views.py", line 92, in parse_token identity_data = self.get_verified_identity_data(data["id_token"]) KeyError: 'id_token' -
Can't delete old objects after adding new one in django
old_objs = MyModel.objects.filter(user=request.user) MyModel.objects.create(user=request.user,...)# I must have to keep this line here. Because the new object is related to old objects old_objs.delete() I've a Model named MyModel. I filtered some old objects and keep them in a variable, then add a new object. Now if I want to delete old_objs, it delete all the objects including new object. I want to keep the new object and delete old objects. -
Listening onchange events on a dropdown to update a chart data list
I'm trying to figure it out how can I create an onchange event to listen to the value from the dropdown, so the chart will change it values depending on that id, for that I have the following elements: In views.py: def html(request, filename): #Data for the graph id = list(Device.objects.values_list('patientId', flat=True).distinct()) labels = list(Device.objects.values_list('hour', flat=True)) glucose_data = list(Device.objects.values_list('glucoseValue', flat=True)) data = glucose_data formatted_data = select_formatted_date(labels) lastPatientData = Device.objects.filter(patientId = id[-1]) #the last element added hourArray = [] glucoseArray = [] for item in lastPatientData: lastPatientHour = Device._meta.get_field('hour') lastPatientGlucose = Device._meta.get_field('glucoseValue') formattedHour = lastPatientHour.value_from_object(item) frt_hour = formattedHour.strftime('%Y-%m-%d %H:%M:%S') formattedGlucose = lastPatientGlucose.value_from_object(item) hourArray.append(frt_hour) glucoseArray.append(formattedGlucose) device_list = list(Device.objects.all()) for device in device_list: print(device) #f = DateRangeForm(request.POST) context = {"filename": filename, "collapse": "", "hourArray":hourArray, "glucoseArray": glucoseArray, "patientId": id, "dataSelection": formatted_data, "deviceList": device_list, "labels": json.dumps(labels, default=str), "data": json.dumps(data) } return render(request, f"{filename}.html", context=context) In forms.py, I have this, but I really don't know what to do with this data: from django import forms idsList = forms.ModelChoiceField(queryset = Device.objects.values_list('patientIId'),widget = forms.Select(attrs = {'onchange' : "myFunction()"})) my model is: class Device (models.Model): patientId = models.IntegerField(unique=True) deviceId = models.CharField(unique=True,max_length=100) hour = models.DateTimeField() type = models.IntegerField() glucoseValue = models.IntegerField() And in the index.html, I have the following(in data … -
How to set API keys for non-authentication models in Django?
I am developing an inventory tracker for stores, where each store can have multiple outlets. I am using Django with the Django Rest Framework. Each store is an authentication model. As such, it can manage its respective outlets and settings by logging into the system. In the current state, each outlet uses the same token of the store model (provided by DRF) to connect and update inventory as sales are made. In my opinion, this creates a security vulnerability. For example, if a store has hundreds of outlets and one of the outlets' API key is exposed, all the outlets are exposed. Is there some way to generate an authentication token for each outlet? This way the stores can manage and, if required, renew the token of each outlet. Also, how would I validate this token in the DRF views and/or serializer? -
DRF: Creating mixin using different serializers & objects
I have two APIView classes with almost similar behaviour (and code). Different are only serializers and models object (Favorite & FavoriteSerializer for first class and PurchaseList and PurchaseListSerializer for second). As far as I understand it is a perfect usecase for mixin, according to DRF docs ([DRF: Creating custom mixins] 1https://www.django-rest-framework.org/api-guide/generic-views/). Unfortunately, I'm struggling with how to define mixin without the definition of serializer & obj in it. class FavoriteViewSet(APIView): def get(self, request, recipe_id): user = request.user.id data = {"user": user, "recipe": recipe_id} serializer = FavoriteSerializer( data=data, context={"request": request}, ) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status.HTTP_201_CREATED) def delete(self, request, recipe_id): user = request.user favorite_recipe = get_object_or_404( Favorite, user=user, recipe__id=recipe_id ) favorite_recipe.delete() return Response( "Рецепт удален из избранного", status.HTTP_204_NO_CONTENT ) class PurchaseListView(APIView): def get(self, request, recipe_id): user = request.user.id data = {"user": user, "recipe": recipe_id} serializer = PurchaseListSerializer( data=data, context={"request": request} ) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status.HTTP_201_CREATED) def delete(self, request, recipe_id): user = request.user purchase_list_recipe = get_object_or_404( PurchaseList, user=user, recipe__id=recipe_id ) purchase_list_recipe.delete() return Response( "Рецепт удален из списка покупок", status.HTTP_204_NO_CONTENT ) -
Having conflicting groups in Django Group Model
I have different groups in my Django Groups: for example: named Moderator and Reviewer. What I want to do is, if a user is in Moderator Group, the user shouldn't be in Reviewer Group. Now, I know that I can do this in different places like save_model() in ModelAdmin, etc. However, I want to prevent the assignment option in the Django Admin panel where you can assign users the groups and permissions as in below group selection. -
ImportError: cannot import name 'url' from 'django.conf.urls' django-rest-auth
error : from django.conf.urls import url ImportError: cannot import name 'url' from 'django.conf.urls' -version Django==4.0.1 django-rest-auth==0.9.5 Pl help me.Thank you in advance url.py # Core Django imports from django.contrib import admin from django.urls import path, include from django.urls import re_path,include # from django.conf.urls import url,include from django.conf import settings # Rest framework imports from rest_framework import permissions # Simple JWT imports from drf_yasg.views import get_schema_view from drf_yasg import openapi schema_view = get_schema_view( openapi.Info( title="Heathy Living Guide API", default_version='v1', description="Heathy Living Guide", ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = ( path('admin/', admin.site.urls), path('api/authentication/', include('apps.authentication.urls'),authentication'), path('api/users/', include('apps.users.urls'), name='users'), path('rest-auth/', include('rest_auth.urls')), # re_path(r'^rest-auth/', include('rest_auth.urls')) ) urlpatterns += [ path('api/swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path('api/redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc') ] -
Optimize Django tests with preloaded database
I am trying to reduce my CI usage and make my code cleaner by pre-loading my test database using a custom class. I had multiple files/classes that looked like this: class TestSomething(TestCase): def setUp(self): User.objects.create(...) def test_something(self): pass I converted them into: class TestSomething(PreloadedTestCase): def test_something(self): pass with a common PreloadedTestCase class: class TestSomething(TestCase): def setUp(self): User.objects.create(...) This does make the code cleaner and removes a lot of duplicate lines, but it seems to increase the CI execution time. Is PreloadedTestCase.setUp() run multiple times? If so, how can I have a common class that is run only once against the database? I looked into fixtures but it is only populating the database, I would have to query it to access my objects in the tests. -
What's the default value for a DecimalField in Django?
I'm adding a new DecimalField to my model, what value will it have by default in the database (if I don't specify the default explicitly)? amount = models.DecimalField(max_digits=15, decimal_places=3) I'm expecting it will be either NULL or 0.0 (or None or Decimal(0.000) in python), but which? Couldn't find this mentioned in the docs: https://docs.djangoproject.com/en/2.2/ref/models/fields/#decimalfield I'm using Django 2.2, but expect this is consistent across versions. -
'builtin_function_or_method' object has no attribute 'split' in django [closed]
def index(request): product = () catProds = Product.objects.values(category) cats = {items['category'] for items in catProds} for cat in cats: prod = Product.objects.filter(category=cat) product.append(prod) params = {'product':product} return render(request, 'shop/index.html', params) -
Django 4 and Unittest loader
We use Django for an online webshop, and want to upgrade to Django 4. However, since upgrading on a test branch, we have a problem, that I will highlight here. We serve two different markets, lets call them Market A and B :) Since these two markets can have different functionalities, our INSTALLED_APPS gets populated like so: MARKET_SPECIFIC_APPS = { MARKET_A: [ 'market_a.apps.MarketAConfig', 'payment_system_a.apps.PaymentSystemAConfig' ], MARKET_B: [ 'market_b.apps.MarketBConfig', 'payment_system_b.apps.PaymentSystemBConfig', ], } if MARKET in MARKET_SPECIFIC_APPS: # If there is a market-specific app, add it to INSTALLED_APPS INSTALLED_APPS += MARKET_SPECIFIC_APPS[MARKET] However, when running MARKET specific tests for each market, only MARKET_A passes. MARKET_B now throws an error, since upgrading from Django 3.2 to Django 4 RuntimeError: Model class payment_system_b.models.payment.Payment doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Meaning, this test is still run, and the test runner includes it in INSTALLED_APPS even tho it shouldnt. Is there any change from the Django 4 changelog im missing about this? Running these market-specific tests was working fine before upgrading to Django 4 -
What does set -e do in Nginx?
This is my code, I don't understand it completely. I would really appreciate your help #!/bin/sh set -e envsubst < /etc/nginx/default.conf.tpl > /etc/nginx/conf.d/default.conf nginx -g 'daemon off;' -
How can I resolve this issue with installing django2-semantic-ui=1.2.2 using pip?
I am trying to locally run an existing django application and install django2-semantic-ui==1.2.2 using the command: pip install django-semantic-ui=1.2.2. Here is the error I am getting: Using cached django2_semantic_ui-1.2.2.tar.gz (8.1 kB) ERROR: Command errored out with exit status 1: command: 'C:\Users\aakar\OneDrive\Documents\Data4Good\data4good-django\myenv\Scripts\python.exe' -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\aakar\\AppData\\Local\\Temp\\pip-install-fti4wdiz\\django2-semantic-ui_86580566b774418c94ae3e3de149c712\\setup.py'"'"'; __file__='"'"'C:\\Users\\aakar\\AppData\\Local\\Temp\\pip-install-fti4wdiz\\django2-semantic-ui_86580566b774418c94ae3e3de149c712\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\aakar\AppData\Local\Temp\pip-pip-egg-info-u198istg' cwd: C:\Users\aakar\AppData\Local\Temp\pip-install-fti4wdiz\django2-semantic-ui_86580566b774418c94ae3e3de149c712\ Complete output (7 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\aakar\AppData\Local\Temp\pip-install-fti4wdiz\django2-semantic-ui_86580566b774418c94ae3e3de149c712\setup.py", line 5, in <module> long_description = fh.read() File "c:\python3\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 919: character maps to <undefined> ---------------------------------------- WARNING: Discarding https://files.pythonhosted.org/packages/a1/76/e57ee8bf33259f832ae9f5c8d4d24a701516389f633efa37627922b6706a/django2_semantic_ui-1.2.2.tar.gz#sha256=a5efe89908c11e231dcea7cad249fd7bf629f7189d5621cd0d3bc82d154a9676 (from https://pypi.org/simple/django2-semantic-ui/) (requires-python:>=3.*). Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. ERROR: Could not find a version that satisfies the requirement django2-semantic-ui==1.2.2 (from versions: 1.0.0b0, 1.0.0b1, 1.0.0b3, 1.0.0b4, 1.0.0, 1.0.1b0, 1.0.1, 1.1.0b0, 1.1.0, 1.1.1, 1.1.2, 1.2.0b0, 1.2.0b1, 1.2.0b2, 1.2.0b3, 1.2.0, 1.2.1b0, 1.2.1b1, 1.2.1b2, 1.2.1b3, 1.2.1b4, 1.2.1b5, 1.2.1b6, 1.2.1, 1.2.2b0, 1.2.2b1, 1.2.2) ERROR: No matching distribution found for django2-semantic-ui==1.2.2 All the other packages from requirements.txt were successfully installed. … -
Get input from front-end of the website and generate file corresponding in python
i am creating an website in which the users are going to input some form data and from the form data that the user given i will generate a excel file based on it using python, my python script is already done, but i dont know how i can connect it to the front-end / javascript so the i can pass the data to my python file script download the excel file to the user, i was looking at some django / flask tutorials but haven't found nothing that solves my problem, thanks for any reply in advance -
After intregation of django and reactjs blank page is rendered instead of component
I am working on full stack website I tried to integrate django with reactjs and was successful, but the problem is that it has returned a blank page instead of the reactjs component. this is output this is index.html inside build folder this is index.js from src -
'collections.OrderedDict' object has no attribute 'id'
My serializers: class SpeakerSerializer(serializers.ModelSerializer): class Meta: model = Speaker fields = ['id',...] class CourseSerializer(serializers.ModelSerializer): .... author = SpeakerSerializer(many=False, required=True) .... class Meta: model = Course fields = ['id', 'author',...] def create(self, validated_data): ... author = validated_data.get('author') ... course, _ = Course.objects.create(author=author.id, **validated_data) course.save() I'm sending POST request to this serializer and getting this response: Help please! course, _ = Course.objects.create(author=author.id, **validated_data) AttributeError: 'collections.OrderedDict' object has no attribute 'id' -
Convert django request.body (bytes) into json
I have a class based view in which a put function and trying to get request.body into json. from django.views import View import json class StudentView(View): def put(self, request): body = request.body #b'name=Arpita+kumari+Verma&roll=109&city=USA' json_body = json.loads(body) # JSONError 'expecting dict values but given bytes object' # I want something like this # { # 'name':'Arpita kumari Verma', # 'roll':'109, # 'city':'USA', # } json_dumped_data = json.dumps(json_body) return HttpResponse(json_dumped_data, content_type="application/json") -
Django template won't respond to css file , worked briefly yesterday
It is exactly how it sounds. My main goal is to make the css file work with django template so I can design my templates. Yesterday I tried and initially my folder structure was wrong. I placed static folder in myapp folder. Didn't work. I tried putting it in templates folder. It only worked when I had 2 static folders both in myapp and templates folder. Realized it isn't a working solution. I placed a single static folder with a css file in it in mysite folder, at the same level with myapp folder and everything seemed to work. Satisfied I left at that. Today I came back to it and it stopped working. It seems to be frozen. Not responding to the new codes. Old colors are showing but new colors aren't, which is odd. Tried changing the old colors, it won't change. Literally my css file has a class name .intro where I changed the color from purple to red, my template still showing purple which I set yesterday. My template shows no error and all the texts and divs I am adding are updating with no issue.Kind of lost where I may have gone wrong. Certainly don't … -
How to open a modal when moving a page
The currently implemented code shows the modal when clicking the button. However, I would like the modal to be displayed when moving to the main page after logging in. (using Django) JavaScript's window.open is not what I want because it prints a new window. I want the modal window to be displayed automatically when the main page is reached upon successful login. Is there a way? [index.html] <div class="modal fade" id="quality" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Quality</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body row"> <div class="col-sm-12"> {% include 'pages/quality_POPUP.html' %} </div> </div> </div> </div> <button type="button" class="btn pull-right" data-toggle="modal" data-target="#quality">POP UP</button> -
Get sales totals per account using model property in django
Okay I thought I can google my way out of this but I am stuck. Desired results are Account_name Total local sales 1802.50 int sales 0.00 from my models class Account(models.Model): account_number = models.IntegerField(unique=True, null=True, blank=True, default=None) account_name = models.CharField(max_length=200, null=True, blank=True, unique=True) class Sales(models.Model): account_name = models.ForeignKey(Account, on_delete=models.CASCADE, related_name='incomes') amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) def sales_total(self): sales_total = Income.objects.values('account_name').order_by('account_name').annotate(sales_total=Sum('sales__total')) return sales_total so in my template when I do {% for account in accounts %} <tr> <td>{{ account.sales_total }}</td> </tr> {% endfor %} I get Account_name Total local sales <QuerySet [{'account_name': 3, 'sales_total': Decimal('1802.5')}]> int sales <QuerySet [{'account_name': 3, 'sales_total': Decimal('1802.5')}]> -
cannot import name 'Channel' from 'channels'
I am using python version==3.8.10 and Django==2.2 and channels==3.0.4 . I am getting error from channels import Channel ImportError: cannot import name 'Channel' from 'channels' (/home/kritik/py38_djanngo2.2_new/lib/python3.8/site-packages/channels/init.py) Can anyone help me on this ? -
after login having error 'Anonymous User' object has no attribute '_meta'
I m new in Django m creating a signup form if submit the form the data is stored success fully but I m having a error in redirection or login view.py from Blog.forms import SignupForm from django.contrib.auth import authenticate,login from django.http import HttpResponseRedirect def signup_form(request): form=SignupForm() if request.method=='POST': form=SignupForm(request.POST) if form.is_valid(): user=form.save() user.refresh_from_db() # load the profile instance created by the signal user.save() raw_password = form.cleaned_data.get('password') user = authenticate(username=user.username, password=raw_password) login(request, user) return HttpResponseRedirect('home/') return render(request,'blog/signup.html',{'form':form}) redirecting in setting file setting.py LOGIN_REDIRECT='home/' LOGOUT_REDIRECT_URL='/logout' my form file look like that forms.py from django.contrib.auth.models import User class SignupForm(ModelForm): class Meta: model=User fields=['username','first_name','last_name','email','password'] labels={'username':' Enter User Name','password':' Enter Password','email':'Enter Email','first_name':'Enter First Name','last_name':'Enter Last Name'} widgets={'password':forms.PasswordInput,'username':forms.TextInput(attrs={'class':'form-control','placeholder':'Enter Your User Name'}), 'password':forms.PasswordInput(attrs={'class':'form-control','placeholder':'Enter Your Password'}), 'email':forms.EmailInput(attrs={'class':'form-control','placeholder':'Enter Your Email'}), 'first_name':forms.TextInput(attrs={'class':'form-control','placeholder':'Enter First Name'}), 'last_name':forms.TextInput(attrs={'class':'form-control','placeholder':'Enter Last Name'}) } urls.py path('signup/',views.signup_form,name='signup/'), 'Anonymous User' object has no attribute '_meta' -
Django post request field always null
My post request from React frontend to Django backend won't work and I'm not sure why. It always says that "question" is null. I know there to be a question already in the database with a primary key id of 19. Quiz.js: const createAnswerSubmission = () => { submit(questionIndex); const data = { "question": quiz.question[questionIndex].id, "answer_choice": answerSelected[questionIndex], "user": window.localStorage.getItem("user") } const url = "http://localhost:8000/api/submittedanswer/"; axios.post(url, data, {headers: { Authorization: `Token ${window.localStorage.getItem('auth_token')}`, Accept: "application/json", 'Content-Type': 'application/json', } }).then(function (response) { console.log(data) }) .catch(function (error) { console.log(data); alert(error); }); } The console log shows the following: {question: 19, answer_choice: 4, user: '1'} And the request payload shows: {question: 19, answer_choice: 4, user: "1"} Yet I am getting some error: IntegrityError at /api/submittedanswer/ null value in column "question_id" of relation "api_submittedanswer" violates not-null constraint DETAIL: Failing row contains (123, 4, null, 1). models.py: //... class Question(models.Model): pt = models.ForeignKey(PT, on_delete=models.CASCADE, null=True, blank=True, related_name = 'pt') section = models.ForeignKey(Section, on_delete=models.CASCADE, null=True, blank=True, related_name = 'section') question_type = models.CharField(max_length=20) number = models.IntegerField() stimulus = models.CharField(max_length = 1000) question = models.CharField(max_length = 400) answer = models.ManyToManyField(AnswerChoice) correct_answer = models.IntegerField(default = 0) def __str__(self): return "PT " + str(self.pt) + " Section " + str(self.section) + " … -
Use python par file with gunicorn
I want to use a django app packaged as a par file generated via https://github.com/google/subpar with gunicorn. Is this possible? -
Factory boy field not getting expected value
I am using factory boy to generate data for my django application. It is a tennis matches app which has player one and two as shown in below class. Either of it will be a winner which will be store in winner_one field. I am getting some third player name in this field instead of player one or two. That player is also present in table. Please advise what would be the best way to fix this? class MatchFactory(factory.django.DjangoModelFactory): class Meta: model = Match player_one = factory.SubFactory(UserFactory) player_two = factory.SubFactory(UserFactory) league = factory.Iterator(League.objects.all()) type = fuzzy.FuzzyChoice(Match.MATCH_CHOICES, getter=lambda c: c[0]) winner_one = random.choice([player_one, player_two]) start_date = fuzzy.FuzzyNaiveDateTime( datetime.today() + relativedelta(months=1), datetime.today() + relativedelta(months=3) ) end_date = start_date