Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Security concerns with user defined postgres jsonb queries in Django
We have a postgres jsonb field in Django that allows users to store arbitrary user data. We wish to allow users to query this field but are unsure about the security implications. The model from django.db import models class Item(models.Model): user = models.ForeignKey("user", null=False) meta = JSONField() Query def custom_query(operation, value): qs = Item.objects.filter(user=user) params = { "meta__" + operation: value } qs = qs.filter(**params) Usage: Assuming meta is {"a": 1}. custom_query(operation="contains", value={"a": 1}) custom_query(operation="a", value=1) The above should be valid and equivalent queries. Is this a secure way to perform the query? -
Not able to pass user in a view in django so want to pass it through the URL
I am having a payment app in django(paytm) it has the following views: def payingpage(request): if request.user.is_authenticated: customer=request.user.customer order, created=Order.objects.get_or_create(customer=customer, complete=False) items=order.orderitem_set.all() shippingddress=ShippingAddress.objects.filter(customer=customer) total=order.finalpay() context={ 'items':items, 'order':order, 'ship':shippingddress } param_dict = { 'MID': 'QEnNqO51999030615507', 'ORDER_ID':str(order.id), 'TXN_AMOUNT':str(total), 'CUST_ID': "customer.user.id", 'INDUSTRY_TYPE_ID': 'Retail', 'WEBSITE': 'WEBSTAGING', 'CHANNEL_ID': 'WEB', 'CALLBACK_URL':'http://127.0.0.1:8000/handlerequest/', } param_dict['CHECKSUMHASH'] = Checksum.generate_checksum(param_dict,MERCHANT_KEY) return render(request, 'paytm.html', {'param_dict': param_dict}) return HttpResponse("ERROR") @csrf_exempt def handlerequest(request): form = request.POST response_dict = {} for i in form.keys(): response_dict[i] = form[i] if i == 'CHECKSUMHASH': checksum = form[i] verify = Checksum.verify_checksum(response_dict, MERCHANT_KEY, checksum) if verify: if response_dict['RESPCODE'] == '01': print('order successful') else: print('order was not successful because' + response_dict['RESPMSG']) return render(request, 'handlerequest.html', {'response': response_dict,'types':Category.objects.all()}) Now the problem is that I cant pass user=request.user or order=Order.objects.all(user=user) in handlerequest view as for some reason it is not working and what I want is that in some way I can get the order id in the handlerequest view so that I can set that the orders payment in successful but I am not able to that. In django docs i saw passing parameters through Url but I cannot figure out how to proceed with it (am a beginner). This is my urls.py: path("handlerequest/",views.handlerequest,name="handlerequest"), path("payingpage/",views.payingpage,name="payingpage") In simple terms what I want is to … -
How to solve the error in login information
I have created a user and given him all the required data, but I cannot log into the page, I sure the email and password correct , but it gives me error in the information entered. template: <form action="" method="post" class="border rounded overflow-hidden p-5"> {% csrf_token %} <h4 class="text-center py-3 title">Login </h4> {% for message in messages %} <div class="btn btn-sm btn-dark col-6" role="alert"> <h3 class="text-center"> {{ message }}</h3> </div> {% endfor %} <div class="row"> <div class="form-group col-md-12 text-left px-0"> <label for="email">Email</label> <input class="border rounded-2 p-3 bg-input " type="email" name="email" id="email" placeholder="Email "> </div> <div class="form-group col-md-12 text-left px-0"> <label for="password">Password </label> <input class="border rounded-2 p-3 bg-input " type="password" class="form-control" id="password" name="password"> </div> <button class="btn btn-sm btn-dark col-12 rounded-2 my-4 p-3" type="submit">Login </button> </div> </form> my view: from django.contrib.auth import authenticate,login from django.shortcuts import render,redirect from django.contrib.auth.models import auth,Group from django.contrib import messages from django.conf import settings from django.contrib.auth.decorators import login_required from .decorators import uthenticated_user from app.models import * # Create your views here. @uthenticated_user def login(request): if request.method=='POST': email=request.POST['email'] password=request.POST['password'] user=authenticate(request,email=email,password=password) if user is not None: login(request,user) return redirect('user_home') else: messages.error(request,'There was a problem logging in. Check your email and password or create an account') return redirect('login') else: return … -
how to fix the application response error in heroku?
now I'm trying to upload my project on Heroku cloud and the website has uploaded successfully but I get the application error page from heroku when I try to enter the page the files I have created are: Pipfile Pipfile.lock Procfile pyvenv.cfg requirements.txt and I did everything the heroku needs it so, what's going on here? procfile web: gunicorn website.wsgi please tell me How can I fix that error and get the response page! -
How to change field in JWT django rest-framework
I want to change the JWT token generator field. I want a phone field instead of a username. I don't want the username field in the token generator. I want to generate a token through phone and password field only not the username. Thanks in advance. serializer.py* class MyTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): try: request = self.context["request"] except KeyError: pass else: request_data = json.loads(request.body) phone = request_data.get("phone") # app_id = request_data.get("app_id") profile_has_expired = False try: profile = Customer.objects.get(user__user=username) except ProfileApp.DoesNotExist: profile_has_expired = True else: profile_has_expired = dt.date.today() > profile.expires_on finally: if profile_has_expired: error_message = "This profile has expired" error_name = "expired_profile" raise exceptions.AuthenticationFailed(error_message, error_name) finally: return super().validate(attrs) views.py class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer models.py class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=254, unique=True) name = models.CharField(max_length=254, null=True) email = models.EmailField(max_length=254, null=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_Customer = models.BooleanField(default=True) is_Service_Provider = models.BooleanField(default=False) phone_regex = RegexValidator( regex = r'^\+?1?\d{9,10}$', message = "Phone number must be in the form of =919999999999") phone = models.CharField('Phone', validators = [phone_regex], max_length=15, unique=True, default=False) address = models.CharField(max_length=254, blank=True) Date_Of_Birth = models.DateField(auto_now_add=True, blank=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'username' EMAIL_FIELD = 'email' PHONE_FIELD = 'phone' REQUIRED_FIELDS = ['phone'] objects = UserManager() def … -
How to speed up API calls?
What i'm trying to do: Get nationality of artists (which are basically the top artists of a particular user on Spotify) from MusicBrainz API. Purpose is to map each artist to his/her nationality What i've done so far : I'm using Django to build the web app, and so i'm making API calls to Spotify, retrieve artists, and then passing artist name in the search query with limit = 1 (as i really just want to select the first result) Problem: I see that in my web app, as you can see i'm making calls to Spotify API and then the MusicBrainz API (in the given order), the response i get from Musicbrainz API takes really long time hence the first page takes quite long to load up. Is there any way to speed up this process? Or open to take up suggestions that'd replace MusicBrainz API Here's my code: url = 'https://api.spotify.com/v1/me/top/artists' headers = {"Authorization": f"Bearer {socialtoken.token}"} params = {'time_range': 'short_term', 'limit': 50} resp = requests.get(url, headers=headers, params= params) response = resp.json() topArtists = {} //creates a dictionary of top artists with key = artists name and value set to None for i in range(len(response['items'])): topArtists[(response['items'][i]['name'])] = None // … -
How can I fix this error? What you should pay attention to?
When starting the server, an error crashes, which file and piece of code should I pay attention to? Other answers given on this site did not help. Terminal: File "/home/lab/ProjectsDjango/env_bookmarks/dj-bookmarks/bookmarks/account/urls.py", line 7, in <module> url(r'^login/$', 'django.contrib.auth.views.login', name='login'), File "/home/lab/ProjectsDjango/env_bookmarks/bookmarks/lib/python3.8/site-packages/django/conf/urls/__init__.py", line 22, in url return re_path(regex, view, kwargs, name) File "/home/lab/ProjectsDjango/env_bookmarks/bookmarks/lib/python3.8/site-packages/django/urls/conf.py", line 73, in _path raise TypeError('view must be a callable or a list/tuple in the case of include().') TypeError: view must be a callable or a list/tuple in the case of include(). Next is my application code. Main urls.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^account/', include('account.urls')), ] App views.py from django.http import HttpResponse from django.shortcuts import render from django.contrib.auth import authenticate, login from .forms import LoginForm from django.contrib.auth.decorators import login_required def user_login(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate(username=cd['username'], password=cd['password']) if user is not None: if user.is_active: login(request, user) return HttpResponse('Authenticated successfully') else: return HttpResponse('Disabled account') else: return HttpResponse('Invalid login') else: form = LoginForm() return render(request, 'account/login.html', {'form': form}) @login_required def dashboard(request): return render(request, 'account/dashboard.html', {'section': 'dashboard'}) App urls.py from django.conf.urls import url from . import views urlpatterns = [ #url(r'^login/$', views.user_login, name='login'), … -
Django settin up Media files on IIS
I have a Django App which creates PDF files on the server. On the development server it works well but on IIS it doesnt create the file. I have given all the persmission yet theres no luck. I wrote a simple script to write a text file and that too doesnt work on IIS. Any help to resolve this is appriciated. Thank you. def fileWriteTest(request): f = open("media/testwrite.txt", "a") f.write("Now the file has more content!") f.close() print("File Written!") return HttpResponse("Done !") FileNotFoundError at /accounts/testfile/ [Errno 2] No such file or directory: 'media/testwrite.txt' -
Redis server not starting on windows 10
I have to use redis so that in django i can have channels_redis. Problem is, the server doesnt run. Im not sure why, im new to this. when i use this command: >redis-server redis.windows.conf [11428] 09 Aug 11:51:03.037 # Creating Server TCP listening socket 127.0.0.1:6379: bind: No error then i use this: >redis-server [8524] 09 Aug 11:55:25.736 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf [8524] 09 Aug 11:55:25.741 # Creating Server TCP listening socket *:6379: bind: No such file or directory As you can see these lines turn up and i dont know what to do. This is my folder: Help would be appreciated! -
How can I GET a variable from the html page?
Please help me fix this GET statement. I tried many diferent options but it is still not working. You can find my code here -
Form submitt upon selection
I am working on the solution which will enable language selection of my website. My current code is as follows: {% trans "Select language" %}: <div class="language-changer mt-2 col-md-12"> <form action="{% url 'set_language' %}" method="post"> {% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"/> <select name="language" class="selectpicker" data-width="10px" id="inputGroupSelect02"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% for lang in LANGUAGES %} <option value="{{ lang.0 }}" selected="selected"> {{ lang.1 }} ({{ lang.0 }}) </option> {% endfor %} </select> <br> <input class="btn btn-m btn-full rounded-s bg-green1-dark text font-600" type="submit" value="{% trans 'Change' %}"/> </form> </div> How do I change it so form is sent without hitting "submit" button? I found that one can use "onchage" attribute, but I cannot implement in within my form -
How can we add Django logentry from admin to client side?
views.py this is inside a django app. from django.contrib.admin.models import LogEntry def activity(request): entries=LogEntry.objects.all() return render(request, 'accessories/activity.html',{'entries':entries}) activity.html {{entries}} urls.py from .import views url_patterns=[ path('activity/',views.activity,name='activity'), ] I got queryset data with only datefields Image Here for Output I want to get output like: Django admin Output -
Could not load Google Cloud Storage bindings error Django
When want to use Google Cloud Storage with my Django project it gives the above error. Cannot find out what is the problem, tried all the answers from here: Configure Django and Google Cloud Storage? too, did not help. Followed all the steps of this documentation too: https://django-storages.readthedocs.io/en/latest/backends/gcloud.html My code: Used django-storages[google] to connect. Configured settings as follows: settings.py: GS_CREDENTIALS=service_account.Credentials.from_service_account_file('path/to/my/credentials.json') DEFAULT_FILE_STORAGE='storages.backends.gcloud.GoogleCloudStorage' GS_BUCKET_NAME = 'my-bucket-name' GS_PROJECT_ID='my-project-id' MEDIA_URL = 'https://storage.googleapis.com/my-bucket-name/' MEDIA_ROOT = 'media/' From Google Platform Console created service, gave permission to my bucket for my service as Cloud Storage Admin Any clues of what is the problem, spend hours tryn find out -
Customize a Django widgets' template
I need to customize a widget from GeoDjango to allow to use a specific template. When I try to use that template I see this error: TemplateDoesNotExist at /add/points openlayers/widgets/add_geometry.html Request Method: GET Request URL: http://127.0.0.1:8000/add/points Django Version: 3.0.8 Exception Type: TemplateDoesNotExist Exception Value: openlayers/widgets/add_geometry.html Exception Location: /home/maxdragonheart/DEV_FOLDER/Django/Singole APP/GeoDjango/devenv/lib/python3.6/site-packages/django/template/backends/django.py in reraise, line 84 Python Executable: /home/maxdragonheart/DEV_FOLDER/Django/Singole APP/GeoDjango/devenv/bin/python3 Python Version: 3.6.9 Python Path: ['/home/maxdragonheart/DEV_FOLDER/Django/Singole APP/GeoDjango/webgis', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/maxdragonheart/DEV_FOLDER/Django/Singole ' 'APP/GeoDjango/devenv/lib/python3.6/site-packages'] Server time: Sun, 9 Aug 2020 11:15:17 +0200 Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /home/maxdragonheart/DEV_FOLDER/Django/Singole APP/GeoDjango/devenv/lib/python3.6/site-packages/django/forms/templates/openlayers/widgets/add_geometry.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/maxdragonheart/DEV_FOLDER/Django/Singole APP/GeoDjango/devenv/lib/python3.6/site-packages/django/contrib/admin/templates/openlayers/widgets/add_geometry.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/maxdragonheart/DEV_FOLDER/Django/Singole APP/GeoDjango/devenv/lib/python3.6/site-packages/django/contrib/auth/templates/openlayers/widgets/add_geometry.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/maxdragonheart/DEV_FOLDER/Django/Singole APP/GeoDjango/devenv/lib/python3.6/site-packages/django/contrib/gis/templates/openlayers/widgets/add_geometry.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/maxdragonheart/DEV_FOLDER/Django/Singole APP/GeoDjango/devenv/lib/python3.6/site-packages/rest_framework/templates/openlayers/widgets/add_geometry.html (Source does not exist) Here my widget: from django.contrib.gis.forms.widgets import BaseGeometryWidget from django.contrib.gis.geometry import json_regex class CustomOpenLayersWidget(BaseGeometryWidget): template_name = 'openlayers/widgets/add_geometry.html' map_srid = 3857 class Media: css = { 'all': ( 'https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/css/ol.css', 'css/map.css', ) } js = ( 'https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.3.1/build/ol.js', 'js/CustomOpenLayersWidget.js', ) def serialize(self, value): return value.json if value else '' def deserialize(self, value): geom = super().deserialize(value) # GeoJSON assumes WGS84 (4326). Use the map's SRID instead. if geom and json_regex.match(value) and self.map_srid != 4326: geom.srid = self.map_srid return geom … -
Django-Oscar no such table: main.customer_communicationeventtype when deleting order
I have a Django-Oscar e-commerce app that I built from the sandbox. I have not really changed anything in the code, but added a few products and stuff. I tried to add a demo order and it failed for some reason, but the order object was created. When I tried to delete the object from django-admin page, it gives me following error: django.db.utils.OperationalError: no such table: main.customer_communicationeventtype Django v3.0.9 Basic SQLite3 DB Complete Traceback: Internal Server Error: /admin/order/order/ Traceback (most recent call last): File "/Users/siddheshpisal/.pyenv/versions/3.7.1/envs/oscar/lib/python3.7/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/Users/siddheshpisal/.pyenv/versions/3.7.1/envs/oscar/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: main.customer_communicationeventtype The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/siddheshpisal/.pyenv/versions/3.7.1/envs/oscar/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/siddheshpisal/.pyenv/versions/3.7.1/envs/oscar/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/siddheshpisal/.pyenv/versions/3.7.1/envs/oscar/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/siddheshpisal/.pyenv/versions/3.7.1/lib/python3.7/contextlib.py", line 74, in inner return func(*args, **kwds) File "/Users/siddheshpisal/.pyenv/versions/3.7.1/envs/oscar/lib/python3.7/site-packages/django/contrib/admin/options.py", line 607, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/Users/siddheshpisal/.pyenv/versions/3.7.1/envs/oscar/lib/python3.7/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/siddheshpisal/.pyenv/versions/3.7.1/envs/oscar/lib/python3.7/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/Users/siddheshpisal/.pyenv/versions/3.7.1/envs/oscar/lib/python3.7/site-packages/django/contrib/admin/sites.py", line 231, in inner return … -
How can I make a field in my Django app random
I am working on a Django project and I want to make a field to always be randomly generated so they are unique in the database but I don't seem to get how to do so. I tried the following : from django.db import models # Random character generation for # the unique short URLs import string, random def random_url(n): return ''.join(random.choice(string.ascii_letters) for x in range(n)) #print(random_id(6)) #testing the function #Class for the URL class ShortURL(models.Model): original_url = models.CharField(max_length=200) short_url = models.CharField(max_length=100, primary_key=True, default=random_url(6)) timestamp = models.DateTimeField(auto_now=True) In my admin view. All the "URL" have the same random code which I don't want. E.g ABYpsB Please help needed -
Is there a way to get django-dashing work with newer versions of django?
I'm using django 2.2.6 and I am getting: django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'dashing.templatetags.dashing_tags': cannot import name 'six' from 'django.utils' django dashing when trying to use django-dashing. Is there a way to get django-dashing to work without with django 2.2.6+ version? Note: The only thing I found about django-dashing not working on SO is this question and it seems that there, the OP cannot get the django-dashing dashboard to work with django 1.9, although there isn't a solution other than downgrading the django version. -
Connecting django http request signal with a particular page
I'm trying to build a Django signal that reports when a particular page was visited. I've tried updated Django's request_finished signal but I'm not sure how to filter it so that the sender only tells the receiver when a certain page was visited. This works for returning any page, but how do I filter for a particular URL? from django.core.signals import request_finished from django.dispatch import receiver @receiver(request_finished) def my_callback(sender, **kwargs): print("Request finished!") -
How to pass OneToOne field value to Django serializer
I have two models Retailer and Shop. They are related by OneToOne field. class Retailer(models.Model): name=models.CharField( max_length=255, null=False, ) email=models.EmailField( max_length=255, null=False, unique=True ) password=models.CharField( max_length=255, null=False ) phone_number=models.CharField( max_length=10, null=False ) verification_status=models.BooleanField( default=False, ) created_at=models.DateField( default=timezone.now, ) def __str__(self): return (self.name) class Shop(models.Model): shop_name=models.CharField( max_length=255, null=False ) shop_address=models.CharField( max_length=255, null=False ) gst_number=models.CharField( max_length=15, null=False, ) pin_code=models.CharField( max_length=6, null=False ) store_description=models.TextField( blank=True, null=True ) retailer=models.OneToOneField( Retailer, on_delete=models.CASCADE, related_name="shop" ) def __str__(self): return (self.shop_name) In my frontend the intial form is to register the Retailer. The Retailer gets successfully added to the database. But when i add shop it does not get added into the database. Though the rest api sents the response but serializer.save() does not work. Here's how my shop json serializer data looks : { "shop_name": "Smith Electronics", "shop_address": "Street 11, LA", "gst_number": "6786768809988u9", "pin_code": "412004", "store_description": "", "retailer": 5 } Here's how i send a post request: axios.post("http://127.0.0.1:8080/addshop/", { shop_name: this.state.storeName, shop_address: this.state.storeAdd, gst_number: this.state.gst, pin_code: this.state.pinCode, store_description: this.state.description, retailer_id: this.state.retailerID }) .then(response => { this.handleRedirect(event, response) }) .catch(error => { event.preventDefault(); console.log(error); }) I am new to Django serializers. Anyone knows how it should be done? -
Fail to display the context passed to templates while using Django3.1
I want to use Django to make a notice board on my website, so I made a model like this: class notice(models.Model): # the title of the notice text = models.CharField(max_length = 50) date_added = models.DateTimeField(auto_now_add = True) def __str__(self): return self.text And I wrote "view.py" like this (the main part): def notices(request): # display the notice title notices = notice.objects.order_by("date_added") context = {"notice": notices} return render(request, "index.html", context) But in the file "index.html", when I wrote these codes: <ul> {% for n in notices %} <li>{{n.text}}</li> {% endfor %} </ul> Nothing was displayed. Does anyone know how to solve this issue? I'd be grateful if you help me. Well...My English is really poor, and if what I said is kind of impolite... Might you just forgive me for that? Thanks! -
Django Admin, ValidationError as flash?
I was able to show validation error message in django admin.. using this method class TblSearchCase(models.Model): top_place_id = models.IntegerField() #models.ForeignKey('TblUser', models.DO_NOTHING, blank=True, null=True) def clean(self): if self.top_place_id < 0: raise ValidationError("place id cannot be negative") like this is there a simple way to make this look like a flash message, without having to edit the template? -
how can I fix the application error in heroku cloud?
I'm trying upload my project on the cloud by heroku but the application doesn't work and when I run that command: $ heroku logs --tail I got that error: 2020-08-09T07:49:54.503447+00:00 app[api]: Starting process with command `bash` by user medoabdin@gmail.com 2020-08-09T07:49:54.752948+00:00 app[web.1]: [2020-08-09 07:49:54 +0000] [9] [ERROR] Exception in worker process 2020-08-09T07:49:54.752982+00:00 app[web.1]: Traceback (most recent call last): 2020-08-09T07:49:54.752983+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2020-08-09T07:49:54.752984+00:00 app[web.1]: worker.init_process() 2020-08-09T07:49:54.752984+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 119, in init_process 2020-08-09T07:49:54.752985+00:00 app[web.1]: self.load_wsgi() 2020-08-09T07:49:54.752985+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2020-08-09T07:49:54.752985+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2020-08-09T07:49:54.752986+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi 2020-08-09T07:49:54.752986+00:00 app[web.1]: self.callable = self.load() 2020-08-09T07:49:54.752987+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 49, in load 2020-08-09T07:49:54.752987+00:00 app[web.1]: return self.load_wsgiapp() 2020-08-09T07:49:54.752987+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp 2020-08-09T07:49:54.752988+00:00 app[web.1]: return util.import_app(self.app_uri) 2020-08-09T07:49:54.752988+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/util.py", line 358, in import_app 2020-08-09T07:49:54.752988+00:00 app[web.1]: mod = importlib.import_module(module) 2020-08-09T07:49:54.752988+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module 2020-08-09T07:49:54.752989+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2020-08-09T07:49:54.752989+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import 2020-08-09T07:49:54.752990+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load 2020-08-09T07:49:54.752990+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked 2020-08-09T07:49:54.752991+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 671, in _load_unlocked 2020-08-09T07:49:54.752991+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 783, in … -
ValueError: Field 'id' expected a number but got 'None' on django
I have UpdateView for updating my employee object which has three models. One of two models has been set with inline formset factory because those are connected with ForeignKey relationship. views.py: class EmployeeUpdateView(LoginRequiredMixin, UpdateView): """ Update a created a employee """ login_url = '/authentication/login/' template_name = 'employee/employee_update_form.html' form_class = EmployeeAddModelForm # work_form_class = WorkExperienceForm # education_form_class = EducationForm work_formset_class = WorkExperienceFormset education_formset_class = EducationFormset queryset = Employee.objects.all() # Override default get method def get(self, request, *args, **kwargs): id_ = self.kwargs.get("id") employee_id = Employee.objects.get(id=id_) work_info = WorkExperience.objects.get(employee=employee_id) education_info = Education.objects.get(employee=employee_id) form = self.form_class(instance=employee_id) # work_form = self.work_form_class(prefix='work_form', instance=work_info) # education_form = self.education_form_class(prefix='education_form',instance=education_info) work_formset = self.work_formset_class(request.GET or None, instance=employee_id) education_formset = self.education_formset_class(request.GET or None, instance=employee_id) return render(request, self.template_name, { 'form': form, 'work_formset': work_formset, 'education_formset': education_formset, 'supervisor_assigned': employee_id.supervisor_select } ) # Override default post method def post(self, request, *args, **kwargs): id_ = self.kwargs.get("id") employee_id = Employee.objects.get(id=id_) # work_info = WorkExperience.objects.get(employee=employee_id) # education_info = Education.objects.get(employee=employee_id) form = self.form_class(request.POST, instance=employee_id) # work_form = self.work_form_class(request.POST, prefix='work_form', instance=work_info) # education_form = self.education_form_class(request.POST, prefix='education_form',instance=education_info) work_formset = self.work_formset_class(request.POST, instance=employee_id) education_formset = self.education_formset_class(request.POST, instance=employee_id) # Check form validation if form.is_valid() and work_formset.is_valid() and education_formset.is_valid(): instance = form.save() # Save work experience for work_form in work_formset: work = work_form.save(commit=False) work.employee_id = … -
Data not saving in models in django
I am creating a review application that requires the ratings,subject & comment. However each time I input form data . no change is reflected in the database Views.py def addcomment(request,id): url = request.META.get('HTTP_REFERER') # return HttpResponse(url) if request.method == 'POST': # check post form = CommentForm(request.POST) if form.is_valid(): obj = Comment() # create relation with model obj.subject = form.cleaned_data['subject'] obj.comment = form.cleaned_data['comment'] obj.rate = form.cleaned_data['rate'] obj.product_id=id current_user= request.user obj.user_id=current_user.id obj.save() return HttpResponseRedirect(url) return HttpResponseRedirect(url) model.py class Comment(models.Model): STATUS = ( ('New', 'New'), ('True', 'True'), ('False', 'False'), ) product=models.ForeignKey(Product,on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) subject = models.CharField(max_length=50, blank=True) comment = models.CharField(max_length=250,blank=True) rate = models.IntegerField(default=1) image = models.ImageField(upload_to='tetimonials/', null=True, blank=True) status=models.CharField(max_length=10,choices=STATUS, default='New') def __str__(self): return self.subject class CommentForm(ModelForm): class Meta: model = Comment fields = ['subject', 'comment', 'rate'] However i m getting Post data from template , but the code doesnot save in comment model? Help me out. -
Django - Targetting primary key of current "Artist" object as a filter from "All Track" result list
Im working n a record label website in Django 3 using Python3. (Artist, Release, Track structure) I am attempting to filter out a list of all tracks based on the current artist page. music/artist/ I'm thining to filter this in the context_processors file, but dont know how, and am willing to do it anyway that works if this is not possible. artist.html {% block body %} <div class="container artistitem"> <h2>{{ artist.artist_name }}</h2> <h3>{{ artist.artist_url }}</h3> <h5>{{ artist.artist_id }}</h5> <div class="artistimage"><img src="{{ artist.artist_logo.url }}"></div> <div> <h3>Discography</h3> <p> <ul> <!-- for this artist id in all releases print all release name --> <!-- {% for release.artist.id in all_releases %} <li> {{ release.release_title }} </li> {% endfor %} --> <!-- for this artist id in all releases print all release name --> {% for track in all_tracks_byartist %} <li> {{ track.track_title }} </li> {% endfor %} </ul> </p> </div> </div> {% endblock %} models.py from django.db import models # Create your models here. class Artist(models.Model): artist_name = models.CharField(max_length=250, default='') artist_logo = models.FileField() artist_url = models.URLField(blank=True) def __str__(self): return self.artist_name class Release(models.Model): artist = models.ForeignKey(Artist, on_delete=models.CASCADE, related_name='release') release_title = models.CharField(max_length=500) release_cover = models.FileField() release_duration = models.IntegerField() def __str__(self): return self.release_title class Track(models.Model): release = …