Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Gunicorn / Procfile - module.wsgi not found
I'm trying to deploy a django app to heroku. My directory structure is: 'root'/ Procfile backend/ django_app/ manage.py mainapp/ settings.py wsgi.py I tried to follow the indications given on some posts here on stackoverflow but to no avail. I have a Procfile in the root directory. The latest version has: web: gunicorn backend.django_app.mainapp.wsgi --log-file - But it still gives me a module not found error: 2021-05-01T20:20:33.556737+00:00 heroku[web.1]: State changed from crashed to starting 2021-05-01T20:20:58.799412+00:00 heroku[web.1]: Starting process with command `gunicorn backend.django_app.mainapp.wsgi --log-file -` 2021-05-01T20:21:01.738041+00:00 app[web.1]: [2021-05-01 20:21:01 +0000] [4] [INFO] Starting gunicorn 20.0.4 2021-05-01T20:21:01.739021+00:00 app[web.1]: [2021-05-01 20:21:01 +0000] [4] [INFO] Listening at: http://0.0.0.0:46010 (4) 2021-05-01T20:21:01.739198+00:00 app[web.1]: [2021-05-01 20:21:01 +0000] [4] [INFO] Using worker: sync 2021-05-01T20:21:01.744319+00:00 app[web.1]: [2021-05-01 20:21:01 +0000] [8] [INFO] Booting worker with pid: 8 2021-05-01T20:21:02.007630+00:00 app[web.1]: [2021-05-01 20:21:02 +0000] [8] [ERROR] Exception in worker process 2021-05-01T20:21:02.007644+00:00 app[web.1]: Traceback (most recent call last): 2021-05-01T20:21:02.007645+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2021-05-01T20:21:02.007645+00:00 app[web.1]: worker.init_process() 2021-05-01T20:21:02.007646+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 119, in init_process 2021-05-01T20:21:02.007646+00:00 app[web.1]: self.load_wsgi() 2021-05-01T20:21:02.007647+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2021-05-01T20:21:02.007648+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2021-05-01T20:21:02.007648+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi 2021-05-01T20:21:02.007648+00:00 app[web.1]: self.callable = self.load() 2021-05-01T20:21:02.007649+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 49, in load … -
Why do I have a TypeError (Object ... is not JSON serializable) when trying to set a session value in a view?
I have this strange TypeError raised : "Object of type Product is not JSON serializable" when I try to set a session value in a view (in basket app). The error occurs with request.session['Hello'] = 'foo'. However, this error does not occur elsewhere. For instance, in store app, in views.py, the following request.session['Hello World'] = 'Alloy' works very well. Why is that happening ? basket app / views.py from django.shortcuts import render, get_object_or_404 from django.http import JsonResponse from . basket import Basket from store.models import Product from discount.forms import UserDiscountForm def basket_summary(request): basket = Basket(request) context = {'basket':basket} request.session['Hello'] = 'foo' return render(request,"store/basket_summary.html",context) def basket_add(request): basket = Basket(request) if request.POST.get('action') == 'post': product_id = int(request.POST.get('productid')) product_qty = int(request.POST.get('productqty')) product = get_object_or_404(Product, id=product_id) basket.add(product=product, qty=product_qty) basketqty = basket.__len__() response = JsonResponse({'qty':basketqty}) return response def basket_add_new(request): basket = Basket(request) if request.POST.get('action') == 'post': product_id = int(request.POST.get('productid')) product = get_object_or_404(Product, id=product_id) basket.add_new(product=product) basketqty = basket.__len__() response = JsonResponse({'qty':basketqty}) return response def basket_delete(request): basket = Basket(request) if request.POST.get('action') == 'post': product_id = int(request.POST.get('productid')) basket.delete(product=product_id) basketqty = basket.__len__() baskettotal = basket.get_total_price() response = JsonResponse({'qty':basketqty, 'subtotal':baskettotal}) return response def basket_update(request): basket = Basket(request) if request.POST.get('action') == 'update-basket': product_id = int(request.POST.get('productid')) product_qty = int(request.POST.get('productqty')) basket.update(product=product_id, qty=product_qty) basketqty … -
Django database stored images showing only text descriptions
I am trying to store images on a database and then display them on a Django template. For some reason Django is only showing the alt (alternate - html attribute) instead of the actual image. This is the template {% extends "myapp/layout.html" %} {% load static %} {% block body %} <div class="sidenav"> <a href="{% url 'index' %}" id="active">Gallery</a> <a href="{% url 'about' %}">About</a> <a href="{% url 'contact' %}">Contact</a> </div> <div class="main"> <h2>Gallery</h2> {% for image in images %} <img class="gallery" src="{% static '{{image.image.url}}' %}" alt="{{image.description}}"> {% endfor %} </div> {% endblock %} This is my model from django.db import models # Create your models here. class Image(models.Model): image = models.ImageField(upload_to='images/') description = models.CharField(max_length=50) def __str__(self): return "Description of image: " + self.description This is what I'm seeing -
remove checkbox checked jquery
I show some checkbox to the user. When a user selects a checkbox, it is checked. If the user selects another checkbox after the first selection, the second checkbox will also be checked, but the first checkbox selected by the user will not be unchecked. I want to make sure that by selecting each check box, the previous check box is removed and several checkbox are not checked at the same time, that is, only one check box has the right to be selected. $(document).on('change','.filter-form',function(event){ event.preventDefault(); $.ajax({ type:'GET', url:'filter/', data : $(this).serialize(), dataType: 'json', success: function (data) { $('#product-main').html(data['form']); }, error: function (data) { alert("error" + data); } }); }); <form action="" class="filter-form"> <input type="checkbox" name="price" value="new"> <input type="checkbox" name="discount" value="discount"> <input type="checkbox" name="old" value="old"> </form> -
How to get options order from select in (Model)MultipleChoiceField?
I need to somehow get the order of options from (in my case) ModelMultipleChoiceField. By that I mean indexes of options which are obtainable through JavaScript easily. I guess that to do that I would need custom Field which I've already created. It uses custom widget which allows user to reorder options of the field's select. class DataTypeForm(forms.ModelForm): file = forms.FileField() headers = OrderedModelMultipleChoiceField(queryset=Header.objects.none()) class Meta: model = DataType fields = ("file", "headers") def __init__(self, *args, **kwargs): super(DataTypeForm, self).__init__(*args, **kwargs) self.fields["headers"].queryset = Header.objects.filter(data_type=self.instance) class OrderedModelMultipleChoiceField(forms.ModelMultipleChoiceField): widget = OrderableSelectMultiple class OrderableSelectMultiple(forms.SelectMultiple): template_name = "django/forms/widgets/orderable_select.html" class Media: css = { "all": ("orderable-select-multiple.css",), } js = ("orderable-select-multiple.js",) How can I get access to those properties? -
why django channels is not working on server?
i create a django websocket chat app with django-channel and that is working in localhost very well ,but when i run it on the server with daphne and nginx is not working . since i dont have any error in journalctl -u daphne and journalctl -u nginx i think my nginx config has a problem this is nginx config in sites-available and also linked in sites-enabled : server { listen 80; server_name {DOMAIN-OR-IP}; location /ws/ { proxy_pass http://0.0.0.0:9000; proxy_http_version 1.1; proxy_read_timeout 86400; proxy_redirect off; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location = /favicon.ico { access_log off; log_not_found off; } location /static_in_env/ { root /home/mhfd/newblog17/blog23; } location / { include proxy_params; proxy_pass http://unix:/home/mhfd/newblog17/blog23/blog23.sock; } } and this is config of daphne.service in systemd: [Unit] Description=daphne daemon After=network.target [Service] User={USER} Group=www-data WorkingDirectory={PROJECT-DIRECTORY} ExecStart={VIRTUAL-ENVIRONMENT-ADDRESS}/bin/daphne --bind 0.0.0.0 --port 9000 --verbosity 0 {PROJECT-NAME}.asgi:application [Install] WantedBy=multi-user.target i got no error but websocket chat (send and recieve) is not working? error image -
"ValueError: I/O operation on closed file" when reading CSV file from form data in Django
I want website users to be able to upload a CSV file to my webpage. The file is uploaded through a form with a FileField. I overrode the is_valid method of the FormField to check whether the file has a CSV extension or not. If the form is valid, I want to read the lines of the CSV and save them to a model. The is_valid method works well. But when I try to execute the code following the is_valid condition I run into "ValueError: I/O operation on closed file". Views.py def upload_file(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): csv_processor(form.cleaned_data['csv_file']) #messages.success(request, 'Archivo recibido para procesamiento') return HttpResponseRedirect(reverse('home_page')) else: form = UploadFileForm() return render(request, 'products/csv_upload_page.html', {'form': form}) csv_processor function def csv_processor(csv_file): csv_object = TextIOWrapper(csv_file, encoding='utf-8-sig') reader = csv.reader(csv_object) # Code to read lines follows here forms.py class UploadFileForm(forms.Form): csv_file = forms.FileField(label = 'Adjunte archivo csv', validators= [csv_content_validator]) def csv_content_validator(csv_file): if not csv_file.name.endswith('.csv'): raise ValidationError('Archivo debe tener extension csv') return True csv_object = TextIOWrapper(csv_file, encoding='utf-8-sig') reader = csv.reader(csv_object) first_row = next(reader) headers = ['SKU','Price'] # Check if column names match desired names for header_index in range(len(headers)): # Check if first row of the CSV file contains correct names … -
django.db.utils.OperationalError: foreign key mismatch - "Entry_returncylinder" referencing "Entry_cylinderentry"
Getting following error even after I have cleared all migrations.All was working fine until I tried to primary_key to my Cylinderentry model later on I removed but still it displays "django.db.utils.OperationalError: foreign key mismatch - "Entry_returncylinder" referencing "Entry_cylinderentry" " when I run py manage.py makemigrations it displays: You are trying to add a non-nullable field 'id' to cylinderentry without a default; we can't do that (the database needs something to populate existing rows).splays following : or when I run py manage.py migrate it displays: django.db.utils.OperationalError: foreign key mismatch - "Entry_returncylinder" referencing "Entry_cylinderentry" here is all models: from django.db import models from django.utils import timezone from django.urls import reverse # Create your models here. class CylinderEntry(models.Model): stachoice=[ ('Fill','fill'), ('Empty','empty') ] substachoice=[ ('Available','availabe'), ] cylinderId=models.CharField(max_length=50,unique=True) gasName=models.CharField(max_length=200) cylinderSize=models.CharField(max_length=30) Status=models.CharField(max_length=40,choices=stachoice,default='fill') Availability=models.CharField(max_length=40,choices=substachoice,default="available") EntryDate=models.DateTimeField(default=timezone.now) def get_absolute_url(self): return reverse('cylinderDetail',args=[(self.id)]) def __str__(self): return self.cylinderId class IssueCylinder(models.Model): cylinder=models.OneToOneField('CylinderEntry',on_delete=models.CASCADE) userName=models.CharField(max_length=60) issueDate=models.DateTimeField(default=timezone.now) def save(self,*args,**kwargs): if not self.pk: CylinderEntry.objects.filter(cylinderId=self.cylinder.cylinderId).update(Availability=('issued')) super().save(*args,**kwargs) def __str__(self): return self.userName class ReturnCylinder(models.Model): rechoice=[ ('fill','Fill'), ('empty','Empty') ] reav=[ ('Yes','yes'), ('No','no') ] cylinder=models.ForeignKey('CylinderEntry',on_delete=models.CASCADE) user=models.ForeignKey('IssueCylinder',on_delete=models.CASCADE) status=models.CharField(max_length=20,choices=rechoice) returnDate=models.DateTimeField(default=timezone.now) Availability=models.CharField(max_length=5,choices=reav) def save(self,*args,**kwargs): if not self.pk: IssueCylinder.objects.get(userName=self.user.userName).delete() if self.status=='yes' or self.status=='Yes': CylinderEntry.objects.get(cylinderId=self.cylinder.cylinderId).update(Availability=('available')) else: CylinderEntry.objects.get(cylinderId=self.cylinder.cylinderId).delete() super().save(*args,**kwargs) def __str__(self): return self.cylinder I don't where I m missing. Help!! -
mobile number standardization
You are given mobile numbers. Sort them in ascending order then print them in the standard format shown below: +91 xxxxx xxxxx The given mobile numbers may have +91,91 or 0 written before the actual digit number. Alternatively, there may not be any prefix at all. -
Has decompyle3 started to provide support for Python 3.9?
I forgot to add .gitignore in my repository root of my Python Django Project and I committed the code to my github repository. Now the root folder contains __pycache__, where all the compiled python files are located. I tried looking at, how to decompile the files and found the required resource uncompyle6 on PyPI. However, it works for Python 2.4 - 3.8. In addition, there is a Python decompiler decompyle3 for Python 3.7 - 3.8 which is stripped down from uncompyle6. But the version of Python I have been using all along is Python 3.9. Is there a way I can get around this and be able to solve my problem of decompiling my .py files anyhow so I can get the earlier project structure that I require? -
how can i retrieve and save latitiude and longitude from django-mapbox-LocationField?
i careate a django models with mapbox-locationfield : from mapbox_location_field.models import LocationField class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.SET_NULL ,blank=True,null=True) location = LocationField(null=True, blank=True) latitude = models.DecimalField(max_digits=20,decimal_places=18,null=True, blank=True) longitude = models.DecimalField(max_digits=20,decimal_places=18,null=True, blank=True) def __str__(self): return self.store_name def save(self,*args, **kwargs): if self.location: self.latitude = self.location.y self.longitude = self.location.x super(Profile,self).save(*args, **kwargs) i want to save latitude and longitude but i got this error: 'tuple' object has no attribute 'y' -
I cannot install django onto macos using pip
I'm new to python and I'm trying to install Django onto my MacBook. I am following the documentation on the site from https://docs.djangoproject.com/en/3.2/topics/install/#installing-official-release using $ python -m pip install Django but I get this error message. Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 174, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/Library/Python/2.7/site-packages/pip-21.0.1-py2.7.egg/pip/__main__.py", line 21, in <module> from pip._internal.cli.main import main as _main File "/Library/Python/2.7/site-packages/pip-21.0.1-py2.7.egg/pip/_internal/cli/main.py", line 60 sys.stderr.write(f"ERROR: {exc}") ^ SyntaxError: invalid syntax I'm not sure what the issue is. I might have a bugged version of pip. I'm not sure. Like I said I'm fairly new to all this so help would really be appreciated. Thank you -
Security in django multi tenants and django.contrib.sessions
I'm working with django multi tenancy package, and i would like to know if are there any guidelines on using django-tenants in a secure manner? or ant good practices I can think of at least one issue by which using django-tenants could lead to a security vulnerability. By having 'django.contrib.sessions' in SHARED_APPS, can't a user in one sub-domain/tenant impersonate a user in some other sub-domain/tenant? While I am not sure if my guess is correct, can some one help because it's my first experience in multi tenancies -
how can i change the format of datetime that django is sending to frontend?
model.py class DateTest(models.Model): date_created = models.DateTimeField(auto_now_add=True) view.py def getdate(request): dates = DateTest.objects.filter(product=pid).values('date_created') da=list(dates) print(da) return JsonResponse({'reviews':da}) Expected output: [{ 'date_created': datetime.datetime(May 1, 2021, 5:37 p.m.)}] Actual output: [{'date_reviewed': datetime.datetime(2021, 5, 1, 13, 2, 12, 404779, tzinfo=<UTC>)}] -
Loading pre-existing data into Django project
I have a pre-existing db file 'sample.db' in sqlite3 format that I'm trying to import into my Django project. I've already added it to the settings.py file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'sample': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'sample.db', } I was able to generate the model.py in my application folder using inspectdb. I have run makemigrations and migrate and everything seems to be fine. I try to get some data in my views.py: obj = table_name.objects.get(id=1) Then I start the server: python manage.py runserver, and try to load a page at http://127.0.0.1:8000/ It displays an error message saying: NameError at / Name table_name is not defined What did I miss? Thank you! -
should i keep my custom user model in shared apps?
I'm working with django multi tenancy package, and I have created my own custom user models called users. just i would like to know if i should keep my custom user model, with shared apps or with tenant apps? my second question is related the first one : should i let those apps bellow in tenant apps also or just in shared apps: i'm talking about those exactly : SHARED_APPS = [ 'django_tenants', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # My custom user model # 'users', -
filter category Django
I want to make a button to filter product by category.. Example Salad or Meat. Without Model ProductAtribuut im able to do it, but now i added the model, so im real confused how i can get the data of a Foreign Key inside a Foreign Key ProductAtribuut -> Product(FK) -> Categorie(FK) Models.py class Categorie(models.Model): naam = models.CharField(max_length=150,db_index=True) slug = models.SlugField(unique=True) class MPTTMeta: order_insertion_by = ['naam'] class Meta: ordering=('-naam',) def __str__(self): return self.naam def get_absolute_url(self): return reverse('JavaKitchen:product_by_categorie', args=[self.slug]) @property def get_products(self): return Product.objects.filter(categorie__naam=self.naam) class Groente(models.Model): groente = models.CharField(max_length=100) def __str__(self): return self.groente class Vlees(models.Model): vlees = models.CharField(max_length=100) def __str__(self): return self.vlees class Product(models.Model): slug = models.SlugField(unique=True, primary_key=True) titel = models.CharField(max_length=200) beschrijving = models.TextField(blank=True, null=True) categorie = models.ForeignKey(Categorie, on_delete=models.CASCADE) class Meta: ordering=('-titel',) def __str__(self): return self.titel def get_title_uppercase(self): return self.titel.upper() def get_absolute_url(self): return reverse('JavaKitchen:product_detail',args=[self.id,]) class ProductAtribuut(models.Model): def groente(): return Groente.objects.filter(groente='geen').first() def vlees(): return Vlees.objects.filter(vlees='geen').first() product = models.ForeignKey(Product, on_delete=models.CASCADE, blank=False) groente = models.ForeignKey(Groente, on_delete=models.CASCADE, default=groente) vlees = models.ForeignKey(Vlees, on_delete=models.CASCADE, default=vlees) prijs = models.FloatField(default=0) afbeelding = models.ImageField(blank=True, upload_to='gerechten/') #later upgrade.. zichtbaar = models.BooleanField(default=True) def __str__(self): return self.product.titel def image_tag(self): return mark_safe('<img src="/media/%s" width="80" height="auto" />' % (self.afbeelding)) image_tag.short_description = 'Image' Views.py def product_list(request,categorie_slug=None): categorie = None javakitchen = JavaKitchen.objects.get(id=1) openings_tijden = Openings_tijden.objects.all() categories … -
How to add style to base.html: Django framework?
file structure: app/template/base.html app/static/css/base.css I have created the base.html to contain the header, which I am importing to the other HTML pages to keep it the same throughout the website. And I want to style this header as well, so I am trying to link a base.css to my base.html, but no luck. Things which i have tried are : adding inline css, adding external css,adding internal css, clearing the cache, adding a block. code in base.html: {%load static%}<html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="{% static 'static/css/base.css' %}"> </head> <body> <nav> <button id="myButton" >Home</button> <button id="aboutButton" >About</button> <button id="contactButton" >Contact</button> </nav> {% block content %} {% endblock content %} <footer> <p>this is footer</p> </footer> <script type="text/javascript"> document.getElementById("myButton").onclick = function () { location.href = "{% url 'home' %}"; }; document.getElementById("aboutButton").onclick = function () { location.href = "{% url 'about' %}"; }; document.getElementById("contactButton").onclick = function () { location.href = "{% url 'contact' %}"; }; </script> </body> </html> that's my base.html code, which i want to link with base.css: .header { padding: 60px; text-align: center; background: #1abc9c; color: white; } .button { background-color: #4CAF50; /* Green */ border: none; color: white; … -
Restructure the following function for both robust functionality and maintainability
i have a python script wants to restructure for better functionality and maintainability. Suggestions are welcomed. The resulting return values in different scenarios should be constant. Code is pseudo code and does not have to run # Mock imports - assume these modules are imported import query_objs import enums from django import transaction import update_obj_in_db import api_client def rest_endpoint(input): qs = query_objs(id=input.id) obj = qs.get() obj.name = input.name + "_object" obj.save() if not qs.exists(): return 404 if len(input.name) > 5: return 422 if input.type != "bank_account": return 422 obj.type = enums.Types.BANK_ACCOUNT obj.save() with transaction.atmoic(): response = api_client.post(obj, input) if response.status != 200: return 500 update_obj_in_db(obj, input.details) return 200 -
Search filters that search/recommend similar for misspells as well Django REST framework
I have a Django REST app, what I want to do is: Make an API endpoint when we use ?search="India" it works great using the django-filters. I want it to work(can suggest some results if not finding the exact item) even for ?search="Inda" which is not spelled correctly by user error. How do I approach this issue? Do we use ML for this? I'm new to ML and am not aware of any ML things that might help me here. Any suggestions appreciated! -
Setting Cache-Control in Nginx / Gunicorn / Django
I am trying to set a Cache-Control in my Django/Gunicorn/Nginx project. However, all static files do not have any expiration. Here's how I try to set it. location ~* \.(?:js|css|png|jpg|jpeg|gif|svg|ico)$ { expires 1y; add_header Cache-Control "public, no-transform"; } I have also tried another way but it still didn't work: # Expires map map $sent_http_content_type $expires { default off; text/html epoch; text/css max; application/javascript max; ~image/ max; } server { listen 80 default_server; listen [::]:80 default_server; expires $expires; -
How to Store Image File in Django from html form using Post request?
I am working on a project that require an profile pic. I created a Model in Django UserProfile class UserProfile(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True) image = models.ImageField() adress = models.CharField(default='', max_length=150, blank=True) cnic = models.IntegerField(null=True) contact = models.IntegerField(null=True) city = models.CharField(max_length=50, null=True) about = models.CharField(max_length=50, null=True) location = models.CharField(max_length=150, null=True) subscriptions = models.IntegerField(null=True) rating = models.IntegerField(null=True) I am currently fetching data from HTML <form action="/users/profile/" method="POST" style="display: contents;"> {% csrf_token %} <div class="col-md-3 border-right"> <div class="d-flex flex-column align-items-center text-center p-3 py-5"> {% if profile.image %} <img class="rounded-circle mt-5" src="/media/{{profile.image}}" style="width: 200px;max-height: 300px;" id='image'> {% else %} <img class="rounded-circle mt-5" src="https://image.shutterstock.com/image-vector/house-not-available-icon-flat-260nw-1030785001.jpg" style="width: 200px;max-height: 300px;" id='image'> {% endif %} <label for="upload-photo" class="uploadImgLabel btn btn-outline-danger w-75">Browse</label> <input type="file" name="photo" id="upload-photo" required /> <span class="font-weight-bold">{{user}}</span><span class="text-black-50">{{user.email}}</span><span> </span> </div> All the other field is working correctly and I can visualize data by printing in views.py if request.method == 'POST': photo = request.POST.get('photo') fname = request.POST.get('firstname') lastname = request.POST.get('lastname') contact = request.POST.get('contact') address = request.POST.get('address') email = request.POST.get('email') country = request.POST.get('country') cnic = request.POST.get('cnic') city = request.POST.get('city') user = User.objects.get(username=request.user) user.first_name = fname user.last_name = lastname user.email = email user.save() obj = models.UserProfile.objects.get(user=request.user) obj.adress = address # obj.image = photo, <---- Here is the … -
application error django deployment heroku
I am trying to deploy my app to heroku and the deployment does not show me any error but when I try to load the website I get and Application error: An error occurred in the application and your page could not be served. I tried running heroku logs --tail as suggested and I get this traceback: app[web.1]: self.load_wsgi() app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi app[web.1]: self.wsgi = self.app.wsgi() app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/base.py", line 67, in wsgi app[web.1]: self.callable = self.load() app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 58, in load app[web.1]: return self.load_wsgiapp() app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp app[web.1]: return util.import_app(self.app_uri) app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/gunicorn/util.py", line 359, in import_app app[web.1]: mod = importlib.import_module(module) app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load app[web.1]: File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked app[web.1]: ModuleNotFoundError: No module named 'api.wsgi' app[web.1]: [2021-05-01 17:13:14 +0000] [8] [INFO] Worker exiting (pid: 8) app[web.1]: [2021-05-01 17:13:14 +0000] [4] [WARNING] Worker with pid 8 was terminated due to signal 15 app[web.1]: [2021-05-01 17:13:14 +0000] [4] [INFO] Shutting down: Master app[web.1]: [2021-05-01 17:13:14 +0000] [4] [INFO] Reason: Worker failed to boot. … -
Django messes up the order of load tags?
I am using navbar of this project, in my django project (Bootstarp 4.6). Here is the code: Base.html : {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="icon" href="{% static 'images/favicon.png' %}"> <!--Bootstarp CSS--> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous"> <!--Bootstarp CSS ENDs--> <!--CSS--> {% block css %}{% endblock %} <!--CSS ENDs--> <title>{% block title %}{% endblock %}</title> </head> <body> <!--Navbar--> {% include 'quicky/navbar.html' %} <!--Navbar ENDs--> {% block content %} {% endblock %} <!--Bootstrap JS--> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns" crossorigin="anonymous"></script> <!--Bootstrap JS ENDs--> <!--JS--> {% block js %}{% endblock %} <!--JS ENDs--> </body> </html> Navbar.html : {% load static %} {% block css %} <link rel="stylesheet" href="{% static 'css/quicky/navbar.css' %}"> {% endblock %} <nav class="navbar navbar-expand-lg fixed-top navbar-dark bg-dark"> <a class="navbar-brand mr-auto mr-lg-0" href="#">Offcanvas navbar</a> <button class="navbar-toggler p-0 border-0" type="button" data-toggle="offcanvas"> <span class="navbar-toggler-icon"></span> </button> <div class="navbar-collapse offcanvas-collapse" id="navbarsExampleDefault"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Dashboard <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Notifications</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Profile</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Switch account</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Settings</a> <div class="dropdown-menu" aria-labelledby="dropdown01"> <a class="dropdown-item" href="#">Action</a> … -
Can someone make me understand what the issue really is here? new to django
django==3.2 AssertionError at /api/content/coordinator/read/0 The request argument must be an instance of django.http.HttpRequest, not content_delivery.view.coordinator.Coordinator_View. class Coordinator_View(object): @staticmethod def run(request): obj = Coordinator_View() return obj.create(request) # this is where the actual error happens @api_view(['POST']) def create(self, request): ...