Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add and Update Post from custom html forms in Django
I've created a custom HTML form for my model, just like I want to add a post from the front-end. I already created a page with the name add-post.html add-post.html <form method="POST" action=""> {% csrf_token %} <input name="title" type="text"> <textarea spellcheck="false" name="description"></textarea> <input type="file" name="image" @change="fileName" multiple /> <select required name="priority"> <option value="Low" selected>Low</option> <option value="Medium">Medium</option> <option value="High">High</option> </select> <input type="checkbox" name="on_hold"> <button type="submit">Add ToDo</button> </form> model.py class Todo(models.Model): title = models.CharField(max_length=100) image = models.ImageField(null=True, blank=True, upload_to='todo/images/') description = RichTextField() Low, Medium, High = 'Low', 'Medium', 'High' priorities = [ (Low, 'Low'), (Medium, 'Medium'), (High, 'High'), ] priority = models.CharField( max_length=50, choices=priorities, default=Low, ) on_hold = models.BooleanField(default=False) forms.py class TodoCreationForm(forms.ModelForm): class Meta: model = Todo fields = ('title','image','description','priorities','priority','on_hold') No, I want to use the above custom HTML form to post data and save it to this model database. instead of using {% form.as_p %} And I also created a particular page to update this post from the front-end but don't know how to make it work. Can you please guide me on how can I save data from the custom form and also update it from the custom form? Appreciate your response :) -
Getting JSONDecodeError from django
I'm getting trouble with requests on local developed server using Django Here are my codes veiws.py from django from django.shortcuts import render from django.views import View import json # Create your views here. class RequestView(View): template_name='request.html' def get(self, request): body_unicode = request.body.decode('utf-8') data = json.loads(body_unicode) data_value =data['key'] return render(request, self.template_name, {'content':data_value}) def post(self, request): body_unicode = request.body.decode('utf-8') data = json.loads(body_unicode) data_value = data['key'] return render(request, self.template_name, {'content': data_value}) request.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {{ conetent }} </body> </html> request on local import requests >>> data = {'key':'value'} >>> url = 'serverip/request' >>> res = requests.get(url, data) I want to get HttpResponse filled with data['key'] on url!! and this is an error message Internal Server Error: /request Traceback (most recent call last): File "/home/django/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 7, in inner response = get_response(request) File "/home/django/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, n _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/django/venv/lib/python3.7/site-packages/django/views/generic/base.py", line 70, i view return self.dispatch(request, *args, **kwargs) File "/home/django/venv/lib/python3.7/site-packages/django/views/generic/base.py", line 98, i dispatch return handler(request, *args, **kwargs) File "/home/django/saferoute/request/views.py", line 9, in get data = json.loads(body_unicode) File "/usr/lib/python3.7/json/__init__.py", line 348, in loads return _default_decoder.decode(s) File "/usr/lib/python3.7/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python3.7/json/decoder.py", line 355, … -
DRF PUT on Viewset/Serializer does not fire post_save signal on model instance
I have the following DRF viewset: class MyViewSet(RetrieveModelMixin, ListModelMixin, UpdateModelMixin, GenericViewSet, CreateModelMixin, DestroyModelMixin): serializer_class = MySerializer queryset = My.objects.all() lookup_field = "uuid" The following Serializer: class MySerializer(serializers.ModelSerializer): class Meta: model = My fields = [ 'uuid', 'name' ] I have a signal stored in signal.py in the app @receiver(post_save, sender=My) def my_updated(sender, instance, created, **kwargs): if not created: print('MySignal Fired') The signal is imported in apps.py. The signal is working when I open a terminal and run the .save() method on a instance. The app is also declared in the django config. Any ideas? BTW. when executing the .PUT on the API it saves everything nicely in the DB. So the api is doing it's work. Not sure why the signal is not firing though. -
Add date and time manully in django
I want to add date and time manually for required task but when i add date & time and submit it show error of null field. Model.py from django.contrib.auth.models import User from django.db import models class TaskList(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) task = models.CharField(max_length=100, null=False, blank=False) complete = models.BooleanField(default=False) datetimepicker1 = models.DateTimeField(auto_now_add=False) View.py def post(self, request): if SESSION_KEY in self.request.session: try: data = self.request.POST.get task_list = TaskList( user_id=request.session[SESSION_KEY], task=data('task'), datetimepicker1=data('datetimepicker1') ) task_list.save() return redirect('todolist') except Exception as e: return HttpResponse('failed {}'.format(e), 500) Template <form method="post"> {% csrf_token %} <label for="task"> <input name="task" placeholder="add today's task" id="task" required> </label> <div class="input-group date" id="datetimepicker1" data-target-input="nearest"> <label for="datetimepicker1"> <input class="form-control datetimepicker-input" data-target="#datetimepicker1" type="text" id="datetimepicker1" required> </label> <div class="input-group-append" data-target="#datetimepicker1" data-toggle="datetimepicker"> <div class="input-group-text"><i class="fa fa-calendar"></i></div> </div> </div> <button type="submit">add</button> </form> -
Django Column Data Gets Encoded
I'm using raw query to get data from server and data that I receive from one specific column gets converted to bytes, like so: "date": "b'2021-02-09'" Column itself: CASE WHEN some.column IS NULL THEN DATE(some.other_column) ELSE DATE(some.column) END AS "date", I believe that DATE() is getting messed up by Python somehow, cause I have exact same CASE column below, but with TIME() and that column outputs data as str, not bytes My question is: How do I bypass that behavior and receive data from that column as str, or, if possible - how do I decode column data in serializer? -
Django - Saving data without using input fields/forms
I am a novice, apologies if this question seems silly. I need to save some data into MySQL database. There are no input fields. The user should click a button, and a table is updated. The data to be saved is two foreign keys and a PK. Here is my model class Bids(models.Model): id=models.AutoField(primary_key=True) userid = models.ForeignKey(Writer, on_delete=models.DO_NOTHING, related_name='userid ') orderid = models.ForeignKey(Orders, on_delete=models.DO_NOTHING, related_name='orderids') biddatetime=models.DateTimeField(auto_now_add=True) I have tried writing several functions to save these fields into table bids but no joy so far. Hers's a sample. def saveBid(request): if request.method!= "POST": return HttpResponse("Action Not Allowed") else: biddatetime=request.POST.get('biddatetime') bids= Bids(biddatetime=biddatetime) order=Orders(id=id) user= CustomUser() user.save() bids.save() Pls assist -
Django, Djoser social auth : State could not be found in server-side session data. status_code 400
i'm implementing an auth system with django and react. The two app run respectively on port 8000, 3000. I have implemented the authentication system using the Djoser package. This package use some dependencies social_core and social_django. Everything seems to be configured ok. I click on login google button...I'm redirected to the google login page and then back to my front-end react app at port 3000 with the state and code parameters on the url. At this point I'm posting those parameters to the backend. The backend trying to validate the state checking if the state key is present in the session storage using the code below from (social_core/backends/oauth.py) def validate_state(self): """Validate state value. Raises exception on error, returns state value if valid.""" if not self.STATE_PARAMETER and not self.REDIRECT_STATE: return None state = self.get_session_state() request_state = self.get_request_state() if not request_state: raise AuthMissingParameter(self, 'state') elif not state: raise AuthStateMissing(self, 'state') elif not constant_time_compare(request_state, state): raise AuthStateForbidden(self) else: return state At this point for some reasons the state session key is not there..and I receive an error saying that state cannot be found in session data ( error below ) {"error":["State could not be found in server-side session data."],"status_code":400} I recap all the … -
400 Bad Request The plain HTTP request was sent to HTTPS port, while Deploying Django to AWS with Docker and Let's Encrypt
I am following the "Django on Docker Series" series by testdrivenio for deploying a project into a new domain. I am using Django as backend but when I try to access the backend url via the port it showing via docker ps command i.e., http://0.0.0.0:443/ I get the following error, This is the docker-compose file I am using version: '3.7' services: web: build: context: ./myprojectname dockerfile: Dockerfile.staging image: 789497322711.dkr.ecr.us-east-3.amazonaws.com/myprojectname-staging:web command: gunicorn myprojectname.wsgi:application --bind 0.0.0.0:8005 volumes: - static_volume:/home/myprojectname_staging/web/static - media_volume:/home/myprojectname_staging/web/media expose: - 8000 env_file: - ./.env.staging frontendimage: container_name: frontendimage image: 789497322711.dkr.ecr.us-east-3.amazonaws.com/myprojectname-staging:frontendimage stdin_open: true build: context: . dockerfile: frontend/Dockerfile.staging # volumes: # - type: bind # source: ./frontend # target: /usr/src/frontend # - '.:/usr/src/frontend' # - '/usr/src/frontend/node_modules' ports: - '1337:30' environment: - CHOKIDAR_USEPOLLING=true depends_on: - web nginx-proxy: container_name: nginx-proxy build: ./myprojectname/nginx image: 789497322711.dkr.ecr.us-east-3.amazonaws.com/myprojectname-staging:nginx-proxy restart: always ports: - 443:443 - 80:80 volumes: - static_volume:/home/myprojectname_staging/web/staticfiles - media_volume:/home/myprojectname_staging/web/mediafiles - certs:/etc/nginx/certs - html:/usr/share/nginx/html - vhost:/etc/nginx/vhost.d - /var/run/docker.sock:/tmp/docker.sock:ro depends_on: - web nginx-proxy-letsencrypt: image: jrcs/letsencrypt-nginx-proxy-companion env_file: - .env.staging.proxy-companion volumes: - /var/run/docker.sock:/var/run/docker.sock:ro - certs:/etc/nginx/certs - html:/usr/share/nginx/html - vhost:/etc/nginx/vhost.d depends_on: - nginx-proxy volumes: static_volume: media_volume: certs: html: vhost: My Nginx directory └── nginx ├── Dockerfile ├── custom.conf └── vhost.d └── default Dockerfile FROM jwilder/nginx-proxy COPY vhost.d/default /etc/nginx/vhost.d/default COPY custom.conf /etc/nginx/conf.d/custom.conf … -
Why I get error-404 while I try to add new position in admin-panel Django?
All's working for a local version. But on production-server I get 404-error (Page not found) when I try to add new position in admin-panel. I suppose that I have problems with image-fields. And I think that I maked errors for BASE_DIR and MEDIA_ROOT. urlpatterns = [ path('admin/', admin.site.urls), path('', include('pharmacy.urls')), path('articles/', include('articles.urls', namespace='articles')), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In a app: urlpatterns = [ path('', views.index, name='main'), path('about', views.about, name='about'), path('contact', views.contact, name='contact'), ] My Model: class Product(models.Model): title = models.CharField(max_length=200, verbose_name='Название') description = models.TextField(max_length=2000, verbose_name='Описание', blank=True, null=True) pic = models.ImageField(verbose_name='Картинка', upload_to='pharmacy/products') is_published = models.BooleanField(verbose_name='Опубликовано', default=True) def __str__(self): return self.title class Meta: verbose_name = 'Продукт' verbose_name_plural = 'Продукты' serrings.py: BASE_DIR = Path(__file__).resolve(strict=True).parent.parent STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ BASE_DIR / "pharmacy/static", os.path.join(BASE_DIR, 'static'), ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') I'm attaching screenshot with my file structure. -
Python: How to call all objects of a class with their attributes in Django?
For some context, the class is meant to hold the metadata of the products, which are objects. Now, I would like to pass the objects to my template, in order to call its attributes. Here's my code in views.py: def prices(request): @attr.s class ProductMetadata: """ Metadata for a Stripe product. """ stripe_id = attr.ib() name = attr.ib() features: list = attr.ib() monthly_price = attr.ib() yearly_price = attr.ib() standard = ProductMetadata( stripe_id='example', name='Standard', features=[(True ,"Up to 1000 DMs"), (False, "Ludicrous mode"), (False, "Premium Support")], monthly_price = "month1", yearly_price = "year1" ) premium = ProductMetadata( stripe_id='example2', name='Premium', features=[(True ,"Up to 1000 DMs"), (True, "Ludicrous mode"), (False, "Premium Support")], monthly_price = "month2", yearly_price = "year2" ) business = ProductMetadata( stripe_id = "example3", name = 'Business', features=[(True ,"Up to 1000 DMs"), (True, "Ludicrous mode"), (True, "Premium Support")], monthly_price = 'month3', yearly_price = 'year3' ) return render(request, 'instagram_prices.html', {'products': ProductMetadata.all()}) How can I achieve this? Thanks! -
django api using generic views for deleting multiple objects
i'm trying to use django generic view. and i want to be able to delete multiple objects at the same time using the same view.for example delete all the 'femail' Employees in my model. i used the following code: from ..models import Employee from . import serializer from rest_framework import generics, status from rest_framework.response import Response from django.shortcuts import get_list_or_404, get_object_or_404 class EmployeeDeleteandUpdate(generics.UpdateAPIView): queryset = Employee.objects.filter(gender__startswith='femail') serializer_class = serializer.PostSerializer def delete(self, request, *args, **kwargs): myobj = get_object_or_404(Employee, gender=kwargs['gender']) myobj.delete() return Response("Femails deleted", status=status.HTTP_204_NO_CONTENT) and heres my url code: path('mydel/<str:gender>/', view.EmployeeDeleteandUpdate.as_view()), and also my model: class Employee(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) gender = models.CharField(max_length=10) national_code = models.CharField(max_length=11) personal_code = models.CharField(max_length=15) phone_number = models.CharField(max_length=11) address = models.CharField(max_length=50) married = models.BooleanField() age = models.IntegerField() wage = models.IntegerField() def __str__(self): return self.first_name but when i use delete method with following url in my django rest framework: http://127.0.0.1:8000/mydel/femail/ i get this error: client.models.Employee.MultipleObjectsReturned: get() returned more than one Employee -- it returned 2! can somebody help me with this problem please?? -
Limit access to views in Django based on account type
How to limit access to views in Django? My Account model is like this: class Account(AbstractBaseUser): ... account_type = models.PositiveSmallIntegerField(default=0, choices=ACCOUNT_TYPE_CHOICES) I want to use a custom decorator to all my views based on account type but I don't know where to start. Currently on my views, this is what I have done: @login_required(login_url='/login/') def dashboard(request, *args, **kwargs): if request.user.is_authenticated: if request.user.account_type == 1: return redirect('admin_page') else: .... But this one is very repetitive. -
Can't display images from models when debug=false
I have asked another question about the issue of displaying images from models. and It was because I didn't add media url to urlpatterns. But it turns out that it only works when I set debug=true in settings file, when I set debug=false, I got 404 error again, any expert here to help ? I need to set debug=false for production here my urls.py file from django.contrib import admin from django.urls import path from home import views as HomeViews from django.conf.urls import include, url from django.conf.urls.static import static from django.conf import settings import os urlpatterns = [ path('admin/', admin.site.urls), path('',HomeViews.index,name='home') ] if settings.DEBUG: urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my settings file from pathlib import Path import os import django_heroku import django # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'ws^pgf$%!=l8y#%^7anp$rl6*o4u9!86g-ba_uq9pcee=vc@13' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home', ] MIDDLEWARE … -
Django filter queryset only if variable is not null
I have a queryset it filter by 2 variables family = ModelsClass.objects.filter(foo=var1).filter(bar=var2) If var1 and var2 are not null everything work but var1 and var2 can be Null. In this case i need to exclude the Null one. For example, if var1 is Null it must filter only by var2 and the other way around. There is a way to insert an if condition inside the filter queryset or something else? TY -
Model method to generate the value for a parameter of an attribute
I want to create a method inside a model which can be called on a parameter of an attribute to populate it. I thought of doing it this way but it gives me an error NameError: name 'self' is not defined. class Host(User): class Meta: verbose_name = "Host" verbose_name_plural = "Hosts" def gen_path(self): path = 'static/{userdir}'.format(userdir=self.email) os.mkdir(path) return path hostpic = models.ImageField(verbose_name='Host Profile Image', upload_to=self.gen_path(), null=True) What could be a workaround for this? -
django.db.utils.DatabaseError: Error while trying to retrieve text for error ORA-01804
Q1. What versions are we using? Ans. Python 3.6.12 OS : CentOS 7 64-bit DB : Oracle 18c Django 2.2 cx_Oracle : 8.1.0 Q2. Describe the problem Ans. While running server with "python3 manage.py runserver" application is able to contact Oracle DB and show the Django Administration page and login also works. But when we access the application using the Apache (HTTPD) based URL over secure SSL port, we do see the Django page and the admin page as well but Login to Admin page with Internal server error. In the logs, we see "django.db.utils.DatabaseError: Error while trying to retrieve text for error ORA-01804" cx_oracle is otherwise able to connect to the database properly, another application is also using the same database behind the same httpd proxy and works fine Q3. Show the directory listing where your Oracle Client libraries are installed (e.g. the Instant Client directory). Is it 64-bit or 32-bit? Ans. 64-bit Q4. Show what the PATH environment variable (on Windows) or LD_LIBRARY_PATH (on Linux) is set to? LD_LIBRARY_PATH=/srv/vol/db/oracle/product/18.0.0/dbhome_1/lib:/lib:/usr/lib PATH=$ORACLE_HOME/bin:/srv/vol/db/oracle/product/18.0.0/dbhome_1/lib:$PATH Q5. Show any Oracle environment variables set (e.g. ORACLE_HOME, ORACLE_BASE). ORACLE_HOME=/srv/vol/db/oracle/product/18.0.0/dbhome_1 TNS_ADMIN=$ORACLE_HOME/network/admin NLS_LANG=AMERICAN_AMERICA.AL32UTF8 ORACLE_BASE=/srv/vol/db/oracle CLASSPATH=$ORACLE_HOME/jlib:$ORACLE_HOME/rdbms/jlib:$ORACLE_HOME/lib Any suggestions/help is highly appreciated. Thank you -
Django: How to get total cart item in ecommerce
I am trying to add the total item in the cart, but I am getting <property object at 0x000001CFFDED8228>: could anybody help? View.py class checkout(ListView): model = OrderItem template_name = 'product/checkout.html' def get_context_data(self, **kwargs): context = super(checkout, self).get_context_data(**kwargs) context['orderQty'] = Order.get_cart_items return context model.py class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null = True, blank=False) transaction_id = models.CharField(max_length= 200, null=True) def __str__(self): return str(self.id) @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum(item.quantity for item in orderitems) return total size_choices = (('small', 'S'), ('medium', 'M'), ('large', 'L')) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) date_added = models.DateTimeField(auto_now_add=True) quantity = models.IntegerField(default=0, blank=True, null=True) size = models.CharField(max_length= 200,choices= size_choices, default=0) @property def get_total(self): total = self.product.price *self.quantity return total template.html: <div class="row-1"> <div style="flex:2;"><strong>Total Items</strong>:<span style="float: right;">{{orderQty}}</span></div> <hr> <div style="flex:2;"><strong>SubTotal</strong>:<span style="float: right;">$387</span></div> <hr> <div style="flex:2; margin-top:10px"><strong>Shipping</strong><span style="float: right;">$54</span></div> <hr> </div> <div> <div style="flex:2; text-align:center"><h6>Total: $387</h6></div> <input id="form-button" class="btn btn-success btn-block" type="submit" value="Pay"> </div I believe these files contain the problem but from researching online I can't seem to pinpoint exactly what it is. The function based view of my website was working fine until I moved to class-based … -
image not uploading Django for loop and Bootstrap Card
I trying to upload image. I used Django for loop and inside it placed Bootstrap Card. Products {% for product in products %} {{product.name}} ${{product.price}} ORDER NOW {%endfor%} -
Show some readonly fields and a preview (not a field)
Django 3.1.6 class SvgFile( CreatedMixin, AltMixin, CommentMixin, models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) created = models.DateTimeField(auto_now_add=True, verbose_name=_("Creation date")) file = models.FileField(upload_to=svg_upload_to, verbose_name=gettext_lazy("SVG file"),) def preview(self): return mark_safe('<img width="100" src="{}" />'.format(self.file.url)) preview.short_description = gettext_lazy('Preview') preview.allow_tags = True class Meta: verbose_name = gettext_lazy("SVG file") verbose_name_plural = gettext_lazy("SVG files") class SvgFileForm( ModelForm): class Meta: model = SvgFile exclude = [] Could you help me understand how to show id, created and preview in edit view of Django admin site? -
How to configure django-db-multitenant?
I am trying to use django-db-multitenant and I am doing something wrong. I am getting error ('%s does not subclass db_multitenant.mapper.TenantMapper', 'demo.mapper.TenantMapper'). It would be great help if anyone can help me regarding this. -
Django : matching query does not exist
I am getting error while creating an instance of ModelForm in DJango. I am not always facing the issue but sometimes it work fine and sometimes it gives me error. ModelFOrm code : class ClientinfoForm(ModelForm): Account_Name = forms.CharField(disabled=True) class Meta: model = AccountDescription fields = ['Account_Name','short_Name','group_Master_Project_Code','account_Logo','vertical','client_Website','client_Revenue','Employee_Count','client_Industry_Segment','delivery_Manager_Mail','project_Manager_Mail'] labels = {'client_Revenue':'Client Revenue(in USD Billion)','vertical':'Industry Vertical'} help_texts = {'client_revenue' : '(In Billion USD)' } views.py code def save_client_info(request): fm = ClientinfoForm(request.POST, instance = AccountDescription.objects.get(Account_Name = acc_name),files = request.FILES or None) save_form(request,fm) def clientinfo(request): if request.user.is_authenticated: if request.method == 'POST': print("inside form") save_client_info(request) global s4_option s4_option = AccountDescription.objects.filter(Account_Name = acc_name).values('s4_data') s4_option = s4_option[0]['s4_data'] accdata = AccountDescription.objects.filter(Account_Name = acc_name) clientdata = ClientinfoForm(instance = AccountDescription.objects.get(Account_Name = acc_name)) return render(request, 'AccountData/ClientInfo.html',{'name' : 'clientinfo','form':clientdata,'acntdata':accdata,'content':editoption}) Sometimes, when I save it works perfectly fine but sometimes it give matching query doesn't exist. Let me know if more information is required. -
'CreateView' object has no attribute 'render_to_response'
I have this create view and it throws the error 'CreateView' object has no attribute 'render_to_response' urls.py path( "p/<int:id>/food/create", views.FoodCreateView.as_view(), name="food-create", ), views.py class FoodCreateView(BaseCreateView): template_name = "food_form.html" form_class = forms.FoodForm success_message = "successfully created" def get_queryset(self): return Food.all(#####) def get_success_url(self): return reverse( "food_list" ) am I lacking anything with the code? -
Django AttributeError at /upload/
When I'm trying to run my view.py, I get this error: 'list' object has no attribute 'name' at the fourth line of view.py that I have attached below. My app basically allows users to upload photos and save them after they are edited automatically. This error happens right after I click upload. forms.py class PhotoForm(forms.ModelForm): image = MultiImageField(min_num=1, max_num=20) class Meta: model = Post fields = ['name'] widgets = {'name': forms.HiddenInput()} views.py def photoform(request, *args, **kwargs): if request.method == "POST": form = PhotoForm(request.POST, request.FILES) if form.is_valid(): a = form.save() models.py class Post(models.Model): name = models.CharField(max_length=255, blank=True) uploaded_at = models.DateTimeField(auto_now_add=True, null=True) uuid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) I don't know if this helps, but here is what the error shows. -
How to store filtered data in excel in Django?
Made a view that pulls data from the model. Based on this data, the table in the template is filled. For each field of the table (model) added filtering based on django-filters. Faced the following problem, I need to save filtered data to excel. The problem is precisely in getting the filtered data, saving in excel is not a problem. My class based view: class RequestList(FilterView): template_name = 'MQueryboard/Requests/RequestList.html' filterset_class = Filter_Adjustments_view model = Adjustments paginate_by = 3 def get_queryset(self): filterset_class = Adjustments.objects.order_by('-dateadjustment') return filterset_class def get_context_data(self, *args, **kwargs): _request_copy = self.request.GET.copy() parameters = _request_copy.pop('page', True) and _request_copy.urlencode() context = super().get_context_data(*args, **kwargs) context['parameters'] = parameters return context def post(self, request): if request.method == 'POST': response = adjustments_to_excel(Adjustments.objects.all()) return response else: return render(request, 'MQueryboard/Requests/RequestList.html', {}) The adjustments_to_excel function - in order not to load the view, data is sent to the script to generate an Excel file. Here I do not understand how I can get the filtered queryset in the post function. Now, as a "stub" is the selection for all fields of the model. Please tell me how you can do this. I've been struggling with this question for a week, nothing has been working out yet. Thanks in … -
Can't display images from models of django
Since I have faced this problem many times and couldn't find a solution, I need help Here's my settings file. I've configured media root from pathlib import Path import os import django_heroku import django # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'ws^pgf$%!=l8y#%^7anp$rl6*o4u9!86g-ba_uq9pcee=vc@13' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'testimage.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], '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', ], }, }, ] WSGI_APPLICATION = 'testimage.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = …