Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i want to save my check box value of my form to my Django database
I am using form in my Django Web app and The form consist of checkboxes but when the the check boxes are marked true and the form is submitted the check box chenges are not marked in the databaseenter image description here here is my models.py my Help model is not sending the check box values to Database # Create your models here. class Contact(models.Model): name = models.CharField(max_length=122) email = models.CharField(max_length=122) phone = models.CharField(max_length=12) desc = models.TextField() date = models.DateField() def __str__(self): return self.name class Help(models.Model): name = models.CharField(max_length=122) address = models.TextField() phone = models.CharField(max_length=12) bed = models.BooleanField("bed",default=False) oxygen = models.BooleanField("oxygen",default=False) plasma = models.BooleanField("plasma",default=False) date = models.DateField() def __str__(self): return self.name HERE IS MY views.py from django.shortcuts import render import requests from datetime import datetime from webapp.models import Contact from webapp.models import Help from django.contrib import messages # Create your views here. def index(request): return render(request,'index.html') def contact(request): if request.method == "POST": name = request.POST.get('name') email = request.POST.get('email') phone = request.POST.get('phone') desc = request.POST.get('desc') contact =Contact(name=name,email=email,phone=phone,desc=desc,date=datetime.today()) contact.save() messages.success(request,'Your message has been sent') return render(request,'contact.html') def help(request): if request.method == "POST": name = request.POST.get('name') address = request.POST.get('address') phone = request.POST.get('phone') plasma = request.POST.get('plasma') oxygen = request.POST.get('oxygen') bed = request.POST.get('bed') if plasma … -
How do I connect a Django app to Postgresql inside Docker?
I'm trying to run a django app from Docker container but I'm facing issues when connecting to a Postgresql -database. This is my docker-compose.yml: version: "3.8" services: app: build: . environment: PYTHONUNBUFFERED: 1 DATABASE_URL: postgres://$DATABASE_USER:$DATABASE_PASSWORD@$DATABASE_HOST:$DATABASE_PORT/$DATABASE_NAME env_file: .env volumes: - .:/data ports: - 8000:8000 image: test:django container_name: tes_container command: python manage.py runserver 0.0.0.0:8000 depends_on: - db db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data env_file: .env environment: - POSTGRES_DB=$DATABASE_NAME - POSTGRES_USER=$DATABASE_USER - POSTGRES_PASSWORD=$DATABASE_PASSWORD container_name: postgres_db This is my .env: DEBUG=on SECRET_KEY=mysecret # Database settings DATABASE_NAME=postgres DATABASE_USER=postgres DATABASE_PASSWORD=postgres DATABASE_HOST=localhost DATABASE_PORT=5432 Every time I run docker-compose run --rm app python manage.py migrate I get this error: psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Cannot assign requested address Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? The above exception was the direct cause of the following exception: .... django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Cannot assign requested address Is the server running on host "localhost" (::1) … -
How can I solve this : JSONDecodeError at /update_item Expecting value: line 1 column 1 (char 0)
This is my views.py How can i solve this.Anyone please help!!! JSONDecodeError at /update_item Expecting value: line 1 column 1 (char 0) def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('Action:', action) print('Product:', productId) customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(order=order, product=product) if action == 'add': orderItem.quantity = (orderItem.quantity + 1) elif action == 'remove': orderItem.quantity = (orderItem.quantity - 1) orderItem.save() if orderItem.quantity <= 0: orderItem.delete() return JsonResponse('Item was added', safe=False) url = 'http://httpbin.org/status/200' r = requests.get(url) if 'json' in r.headers.get('Content-Type'): js = r.json() else: print('Response content is not in JSON format.') js = 'spam' and this is my cart.js I hope anybody will help me If you want to check my whole project code I am ready to show var updateBtns = document.getElementsByClassName('update-cart') for (i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'Action:', action) console.log('USER:', user) if (user == 'AnonymousUser'){ addCookieItem(productId, action) }else{ updateUserOrder(productId, action) } }) } function updateUserOrder(productId, action){ console.log('User is authenticated, sending data...') var url = 'update_item' fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'productId':productId, 'action':action}) }) .then((response) => { return response.json(); }) … -
Django CORS requests creating 403 Forbidden Error only on server
I have an application which uses Django for the backend and react for the frontend so I setup django-cors-headers. When I tested the application locally with the settings I added, I had no issues. But I deployed to my server, I kept getting 403 error on API requests (except GET requests). Below is my settings.py file (only the relevant settings): import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '<my-secret-key>' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['<my-server-ip>'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'frontend', 'services', 'rest_framework', 'dj_rest_auth', 'rest_framework.authtoken', 'user', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', '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', ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ) } CORS_ALLOWED_ORIGINS = [ "http://<my-server-ip>:8000", "http://localhost:8000", "http://127.0.0.1:8000", "http://0.0.0.0" ] CSRF_TRUSTED_ORIGINS = [ "http://<my-server-ip>:8000", "http://localhost:8000", "http://127.0.0.1:8000", "http://0.0.0.0" ] CORS_ALLOW_CREDENTIALS = True I make the API requests from React using axios … -
Django Serializer how to hide/show related fields
I have three 4 Model Quiz, Question, Multichoice, and Answers When using serializer to display a Quiz Data, the data is displayed as follows [ { "id": 333, "title": "Practice Exam : Class 12 Physics (Current Electricity) ", "description": "", "url": "b75038cf-e309-45da-9a91-02a4ff1ea231", "category": 52, "random_order": true, "pass_mark": 0, "draft": false, "durationtest": "10:00", "get_questions": [ { "id": 6155, "content": "<p style=\"text-align:justify\"><span style=\"font-size:13pt\"><span style=\"font-family:Calibri,sans-serif\">The equivalent resistance between P and Q in the given figure is approximately:&nbsp;</span></span></p>\r\n\r\n<p style=\"text-align:justify\"><span style=\"font-size:13pt\"><span style=\"font-family:Calibri,sans-serif\">(A) 10&Omega; </span></span></p>\r\n\r\n<p style=\"text-align:justify\"><span style=\"font-size:13pt\"><span style=\"font-family:Calibri,sans-serif\">(B) 5&Omega; </span></span></p>\r\n\r\n<p style=\"text-align:justify\"><span style=\"font-size:13pt\"><span style=\"font-family:Calibri,sans-serif\">(C) 6&Omega; </span></span></p>\r\n\r\n<p style=\"text-align:justify\"><span style=\"font-size:13pt\"><span style=\"font-family:Calibri,sans-serif\">(D) 20&Omega; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;B</span></span></p>\r\n<gdiv></gdiv>", "category": 52, "sub_category": 178, "getanswers": [ { "id": 17065, "content": "A", "correct": false, "question_id": 6155, "question": 6155 }, { "id": 17066, "content": "B", "correct": true, "question_id": 6155, "question": 6155 }, { "id": 17067, "content": "C", "correct": false, "question_id": 6155, "question": 6155 }, { "id": 17068, "content": "D", "correct": … -
Django workaround to use window function call in an aggregate function?
I'm trying to calculate customer order frequency. First use a window function to get the previous order date then annotate the days since the last order. from django.db.models import Avg, F, Window from django.db.models.functions import ExtractDay, Lag, TruncDate orders = ( Order.objects .annotate( prev_order_date=Window( expression=Lag('paid_at', 1), partition_by=[F('customer_email')], order_by=F('paid_at').asc(), ), days_since_last=ExtractDay( TruncDate('paid_at') - TruncDate('prev_order_date') ), ) ) Then group by customer_email before calculating the average frequency. customer_data = ( orders.values('customer') .annotate(avg_frequency=Avg('days_since_last')) ) Unfortunately this throws an error. Does anyone know of a workaround or know of an alternate way to calculate the average frequency? psycopg2.errors.GroupingError: aggregate function calls cannot contain window function calls -
Django request.session empty between views using JWT
I'm having trouble with using request.session in Django (using JWT for authentification) to keep some user's parameters. I am well aware I have to specify INSTALLED_APPS = [ 'django.contrib.sessions', MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', but I think there is something I don't get and I think it is related to the fact I am using JWT. I can store some data in request.session when doing an API call (view) but it won't exist anymore on another one. @api_view(["POST"]) def updateFilters(request): # récupère les filtres dans la session filtres = request.data for key, value in filtres.items(): request.session[key] = value #it's ok here return Response("Filters updated") @api_view(['POST']) def testAPI(request): #empty here !!!!! print(request.session.items()) return Response("Test") Could someone explain what is wrong and maybe propose a solution ? Thank you for your help -
Django - pagination based on search criteria
I am having issues getting results when clicking on page 2 and above - most likely due to url issues. I have a list of names and if I search on e.g. "John" I want them to be separated by pages if number of names > e.g. 10. My Views are as follows: (searching works fine) def name_search(request): if 'q' in request.GET: q=request.GET.get('q', '') pvt_list = pvt_data.objects.filter(full_name__icontains=q) #Pagination p = Paginator(pvt_list, 10) # Show 10 contacts per page. page_num = request.GET.get('page', 1) try: page = p.page(page_num) except PageNotAnInteger: page = p.page(1) except EmptyPage: page = p.page(1) context = {'items' : page} return render(request, 'home/name_search.html', context) else: return render(request, 'home/name_search.html') My urls.py file is urlpatterns = [ ... path('name_search', views.name_search, name='name_search'), ... ] My html file is {% for pvt in items %} {{ pvt.full_name }} {% endfor %} <div class="pagination"> <span class="step-links"> {% if items.has_previous %} <a href="?page={{ items.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ items.number }} of {{ items.paginator.num_pages }}. </span> {% if items.has_next %} <a href="?page={{ items.next_page_number }}">next</a> {% endif %} </span> </div> When I search, I get the following link 'http://127.0.0.1:8000/name_search?q=John' with the first 10 names correct. When I click on next button I get … -
Query data that belongs to a certain user and compare to similar data from another user
I am a month into working with django and this is giving me trouble.I have a table Invoice that stores invoices .The contents for one invoice are structured as below.The invoices have an appointment field that has a field doctor that stores details of the doctor belonging to the appointment.The invoice also has a doctor_amount which belongs to the doctor in the appointment.I need to get all the doctor_amounts that belong to one doctor and sum them.I then need to find the doctor who has the most amount.I have tried a lot and do not know which attempt is even close so I can put here.So I will just leave it open so I can get independent insight. I will really appreciate the help. { id:1, status: "cleared", appointment:{ id: 3, doctor:{ id: 10, name: "kev", } amount: 10000, doctor_amt: 9000, } } views.py class TopDoctorView(APIView): def get(self, request, format=None): all_invoices = Invoice.objects.all() serializers = InvoiceSerializer(all_invoices, many=True) try: result = {} invoices = serializers.data result = res return Response(result, status=status.HTTP_200_OK) except Exception as e: error = getattr(e, "message", repr(e)) result["errors"] = error result["status"] = "error" return Response(result, status=status.HTTP_400_BAD_REQUEST) -
ESP8266 not connecting to django server
I've created a local server on my pc with django and im trying to send a GET request from my esp8266 01 module which just gives a message and a POST request which send data that is stored in a JSON file. The server works fine with postman but doesnt connect with a esp. The http request gives error code -1 This is code only for GET ESP Code: #include <Arduino.h> #include <ESP8266WiFi.h> #include <ESP8266WiFiMulti.h> #include <ESP8266HTTPClient.h> #include <WiFiClient.h> ESP8266WiFiMulti WiFiMulti; void setup() { Serial.begin(115200); // Serial.setDebugOutput(true); Serial.println(); Serial.println(); Serial.println(); for (uint8_t t = 4; t > 0; t--) { Serial.printf("[SETUP] WAIT %d...\n", t); Serial.flush(); delay(1000); } WiFi.mode(WIFI_STA); WiFiMulti.addAP("username", "password"); } void loop() { // wait for WiFi connection if ((WiFiMulti.run() == WL_CONNECTED)) { WiFiClient client; HTTPClient http; Serial.print("[HTTP] begin...\n"); if (http.begin(client, "http://127.0.0.1:8000/polls/")) { Serial.print("[HTTP] GET...\n"); // start connection and send HTTP header int httpCode = http.GET(); // httpCode will be negative on error if (httpCode > 0) { // HTTP header has been send and Server response header has been handled Serial.printf("[HTTP] GET... code: %d\n", httpCode); // file found at server if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { String payload = http.getString(); Serial.println(payload); } } else { … -
Django login required error ERR_TOO_MANY_REDIRECTS
My django application worked fine before using LoginRequiredMiddleware, after I used LoginRequiredMiddleware i have got this error. This page isn’t working 127.0.0.1 redirected you too many times. Try clearing your cookies. ERR_TOO_MANY_REDIRECTS settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'login_required.middleware.LoginRequiredMiddleware', # 'debug_toolbar.middleware.DebugToolbarMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] REPORT_BUILDER_ASYNC_REPORT = True WSGI_APPLICATION = 'mymachine.wsgi.application' CRISPY_TEMPLATE_PACK = 'bootstrap4' LOGIN_REDIRECT_URL = 'index' LOGOUT_REDIRECT_URL = 'login' LOGIN_URL = 'login' CSRF_COOKIE_HTTPONLY = False url.py urlpatterns = [ path('login/', LoginView.as_view(), name='login'), path('logout/', LogoutView.as_view(), name='logout'), path('', IndexView.as_view(), name='index'), ] view.py class LoginView(CreateView): """ Login """ template_name = "registration/login.html" defaults = dict() def __init__(self, **kwargs): super(LoginView, self).__init__(**kwargs) def on_create(self, request, *args, **kwargs): return render(request, self.template_name, self.defaults) def init_component(self, request): logout(request) self.defaults['name_space'] = reverse('auth') self.defaults['form'] = LoginForm def get(self, request, *args, **kwargs): self.init_component(request) return self.on_create(request, *args, **kwargs) def post(self, request, *args, **kwargs): form = LoginForm(request.POST) if form.is_valid(): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user: login(request, user) request.session["company_id"] = 1 return redirect(settings.LOGIN_REDIRECT_URL) elif user is None: context = {'name_space': reverse('auth'), 'form': LoginForm, 'message': _("username or password is incorrect"), 'add': 'try Again'} return render(request, 'registration/login.html', context) This is the url that appears in chrome. http://127.0.0.1:4050/login/?next=/login/ I have tried must of the answers in the … -
Django: how to refresh html content on new database entry
I am developing a MQTT Dashboard app with django. I have a mqtt thread running in background, periodically polling for data from remote device and saving it as a database (MariaDB) row. I also have a view that displays this row in simple table. Now, what I want to do is to refresh this view (without page reload) when new data appears and my question is how to do that. I thought of two different approaches: Use JS's setInterval triggering ajax call to periodically refresh content. Problem here is that I'm not really proficient with JavaScript nor jQuery so I would love to get simple example how to do that Somehow refresh data from within on_message function which is called when mqtt gets new data. Problem here is that I have no clue if it is even possible I would appreciate any explanation of above or even more some description of different, more proper way to do that. Here is my code: part of template with content i want to refresh: <div class="row mb-4 justify-content-center text-center"> <h1 class="text-uppercase text-white font-weight-bold">{% translate "Parameters" %}</h1> <table id="device-parameters-table"> <thead> <tr> <th scope="col">{% translate "Parameter" %}</th> <th scope="col">{% translate "Value" %}</th> <th scope="col">{% translate … -
In my form there is an image upload section. If user not upload any file, then it gives MultiValueDictKeyError. How to get rid of it?
I am working on a project for a Django web-based application. In this project, there is a section in which I take info from the user through an HTML form. I added a section "image upload " but it gives a MultiValueDictKeyError error when the user does not upload any file. I tried this but not working for me. This is error section : error image This is my addpost.html section. It consists of a form through which, I am taking info. <form action="{% url 'addpost' %}" method='POST' enctype="multipart/form-data" novalidate> {% include 'includes/messages.html' %} {% csrf_token %} {% if user.is_authenticated %} <input type="hidden" name="user_id" value="{{user.id}}"> {% else %} <input type="hidden" name="user_id" value="0"> {% endif %} <div class="row "> <div class="tex-center"> <div class="row"> <div class="col-md-6 text-left"> <div class="form-group name"> <input type="text" name="author" class="form-control" placeholder="Author" {% if user.is_authenticated %} value="{{user.first_name}}" {% endif %} readonly> </div> </div> <div class="col-md-6"> <div class="form-group name"> <input type="text" name="title" class="form-control" placeholder="title" required> </div> </div> <div class="col-md-6"> <div class="form-group name"> <input type="text" name="location" class="form-control" placeholder="location" required> </div> </div> <div class="col-md-6"> <div class="form-group name"> <input type="text" name="short_desc" class="form-control" placeholder="Write short description" required> </div> </div> <div class="col-md-12"> <div class="form-group message"> <textarea class="form-control" name="full_desc" placeholder="Write full description"></textarea> </div> </div> <input type="file" … -
Django static folder works on a local server but doesn`t work on the remote server
Django static folder works on a local server but doesn`t work on the remote server. What could be the reason? -
Django Prefecth - call root elements field in filter
Here is my code, I am retrieving a Feed and all related data using the query. I am also checking if the user who is retrieving the feed is also a friend of the user who posted the feed. For friend relationships, I am using the Friends model. viewer_id and feed_id will be given by the system. I want to replace ?????? with a field from Feed model (like user_id who posted the Feed) feed = Feed.objects.select_related( 'user_info', 'images' ).prefetch_related( 'tags', Prefetch( "friends_set", queryset=Friends.objects.filter(user=viewer_id, follows=??????), to_attr="friends" ), ).get(id=feed_id) -
Django: how to add a step among the auth login code
I'm building out my first Django Project, and I'm always grateful that authentication steps are provided in modern frameworks, but I'm having trouble seeing how/where to customize the login process to do an additional step behind the scenes. I followed a tutorial to use the Django authentication, and everything is working great. I made a registration/login.html page that includes 'next' for where to take the users. I include the Django urls for authentication in mysite/urls.py: urlpatterns = [ path('familytree/', include('familytree.urls')), path('admin/', admin.site.urls, name='admin'), path('accounts/', include('django.contrib.auth.urls')), ] In settings.py, I specify that I want users to go to the dashboard page after logging in: LOGIN_REDIRECT_URL = 'dashboard' LOGOUT_REDIRECT_URL = 'landing' The question: I'd like to add one other step: after a user successfully authenticates, I'd like to make a record in a new logins table, and then let them continue on to the dashboard. Where's the right place to add this step? At first I was thinking I could change the LOGIN_REDIRECT_URL to some other step (and then have that proceed to dashboard), but what I want isn't really a url.... not sure if middleware would be more appropriate? OR is there some way to sort of extend the login code … -
Django - inline formset validation
I'm trying to validate my inline formset cost value's to make sure that it adds up to 100. The formset is returned 5 times so foreach the value should be added until 100 is hit. If it's more or less than that show an error & not allow the user to hit the create button. Models.py class EstimatedBudgetForm(forms.ModelForm): def clean(self): # get forms that actually have valid data count = 0 for percentage in self.cost: try: if percentage.cleaned_data: count += percentage except AttributeError: # annoyingly, if a subform is invalid Django explicity raises # an AttributeError for cleaned_data pass if count != 100: raise forms.ValidationError('Percentage must equal 100%') Views.py EstimatedBudgetChildFormset = inlineformset_factory( Project, EstimatedBudget, fields=('project', 'item', 'cost', 'time'), can_delete=False, form=EstimatedBudgetForm, extra=5, widgets={'item': forms.Select(attrs={'disabled': True})}, ) -
image upload to server using django restful api from android app using retrofit
I have been unable to upload images from android app using retrofit to server using django api. When i try to send images from android app, no errors will be shown and it also does not hit the server but using postman it works perfectly fine. What could be the reasons behind it? -
fix error 404 image not found django-allauth
i have add custom model for user signup and i add Imagefield so when user upload his photo during signup its work and uploaded to my folder but when i try to get image for user and display photo in profile page it's say GET /images/modern-mosaic-wallpaper-rose-gold-black_53876-58064.jpg HTTP/1.1" 404 4835 my code | models.py : class User(AbstractUser): user_pic = models.ImageField(upload_to='images/',null=True, blank=True) forms.py : class CustomSignupForm(SignupForm): first_name = forms.CharField(required=True,label='First Name',widget=forms.TextInput(attrs={'class': 'form-control','placeholder':' Enter First Name '}) ) last_name = forms.CharField(required=True,label='Last Name',widget=forms.TextInput(attrs={'class': 'form-control','placeholder':' Enter Second Name '}) ) user_pic = forms.ImageField(required=True,label='Your photo') def save(self, request): user = super(CustomSignupForm, self).save(request) user.user_pic = self.cleaned_data['user_pic'] user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.save() return user profile_page.html : <img src="{{user.user_pic}}" style="width:100%;height:100%"> settings.py : ACCOUNT_FORMS = { 'signup': 'blog_app.forms.CustomSignupForm', } AUTH_USER_MODEL = 'blog_app.User' everything work , the image successfully uploaded but i cant get image for user it says error 404 not found but the image already in images folder how to display image for user ? -
How to cumsum two models related by an intermediate model using Django ORM
Problem Let's say I have one table called Price which is a timeseries with a timestamp, a value and the difference of previous day. To simplify the table I have put only the dates not the hours, mins, etc.: timestamp value difference 2021-01-21 500 500 2021-01-22 1000 500 2021-01-23 1500 500 2021-01-24 2000 500 2021-01-25 2500 500 Those values might be incorrect and a user might correct it at any point in time using a second table called CorrectedPrice. A user can correct the start value even before the date of the first Price value: timestamp value 2021-01-15 1000 2021-01-23 500 By merging those two informations the resulting queryset between date 2021-01-22 and 2021-01-26 should be: timestamp value 2021-01-21 1500 2021-01-22 2000 2021-01-23 1000 2021-01-24 1500 2021-01-25 2000 Django Models We have a Stock model: class Stock(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.Charfield(unique=True) A Price model: class Price(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) value = models.IntegerField() difference = models.IntegerField() # done with a signal on pre_save timestamp = AutoCreatedField() stock = models.ForeignKey(Stock, on_delete=models.CASCADE) and then we have the CorrectedPrice model: class CorrectedPrice(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) value = models.IntegerField() timestamp = AutoCreatedField() stock = models.ForeignKey(Stock, on_delete=models.CASCADE) What … -
Getting error "SuspiciousFileOperation" after Django Version Update Django: 3.1.9 from Django: 3.1.8
I am getting this error after updating to Django: 3.1.9, on Django: 3.1.8 it works fine. I have a Files model with a FileField as below: class JobFiles(BaseModel): category = models.CharField(max_length=50, choices=FILE_CATEGORY) job_file = models.FileField('JobFile', upload_to=user_directory_path) I specified the upload_to option so that it gets uploaded differently per Category: def user_directory_path(instance, filename): import uuid if not instance.job_file_name: instance.job_file_name = filename if instance.category == 'Job Card': return f'job_card/{uuid.uuid4()}' if instance.category == 'Photos': return f'job_card/photos/{uuid.uuid4()}' if instance.category == 'Other': return f'job_card/other/{uuid.uuid4()}' return f'job_card/other/{uuid.uuid4()}' The code generating the error (double checked the file exists and it is wrapped in a file object): from django.core.files import File def test() job_files = job_card.job_card_file or JobFiles(category='JobCard') # Get path to a temp file that was processed (existence and other checks already done) doc = '/tmp/mergedfile.pdf' with open(doc, mode='rb') as f: job_files.job_file = File(f) job_files.save() The error I am getting: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.9/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/code/job_cards/views.py", line 311, in job_card_maintenance_create job_files.save() File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 753, in save self.save_base(using=using, force_insert=force_insert, File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 790, in save_base updated … -
How can use exclude query in django
I have 2 table orderProduct and orderRequest i want to exclude that order from orderProduct table which are in the orderRequest table, but it show the error 'ForwardManyToOneDescriptor' object has no attribute 'orderProduct' Models.py class OrderProduct(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) description = models.CharField(max_length=90) quantity = models.IntegerField() order_cancel = models.BooleanField(default=False) class OrderRequest(models.Model): order_status = models.CharField(max_length=10) order = models.ForeignKey(Order, on_delete=models.CASCADE) view.py class OrderProduct_View(TemplateView): template_name = 'purchase/orderProduct.html' def get(self, request, *args, **kwargs): checkOrder = OrderRequest.objects.exclude( orderProduct_id__in=OrderRequest.order.orderProduct ) args = {'checkOrder': checkOrder} return render(request, self.template_name, args) -
How to add a user input folder in my webpage so that they can put notes inside it?
I am working on a web notes app. I want to create a folder based on user input so that they can manage what types of notes they want to put in it. Like in a usual notes app. Website layout: -
How to test a view that requires a user to be authenticated in Django?
I have the following view that requires a user to be authenticated to access it, otherwise redirects to the login page: In my urls.py file: from . import views urlpatterns = [ path("settings", login_required(views.Settings.as_view()), name="settings"), ] In my views.py file: class Settings(View): def get(self, request): return render(request, "project/settings.html") How can I test this view? Here is what I tried: class TestViews(TestCase): def setUp(self): self.user = User.objects.create( username="testUser", password="testPassword", ) def test_settings_authenticated(self): client = Client() client.login(username="testUser", password="testPassword") response = client.get("/settings") self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, "project/settings.html") But this returns a 302 status, implying the user was not authenticated. -
Setting up Heroku Postgres from SQLite3 at Django
I have recently hosted my CRM System at heroku. But since I was only using SQLITE3, the database encounters errors at heroku. how will I setup my settings.py to fix this? I have updated settings.py yet it shows NameError: name 'os' is not defined but whenever I put import os, it shows: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte please help me, here is the code for my settings.py: from pathlib import Path import os import django_heroku import dj_database_url import dotenv # Build paths inside the project like this: BASE_DIR / 'subdir'. # BASE_DIR = Path(__file__).resolve().parent.parent # This line should already exist in your settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # This is new: dotenv_file = os.path.join(BASE_DIR, ".env") if os.path.isfile(dotenv_file): dotenv.load_dotenv(dotenv_file) # 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 = 'm)3ag$=da^%ifkti+u!rg@!x3b_%my$*#6vorp1!@vdy!i^i*!' # 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', # Thrid party apps 'crispy_forms', "crispy_tailwind", # Local apps 'clients', 'agents' ] 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', …