Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Need fo get the domain from which the user landing to my website?
I am sharing one url link in different social media platforms. I need to find from which domain the user has landed to my website page. is there any possible way for finding the base url of social media plotforms. Thanks in advance. -
python-social-auth return drf token as a parameter
I am using django rest framework's token authentication for my clients. I have also implemented social auth using python-social-auth in my project. However, once the user has logged in (or signed up) using python social auth, I want to redirect to the next url along with the drf token as a parameter. So, if I make a request like this from the frontend: localhost:8000/auth/login/github?next=localhost:3000 then the backend should redirect to the following url localhost:3000?token=USER_TOKEN_HERE the USER_TOKEN would be the drf token for the user who was created or logged in. How can this be implemented in python-social-auth? I couldn't find any good references. Thanks a lot! -
(1048, "Column 'user_id' cannot be null") with Django DRF
I wrote code to create new users via POST and DRF (Django Rest Framework) successfully and I can obtain token correctly, however when I try to POST (via DRF) to fill Profile linked to that user I get (1048, "Column 'user_id' cannot be null") This is snippets of my code: for serializers: class UserSerializer(ModelSerializer): class Meta: model = User fields = ('username','email','first_name','last_name','password') def create(self, *args, **kwargs): user = super().create(*args, **kwargs) p = user.password user.set_password(p) user.save() return user def update(self, *args, **kwargs): user = super().update(*args, **kwargs) p = user.password user.set_password(p) user.save() return user class ProfileSerializer(ModelSerializer): class Meta: model = Profile fields = ('bio','birth_date','location','country') def create(self, *args, **kwargs): profile = super().create(*args, **kwargs) profile.save() return profile def update(self, *args, **kwargs): profile = super().update(*args, **kwargs) profile.save() return profile and for views: class ProfileViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ permission_classes = IsAuthenticated, serializer_class = ProfileSerializer queryset = Profile.objects.all() class UserViewSet(viewsets.GenericViewSet,mixins.CreateModelMixin,): """ API endpoint that allows users to be viewed or edited. """ #permission_classes= (IsAdminUser,) serializer_class = UserSerializer queryset = User.objects.all().order_by('-date_joined') and for models: @receiver(post_save, sender = settings.AUTH_USER_MODEL) def create_auth_token(sender,instance=None,created=False, **kwargs): if created: Token.objects.create(user=instance) class Country(models.Model): iso = models.CharField(max_length = 2,unique = True) name = models.CharField(max_length = 250) iso3 … -
How to have a views function be called when the respective template is loaded?
So far, on my entirely blank django project I have created a simple template that looks as following. test.html: {% block includes %} {{ mytext }} {% endblock includes %} to my views.py I added the following function: from django.template.response import TemplateResponse def testdex(requset, template_name="news.html"): args = {} text = "hello world" args['mytext'] = text return TemplateResponse(request, template_name, args) My settings.py includes the following: TEMPLATE_DIR = os.path.join(BASE_DIR, "core/templates") TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] However, loading the template only shows me a blank page. Is there something I am missing? -
Validation on filed in signupform with django Alluth
i have a custom signupform created for Djangp Alluth. Everyghing works well. But i want to ad a validation to the form but i cant get the validation to work. I want a lookup on the value Pid. This value is unique so if there already is a user registrered the form validation error should pop up. Any tips or ideas? class SignupForm(SignupForm): def __init__(self, *args, **kwargs): # Call the init of the parent class super().__init__(*args, **kwargs) # Remove autofocus because it is in the wrong place self.fields[_("first_name")] = forms.CharField(required=True) self.fields[_("last_name")] = forms.CharField(required=True) self.fields[_("pid")] = SEPersonalIdentityNumberField(required=True) # Put in custom signup logic def custom_signup(self, request, user): # Set the user's type from th form reponse user.profile.pid = self.cleaned_data[_("pid")] user.first_name = self.cleaned_data[_("first_name")] user.last_name = self.cleaned_data[_("last_name")] # Save the user's type to their database record user.save() -
Custom authentication raises 400 instead of 403
I have written a custom authentication that should return 403 incase of unauthorised login (i.e. when user exists but is not allowed to login). Here is my code: def authenticate(self, request, username=None, password=None): # do something if not results: if not user.has_perm('some_permission'): raise PermissionDenied("Insufficient permission") return None In settings.py I have added this custom authentication before ModelBackend. However, I notice that 400 is returned instead of 403. How can I fix this? Thanks in advance -
Python-Django import csv to Jupiter Note local
Hi I create in Django app that export csv file, next I import this to Jupiter, everything works when my Django published on line, but cant import this when my project run local like http://127.0.0.1:8000/ import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import io import requests import urllib.request as urllib2 df = pd.read_csv('http://127.0.0.1:8000/covid/covid.csv/') df.head(100) ConnectionRefusedError Traceback (most recent call last) /usr/lib/python3.7/urllib/request.py in do_open(self, http_class, req, **http_conn_args) 1349 h.request(req.get_method(), req.selector, req.data, headers, -> 1350 encode_chunked=req.has_header('Transfer-encoding')) 1351 except OSError as err: # timeout error 18 frames ConnectionRefusedError: [Errno 111] Connection refused During handling of the above exception, another exception occurred: URLError Traceback (most recent call last) /usr/lib/python3.7/urllib/request.py in do_open(self, http_class, req, **http_conn_args) 1350 encode_chunked=req.has_header('Transfer-encoding')) 1351 except OSError as err: # timeout error -> 1352 raise URLError(err) 1353 r = h.getresponse() 1354 except: URLError: <urlopen error [Errno 111] Connection refused> Any ideas? -
Django Chart with chart.js
I working on the project where I need chart. I tries to use chart.js but something went wrong. I have list of indicators with target and progress for each. I want to display this list of indicators and their corresponding target and progress. Below is the code I am using and the output. How can I modify the codes to display the full chart with bars. def chart(request): dataset = Indicators.objects.values('indicator','target','progress') indicator = list() target = list() progress = list() for entry in dataset: indicator.append(entry['indicator']) target.append(entry['target']) progress.append(entry['progress']) target_series = { 'name': 'Target', 'data': target, 'color': 'blue', } progress_series = { 'name': 'Progress', 'data': progress, 'color': 'red' } chart = { 'chart': {'type': 'column'}, 'title': {'text': 'Indicator Analysis'}, 'xAxis': {'categories': indicator}, 'series': [target_series,progress_series] } dump = json.dumps(chart) return render(request,'staff/analysis.html',{"chart":dump}) Output of the above codes -
SocialApp matching query does not exist error with an actual domain
I'm trying to add a Google Login to my Django application by using the django-allauth library. It worked fine on my localhost. However, when I try to test it with a domain, it gives SocialApp matching query does not exist error. I have tried to change the SITE_ID, also I have tried to delete the site and insert again. When I run the code below, it returns 4. from django.contrib.sites.models import Site Site.objects.get(domain='www.subdomain.mysite.com') So my SITE_ID is 4 and I have already added the site to the socialapp_sites table. How can I fix this issue? -
Django - How to handle DateTime field as primary key
I have a class with a DateTime as primary key defined class GrowEntry(models.Model): dateTime = models.DateTimeField(primary_key=True, unique=True, null=False, blank=False) airTemperature = models.FloatField(null=True, blank=True) airHumidity = models.FloatField(null=True, blank=True) def __str__(self): return "time {datetime}T:{airtemp}H:{airHumidity}".format(datetime = self.dateTime, airtemp = self.airTemperature, airHumidity = self.airHumidity) def get_absolute_url(self): return reverse('growentry_edit', kwargs={'pk': self.pk}) def get_formatted_id(self): return self.dateTime.strftime("%Y-%m-%d %H:%M:%S") It works, but in Admin I noticed I can't delete entries because the default method (or action, whatever it is) try to use the DateTime field as parameter with the long date format. To solve this I have overridden the Admin this way @admin.action(description='Delete entry') def delete_model(modeladmin, request, queryset): if not modeladmin.has_delete_permission(request): raise PermissionDenied for obj in queryset: obj.delete() class GrowEntryAdmin(admin.ModelAdmin): list_display = ['dateTime', 'airTemperature', 'airHumidity'] ordering = ['dateTime'] actions = [delete_model] but now I have two actions in the list (the default one and my custom). I think I am missing something. There is some guideline about this? How can I get rid of the default action? -
Django: Subtract the time from two datetime objects
I need to subtract two times and get the number of minutes between them to the nearest minutes. For the scheduled_time, it has become in string and im not able to convert it back to time present_time = timezone.now().time() print(present_time) //output is -> 10:36:01.847822 scheduled_time = datetime.strftime(test.scheduled_date_time, '%H:%M:%S') //output is -> 10:20:52 in string format print(scheduled_time) How do I subtract both and get the result to the nearest minutes? :( -
Django Rest Framework ChoiceField - Do an action on choice change
I have a serializer field of type ChoiceField which I populate with a list of tuple values in a list view. What I want is effectively an event listener for that field, where each time the user updates the field (i.e. chooses a different option), a function is called in the back end. Is this even possible at the moment? Any help is highly appreciated, but as the actual project contains sensitive information, I'll try my best to recreate using a dummy model, view, etc... models.py from django.db import models class MyModel(models.Model): field_one = models.TextField() field_two = models.TextField() serializers.py from models import MyModel from rest_framework import serializers class MyModelSerializer(serializers.ModelSerializer): CHOICES = ( (1, 'choice1'), (2, 'choice2'), ... ) choices_field = serializers.ChoiceField( choices=CHOICES, label="Model choice", default=1, write_only=True ) class Meta: model = MyModel fields = ( "field_one", "field_two", "choices_field", ) # non_personal_fields, extra_kwargs etc... views.py from models import MyModel from rest_framework import mixins, viewsets from serializers import MyModelSerializer class MyModelViewSet( mixins.ListModelMixin, mixins.CreateModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet, ): queryset = MyModel.objects.all() -
Django not redirecting for email verification
Note: I am new to django I have been trying to build an application similar to blog posts. I am using the allauth for social login and auth_views.LoginView.as_view for custom login. When someone creates an account, their email is not verified and I used the @verified_email_required decorator in function based views. Now when I am using class based views, I want the user to be verified to add or update posts.. Below is my code in views.py class LogUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Log fields = ['title', 'content', 'image'] slug_url_kwarg = 'question' slug_field = 'slug' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: if EmailAddress.objects.get(user=self.request.user).verified == True: return True else: print('Not verified') send_email_confirmation(self.request, self.request.user) return redirect('log-detail', question=post.slug) else: return False When the user is not verified. I get the email as per the send_email_confirmation function, but I am not redirected to the log-detail page.. I am still able to update the post without verification. urls.py: from django.urls import path from .views import LogListView, LogDetailView, LogCreateView, LogUpdateView, SolutionDetailView, SolutionsCreateView urlpatterns = [ path('', LogListView.as_view(), name='home'), path('new-question', LogCreateView.as_view(), name='log-create'), path('question/<slug:question>', LogDetailView.as_view(), name='log-detail'), path('question/update/<slug:question>', LogUpdateView.as_view(), name='log-update'), path('add-solution/<slug:question>', SolutionsCreateView.as_view(), name='log-solution-create'), path('solution/<slug:solution>', SolutionDetailView.as_view(), name='log-solution'), ] send_email_confirmation … -
Reverse for 'password_reset' not found. 'password_reset' is not a valid view function or pattern name
I keep running into this error since upgrading to Django 3.2, none of my solutions work, any assistance would be appreciated. from django.contrib.auth.views import ( LoginView, LogoutView, PasswordResetCompleteView, PasswordResetConfirmView, PasswordResetDoneView, PasswordResetView ) from django.urls import include, path, reverse_lazy app_name = 'accounts' urlpatterns = [ path('login/', LoginView.as_view(), name='login'), path('logout/', LogoutView.as_view(), name='logout'), path('password_reset/', PasswordResetView.as_view( success_url=reverse_lazy('accounts:password_reset_done')), name='password_reset'), path('password_reset/done/', PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', PasswordResetConfirmView.as_view( success_url=reverse_lazy('accounts:password_reset_complete')), name='password_reset_confirm'), path('reset/done/', PasswordResetCompleteView.as_view(), name='password_reset_complete') ] -
HOW ADD CUSTOM ATTRIBUTES TO CART.PY IN DJANGO
I am writing an electronic prescribing module that permits a user to select a child user to attach to an order. The system works like a shopping cart, where products are added to the cart. The User is related to the Clinic. The Practitioner is related to their own user but also is a foreign key to the Clinic. In the cart I want to associate the child user to the product purchased. The use case is that either the Practitioner, or the Clinic may be logged in to place an order. The cart.html page needs to be a form which permits the selection of a Practitioner user which is associated with the Clinic. I am just struggling to get my head around how I add custom attributes to the cart after the product has been selected. Please help! MODELS.PY from django.contrib.auth.models import User, Group from django.db.models.signals import post_save from django.dispatch import receiver from django.utils import timezone from Product.models import Product import uuid import datetime from django.db.models.signals import post_save, pre_save from django.dispatch import receiver import random class Clinic(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True) clinic_name = models.CharField(max_length=200, blank=True, null=True) email = models.EmailField(blank=True, null=True) address = models.CharField(max_length=250, blank=True, null=True) postal_code = models.CharField(max_length=20) … -
TemplateDoesNotExist for django-templated-email
I want to send a verification code with django and I'm using django-templated-email package to send it. According to the documentation, I have configured my settings like below: settings.py # TEMPLATED EMAIL SETTINGS TEMPLATED_EMAIL_BACKEND = 'templated_email.backends.vanilla_django.TemplateBackend' TEMPLATED_EMAIL_TEMPLATE_DIR = 'templated_email/' TEMPLATED_EMAIL_FILE_EXTENSION = 'email' and the view is like: def register(request): . . . send_templated_mail( template_name='account_verification_email', from_email='from@example.com', recipient_list=[to_email], context={ 'user': user, 'domain': current_site, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': default_token_generator.make_token(user), }, ) and then I put my template in the ecommerce/templates/account_verification_email.email and even in the ecommerce/templates/account_verification_email.email But when I want to send the email It shows the following errors: TemplateDoesNotExist at /accounts/register/ django.template.loaders.filesystem.Loader: /home/alipqb/Desktop/Codes/ecommerce/templates/account_verification_email.email(Source does not exist)` django.template.loaders.app_directories.Loader: /home/alipqb/Desktop/Codes/ecommerce/accounts/templates/account_verification_email.email (Source does not exist) But I have created all those templates. How can fix it? -
Could not find the GDAL library (connection with Hana)
I am using Python 3.8.5 version and the Django 3.2.4. I already install GDAL library from the official website with the version 3.3.0. with a pip install. There are 4 databases presents at the origin in Django but I have to use the Hana one which is notpython. I have only found 2 topics relative to that on GitHub but they are both very old (4 years and 8 years ago). I have tried everything to solve that problem but nothing seems to work. I already have the following message when I try to make migrations : "django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal302", "gdal301", "gdal300", "gdal204", "gdal203", "gdal202", "gdal201", "gdal20"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings." Someone has an idea to solve that problem ? -
django deployment on aws lightsail with apache
i'm trying to deploy my django project in amazon lightsail with apache. i now get the 500 internal server error, the log files says that i'm missing django. this is the error log: [Fri Jun 18 09:17:21.185206 2021] [mpm_event:notice] [pid 18855:tid 139805003744384] AH00491: caught SIGTERM, shutting down [Fri Jun 18 09:17:21.234245 2021] [mpm_event:notice] [pid 32187:tid 139822253159552] AH00489: Apache/2.4.38 (Debian) mod_wsgi/4.6.5 Python/3.7 configured -- resuming norma l operations [Fri Jun 18 09:17:21.234333 2021] [core:notice] [pid 32187:tid 139822253159552] AH00094: Command line: '/usr/sbin/apache2' [Fri Jun 18 09:17:58.402513 2021] [wsgi:error] [pid 32188:tid 139822222972672] [remote 93.43.210.55:49401] mod_wsgi (pid=32188): Failed to exec Python script file '/var/ww w/sito_fotografo/sito_fotografo/sito/wsgi.py'. [Fri Jun 18 09:17:58.402562 2021] [wsgi:error] [pid 32188:tid 139822222972672] [remote 93.43.210.55:49401] mod_wsgi (pid=32188): Exception occurred processing WSGI script '/var/www/sito_fotografo/sito_fotografo/sito/wsgi.py'. [Fri Jun 18 09:17:58.402710 2021] [wsgi:error] [pid 32188:tid 139822222972672] [remote 93.43.210.55:49401] Traceback (most recent call last): [Fri Jun 18 09:17:58.402734 2021] [wsgi:error] [pid 32188:tid 139822222972672] [remote 93.43.210.55:49401] File "/var/www/sito_fotografo/sito_fotografo/sito/wsgi.py", li ne 12, in <module> [Fri Jun 18 09:17:58.402777 2021] [wsgi:error] [pid 32188:tid 139822222972672] [remote 93.43.210.55:49401] from django.core.wsgi import get_wsgi_application [Fri Jun 18 09:17:58.402796 2021] [wsgi:error] [pid 32188:tid 139822222972672] [remote 93.43.210.55:49401] ModuleNotFoundError: No module named 'django' [Fri Jun 18 09:23:28.841563 2021] [wsgi:error] [pid 32188:tid 139822105474816] [remote 93.43.210.55:49231] mod_wsgi (pid=32188): Failed to … -
Django Rest Framework group fields
I'm exposing an REST api for legacy application. I have a Company model class that defines the following fields: address_street (required) address_street_number (required) shipping_address_street (optional) shipping_address_street_number (optional) billing_address_street (optional) ... you got the point I would like to group all address fields into an Adress serializer in order to have a cleaner structure. Some thing like: { "adress": {"street": "foo", "street_number": "bar"}, "shipping_address": {"street": "ham", "street_number": "spam"}, "billing_address": null, } So far, I can create a CompanySerializer from a rest_framework.serializers.Serializer and manually build my Company objects from this. It is tedious, but it will work. But how can I build a rest_framework.serializers.ModelSerializer for my Company model, changing the way fields are structured to have my model fields automatically populated by rest framework ? DRF nested model serializers seems to only work for relations, not groups of fields. Am I to build my models instances by hands or is there a way to decouple the representation of a model serializer to my object ? -
Not getting output from api after hosting in Django
Hi I making a page where user can enter pincode for their respective state and can get availability of vaccine in their area. It's run perfectly on local server but when I hosted it show no output neither any error. (https://doctorz.pythonanywhere.com/vaccine) my views.py def vaccine(request): try: today = date.today() d1 = today.strftime("%d-%m-%Y") pincode = request.GET.get('pincode') pincode = str(pincode) # # pincode = '110065' baseurl = 'https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/findByPin?pincode={}&date={}'.format(pincode,d1) # baseurl = 'https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/findByPin?pincode=110025&date=15-06-2021' vaccine = requests.get(baseurl) data = vaccine.json() vaccinedate = data["sessions"] return render(request, 'vaccine_data.html', {'vaccinedate':vaccinedate}) except: return render(request, 'vaccine_data.html') vaccine_data.html {% extends 'base.html' %} {% block title %}Home{% endblock title %} {% block body %} <div> <div class="form-control formy"> <form method="GET"> <label for="pincode" style="margin: 5px 0px 5px 0px;">Enter Pincode: </label> <input class="" type="text" name="pincode"> <button class="btn btn-primary" type="submit">Submit</button> </form> <br><br> <table class="table table-bordered"> <thead> <tr> <th scope="col">#</th> <th scope="col">Center ID</th> <th scope="col">Name</th> <th scope="col">Address</th> <th scope="col">Fee Type</th> <th scope="col">Vaccine</th> <th scope="col">Age limit</th> </tr> </thead> <tbody> {% for i in vaccinedate %} <tr> <th scope="row">{{forloop.counter}}</th> <td>{{i.center_id}}</td> <td>{{i.name}}</td> <td>{{i.address}}</td> <td>{{i.fee_type}}</td> <td>{{i.vaccine}}</td> <td>{{i.min_age_limit}}</td> </tr> {% endfor %} </tbody> </table> </div> </div> {% endblock body %} urls.py from django.urls import path from home import views from django.conf.urls import * urlpatterns = [ path('',views.index, name="home"), path('home',views.index, name="home"), … -
Celery data import leads to MultipleObjectsReturned
I'm running a Celery Data import Job but I'm running into the following issue Task Import Descriptor[ef5cad5c-26aa-40de-89a0-e85fb0d580a2] raised unexpected: MultipleObjectsReturned('get() returned more than one MusicAlbums -- it returned 2!' This happens because I call the task like this: for clean_obj in keys: .... if not Files.objects.filter(descriptor=strip_descriptor_url_scheme(url)).exists(): task = import_descriptor.delay(descriptor=url) task.get(timeout=120, interval=3) which basically puts all descriptors I try to import directly onto the message queue... I don't have issues if I call the task like that, because every descriptor gets imported one after another: task = import_descriptor.apply_async(kwargs={"descriptor": str(url)}) task.get(timeout=120, interval=1) Inside the task this happens: if not MusicArtists.objects.filter(title=artist_value).exists(): new_music_artist_object = MusicArtists.objects.create(title=artist_value) new_music_artist_object.save() new_music_artist_object.refresh_from_db() else: new_music_artist_object = MusicArtists.objects.get(title=artist_value) if not MusicAlbums.objects.filter(artist=new_music_artist_object, title=album_value).exists(): new_music_album_object = MusicAlbums.objects.create(title=album_value, artist=new_music_artist_object, cover=cover_value, total_discs=total_discs_value, total_tracks=total_tracks_value, copyright=copyright_value, release_date=release_date_value, genre=genre_value) new_music_album_object.save() new_music_album_object.refresh_from_db() else: new_music_album_object = MusicAlbums.objects.get(artist=new_music_artist_object, title=album_value) new_music_track_object = MusicTracks.objects.create(file=new_file_object, album=new_music_album_object, artist=new_music_artist_object, bitrate=bitrate_value, duration=duration_value, size=size_value, nb_streams=nb_streams_value, media_type=0, title=title_value, release_date=release_date_value, disc=disc_value, track=track_value ) new_music_track_object.save() new_music_track_object.refresh_from_db() The problem with this is that if multiple celery processes are working on the task queue I sometimes have the same Artist, Album or Track saved at the Database twice with two different primary keys ... So my question is how could I possibly bypass this behavior without creating my whole database sequential as this … -
I'm trying to change password using the django built in functionality but it's not working
Problem I'm trying to change the password using the Django in-built authentication functionality but it doesn't change the password and doesn't even redirect to the next page. I have pasted all the code below which I have written for this, please can anyone can check it and tell me what am I doing wrong. form.py class MyPasswordChangeForm(PasswordChangeForm): old_password = forms.CharField(label=_("Old Password"),strip=False,widget=forms.PasswordInput(attrs={'autocomplete':'current-password', 'autofocus':True,'class':'form-control'})) new_password1 = forms.CharField(label=_("New Password"),strip=False,widget=forms.PasswordInput(attrs={'autocomplete':'new-password','class':'form-control'}),help_text=password_validation.password_validators_help_text_html()) new_password2 = forms.CharField(label=_("Confirm New Password"),strip=False,widget=forms.PasswordInput(attrs={'autocomplete':'new-password','class':'form-control'})) urls.py path('passwordchange/',auth_views.PasswordChangeView.as_view(template_name='main/passwordchange.html',form_class=MyPasswordChangeForm, success_url='/passwordchangedone/'),name='passwordchange'), passwordchange.html {% extends 'main/base.html' %} {% load static %} {% block title %}Buy Now{% endblock title %} {% block main-content %} <div class="container my-5"> <div class="row"> <h3>Welcome {{request.user.username.title}}</h3> <div class="col-sm-2 border-end"> <ul class="list-unstyled"> <li class="d-grid"><a href="{% url 'main:profile' %}" class="btn btn-primary">Change Password</a></li> </ul> </div> <div class="col-sm-9 offset-sm-1"> <h3>Change Password</h3> <hr> <form action="" method=" post" novalidate class="shadow-sm p-5"> {% csrf_token %} <!-- {{form.as_p}} --> {% for fm in form %} <div class="form-group"> {{fm.label_tag}}{{fm}} <small class="text-danger">{{fm.errors|striptags}}</small><br> </div> {% endfor %} <input type="submit" class="btn btn-primary mt-4" value="Save"> {% if form.non_field_errors %} {% for error in form.non_field_errors %} <p class="alert alert-danger my-3">{{error}}</p> {% endfor %} {% endif %} </form> </div> </div> </div> {% endblock main-content %} -
Init.py goes for local settings.py rather than production settings.py DJANGO
I created a setting folder with init.py, base.py, local. py and production.py but the Heroku address (host) is always trying to use local settings. The app works fine when I access it from '127.0.0.1' but displays a 'disallowed host' error message when I try to access it from Heroku generated web address "XXX.herokuapp.com". "XXX.herokuapp.com" is only an allowed host when running production.py settings. Also, DEBUG = False in that particular setting file, so I suppose I shouldn't an error message detailed Thanks for any help! Here's my init.py file : from .base import * from .production import * try: from .local import * except: pass Here's my local.py file : from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'XXX' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['0.0.0.0', '127.0.0.1', ] EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'XXX@gmail.com' #my gmail username EMAIL_HOST_PASSWORD = 'XXX' #my gmail password EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = "Lucas <XXXX>" ADMINS = [('Lucas', … -
Getting error when trying to use Django ORM
I have a script which pull out every record from database, but I can't run it because I'm getting error. I have googled it, tried to change settings but probably I do something wrong. Eror: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. script def test(self): enter = Enter.objects.all() print(enter) test() -
Extracting data from the payload in Djnago Rest framework
I have a payload of data sent from the frontend. It is a post api call to create a product object and a variant object at the same time. But I am having difficulties in extracting the ids from the validated_data. The data sent is like this: name: Soap category[0]: 7 category[1]: 23 brand: 7 collection: 11 availability: in_stock warranty: no_warranty service: cash_on_delivery rating: 3 best_seller: true top_rated: true featured: true main_product_image: (binary) merchant: 2 variants[0][product_id]: fgfdg variants[0][price]: 127 variants[0][quantity]: 1 variants[0][color]: red variants[0][size]: M variants[0][variant_availability]: not_available variants[0][variant_image]: (binary) variants[1][product_id]: fgfdg variants[1][price]: 127 variants[1][quantity]: 1 variants[1][color]: red variants[1][size]: M variants[1][variant_availability]: not_available variants[1][variant_image]: (binary My view: class ProductAddAPIView(CreateAPIView): permission_classes = [IsAuthenticated] parser_classes = [MultipartJsonParser] serializer_class = AddProductSerializer My serializer: class AddProductSerializer(serializers.ModelSerializer): id = serializers.PrimaryKeyRelatedField(read_only=True) variants = VariantSerializer(many=True) slug = serializers.SlugField(read_only=True) class Meta: model = Product fields = ['id','merchant','featured', 'top_rated','category','brand','collection','sub_category', 'name','slug','description', 'main_product_image','best_seller','picture', 'rating','availability','warranty','services','variants'] #depth = 1 def create(self, validated_data): #user = self.context['request'].user picture_data = validated_data.get('picture') merchant = validated_data.get('merchant') featured = validated_data.get('featured') top_rated = validated_data.get('top_rated') brand = validated_data.get('brand') collection = validated_data.get('collection') sub_category = validated_data.get('sub_category') name = validated_data.get('name') description = validated_data.get('description') main_product_image = validated_data.get('main_product_image') best_seller = validated_data.get('best_seller') rating = validated_data.get('rating') availability = validated_data.get('availability') warranty = validated_data.get('warranty') services = validated_data.get('services') #variants_logic variants_data = validated_data.get('variants') #breakpoint() …