Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django not accepting request from client using bearer token from react native
I have been stuck on this for a couple days. If I pass the bearer token as hard coded it works but if I use props or a variable it gets rejected.. I am not too sure what is wrong. I also added a check in the component before to make sure the jwt is there. import { StyleSheet, Text, View, Image, SafeAreaView, TouchableOpacity, ScrollView, } from "react-native"; import React, { useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; var axios = require("axios"); const FriendsList = (props) => { useEffect(() => { var config = { method: "get", url: "http://127.0.0.1:8000/getuserinfo/", headers: { Authorization: `Bearer ${props.jwt}`, }, }; const fetchD = async () => { const res = await axios(config).then(function (response) { console.log(JSON.stringify(response.data)); }); res(); }; fetchD(); }, []); return ( <View> <Text>FriendList</Text> </View> ); }; export default FriendsList; Here is the component before the above, I can login but when I pass the bearer token to the server I get back a 400 response not authorized :0 import { StyleSheet, Text, View, Image, SafeAreaView, TouchableOpacity, ScrollView, } from "react-native"; import React, { useEffect, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import { accessCookie, … -
How should I create my project so it is easily shareable and won't require the user to install additional packages?
I am writing a small coding exercise I need to share with someone, who will run it on their system. The project uses Django+Celery and runs a search using a CLI tool installed on a Docker image (from Dockerhub). I am wondering what the best solution is for creating a neatly-packaged project with the least amount of user setup required. I can think of only two options here: I could host the entire project on a Docker container built from the Dockerhub image. Since the base image (which I am required to use for the tool it has) does not have Python installed, I would need to use the Dockerfile to install Python, Celery, sqlite3+libsqlite3-dev, as well as redis-server for Celery using the package manager (the image is Debian) For brief context, I run the search using subprocess.Popen("cmd") in a Celery task. I could instead change this to subprocess.Popen("docker run cmd") and use the Docker image only for the CLI tool it has, instead of attempting to host the entire project with Docker. The issue here is that Docker requires sudo, and it seems like very bad practice to run subprocess.Popen("sudo docker run cmd") if it would even work. Are … -
How to record activities of different types?
I am writing an application that would allow a user to record things that occur in their life. For example, you could record Drinks, Breakfast, Lunch, Dinner, Exercise, Supplements, Mood, Sleep Quality, etc. Below are the data models that I have thus far. How should I record the activity of the user when the category of the activity may be different? For example: YYY-MM-DD TIME Breakfast food_id YYY-MM-DD TIME Lunch food_id YYY-MM-DD TIME Exercise 30 minutes from django.contrib.admin.options import ModelAdmin from django.contrib.admin.sites import NotRegistered from django.db import models from django.conf import settings class Food(models.Model): class Meta: verbose_name = "food" verbose_name_plural = "foods" def __str__(self): return self.label food_id = models.BigAutoField(primary_key=True) label = models.CharField(max_length=64) notes = models.CharField(max_length=200, blank=True, null=True) user_id = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Unit(models.Model): class Meta: verbose_name = "unit" verbose_name_plural = "units" def __str__(self): return self.label unit_id = models.BigAutoField(primary_key=True) label = models.CharField(max_length=64, unique=True) class Ingredient(models.Model): class Meta: verbose_name = "ingredient" verbose_name_plural = "ingredients" def __str__(self): return self.label ingredient_id = models.BigAutoField(primary_key=True) label = models.CharField(max_length=64, unique=True) class Allergen(models.Model): class Meta: verbose_name = "allergen" verbose_name_plural = "allergens" def __str__(self): return self.label label = models.CharField(max_length=64) class FoodIngredient(models.Model): class Meta: verbose_name = "food_ingredient" verbose_name_plural = "food_ingredient" def __str__(self): return self.recipe_id food_ingredient_id = models.BigAutoField(primary_key=True) food_id = models.ForeignKey(Food, … -
How to get value from "object_list" returned by listview
I want to check the particular value from "object_list" returned by ListView in a template. So I wrote code this way. {% object_list.<primary key>.<column> %} Example {% if object_list.ABCD1234.item_name == "myitem" %} ... do something ... {% endif %} In this example, ID(primarykey) is "ABCD1234" Column name is "item_name" and value in "item_name" is "myitem". Maybe I wrote something wrong, it does not work at all. Please teach me how to fix the code to get value from object_list to make the above conditional branching works well. I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you -
Django password reset form randomly pre-populating email field
Our system is using the default Django auth password managment, including the password reset view: django.contrib.auth.views.PasswordResetView We override the form used by the view django.contrib.auth.forms.PasswordResetForm by: Adding a simple captcha field to the form (https://pypi.org/project/django-nocaptcha-recaptcha/) Overriding clean_email Overriding send_mail from django.contrib.auth.forms import PasswordResetForm from nocaptcha_recaptcha.fields import NoReCaptchaField from django.contrib.auth import get_user_model from common.utils import send_password_reset_email ... class MyPasswordResetForm(PasswordResetForm): captcha = NoReCaptchaField() def clean_email(self): """Ensure the email address exists in the system.""" email = self.cleaned_data['email'] email_in_db = get_user_model().objects.filter(email__iexact=email).exists() if not email_in_db: raise forms.ValidationError(NO_EMAIL_MESSAGE) user = get_user_model().objects.get(email__iexact=email) if user and not user.password: raise forms.ValidationError( mark_safe( 'Your account doesnt have a password yet, click this ' f'<a href="{reverse("accounts:password-setup")}">Password ' # noqa: E901 'Setup</a> link to setup your password.' ) ) return email.lower() def send_mail(self, *args, **kwargs): """Sends the templated password reset email to the appropriate user.""" email = self.cleaned_data['email'] user = get_user_model().objects.get(email__iexact=email) send_password_reset_email(user) We've been getting some very odd behaviour with the form being initialised to whatever the last email that was reset in the system. This is inconsistent. I can visit the page, and refresh it 10 times, and 3 of the 10 times will initialise the form with an email, while the other times it is blank. -
Django: How do I authenticate an AbstractBaseUser?
I have created a model for an AbstractBaseUser, but am struggling to authenticate it. Here is my model: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.contrib.auth.password_validation import validate_password from uuid import uuid4 class CustomUserManager(BaseUserManager): def _create_user(self, email, password, is_staff=False, is_superuser=False, **other_fields): if not email: raise ValueError('Email address must be specified') if not password: raise ValueError('Password must be specified') user = self.model( email=self.normalize_email(email), is_staff=is_staff, is_superuser=is_superuser, **other_fields ) validate_password(password) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, **other_fields): return self._create_user(email, password, False, False, **other_fields) def create_superuser(self, email, password, **other_fields): return self._create_user(email, password, True, True, **other_fields) class CustomUser(AbstractBaseUser): id = models.UUIDField(primary_key=True, default=uuid4(), editable=False, unique=True) email = models.EmailField(max_length=254, unique=True) is_superuser = models.BooleanField(default=True) is_staff = models.BooleanField(default=True) is_active = models.BooleanField(default=True) is_premium = models.BooleanField(default=False) first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=40) display_name = models.CharField(max_length=40) date_of_birth = models.DateField() currency = models.CharField(max_length=3) date_joined = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now=True) REQUIRED_FIELDS = ['first_name', 'display_name', 'date_of_birth', 'currency'] USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' objects = CustomUserManager() def get_full_name(self): return ("%s %s" % (self.first_name, self.last_name)) if self.last_name != '' else self.first_name def get_short_name(self): return self.first_name def __str__(self): return "%s %s - %s" % (self.first_name, self.last_name, self.email) Here is my view: from django.contrib.auth import authenticate from django.http import HttpResponse def user_login(request): user … -
Download bz2, Read compress files in memory (avoid memory overflow)
As title says, I'm downloading a bz2 file which has a folder inside and a lot of text files... My first version was decompressing in memory, but Although it is only 90mbs when you uncomrpess it, it has 60 files of 750mb each.... Computer goes bum! obviusly cant handle like 40gb of ram XD) So, The problem is that they are too big to keep all in memory at the same time... so I'm using this code that works but its sucks (Too slow): response = requests.get('https:/fooweb.com/barfile.bz2') # save file into disk: compress_filepath = '{0}/files/sources/{1}'.format(zsets.BASE_DIR, check_time) with open(compress_filepath, 'wb') as local_file: local_file.write(response.content) #We extract the files into folder extract_folder = compress_filepath + '_ext' with tarfile.open(compress_filepath, "r:bz2") as tar: tar.extractall(extract_folder) # We process one file at a time: for filename in os.listdir(extract_folder): filepath = '{0}/{1}'.format(extract_folder,filename) file = open(filepath, 'r').readlines() for line in file: print(line) Is there a way I could make this without dumping it to disk... and only decompressing and reading one file from the .bz2 at a time? Thank you very much for your time in advance, I hope somebody knows how to help me with this... -
Django Vs .Net for AWS Glacier
I'm starting to plan a new web app for the company that I'm currently working for. The idea is to create a web app where the user will do all the basic operations (upload, delete, update, etc) on AWS Glacier. Users basically will admin the account of AWS Glacier, create vaults, tags, upload files, delete files, etc.. all the options AWS Glacier has to offer. There are going to be several users each user with different AWS Glacier accounts and of course each user with unique AWS configurations. Another important aspect is the security of the information of each user (the AWS Glacier credentials), I believe I'll need to somehow encrypt this information of each user. I'm having second thoughts if I should develop this project with Django or .Net. What do you think? or maybe is there a third option y should consider besides Django and .Net? -
'Order' object has no attribute 'get_cart_items'
I have no errors in Vs Code but keep getting this in Django, any ideas? Any help much appreciated (: Django AttributeError at / 'Order' object has no attribute 'get_cart_items' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.4 Exception Type: AttributeError Exception Value: 'Order' object has no attribute 'get_cart_items' Exception Location: /Users/alessiolivolsi/Work/pp/ecommerce/ecommerce/ecommerce/store/views.py, line 12, in store Python Executable: /usr/local/opt/python@3.9/bin/python3.9 Python Version: 3.9.5 Python Path: ['/Users/alessiolivolsi/Work/pp/ecommerce/ecommerce/ecommerce', '/usr/local/Cellar/python@3.9/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python39.zip', '/usr/local/Cellar/python@3.9/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python3.9', '/usr/local/Cellar/python@3.9/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload', '/usr/local/lib/python3.9/site-packages'] Server time: Mon, 28 Jun 2021 23:21:08 +0000 views.py from django.shortcuts import render from django.http import JsonResponse import json from .models import * def store(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: items = [] order = {'get_cart_total':0, 'get_cart_items':0} cartItems = order['get_cart_items'] products = Product.objects.all() context = {'products':products, 'cartItems':cartItems} return render(request, 'store/store.html', context) def cart(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() else: items = [] order = {'get_cart_total':0, 'get_cart_items':0} context = {'items':items, 'order':order} return render(request, 'store/cart.html', context) def checkout(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() else: items = [] order = {'get_cart_total':0, 'get_cart_items':0} context = {'items':items, 'order':order} return render(request, 'store/checkout.html', context) def updateItem(request): data = json.loads(request.body) … -
Supervisor within Ansible playbook not running Gunicorn
I want my Ansible playbook to use supervisor to start a Gunicorn server that runs my django project. The playbook that I have right now runs completely through, however Gunicorn does not seem to be running on completion. Here is the current playbook: --- - hosts: sorb become: true vars: product: "sorb" vars_files: - "../../group_vars/sorb" - "../../../../ansible/group_vars/base" roles: - role: base min_mnt_size: 30 daemon_logs: - nginx logs: - file: "{{ log_json }}" category: python-json - file: "{{ log_unhandled }}" category: unhandled-output cron: condition: "{{ not_dev }}" jobs: - sessioncleaner - role: offline # "offline" follows "base" to prevent alerts during deploy - role: install_env #install dep to avoid creation errors - role: pip_virtualenv #this installs pip reqs and the virtual env uses requirements.txt - role: github repositories: #clone in common and sorb from github - "common" - "sorb" - role: gunicorn - role: oefenweb.supervisor - role: supervisor templates: - "../../../gunicorn/templates/supervisor/gunicorn" - role: online - role: done Here is the gunicorn role tasks main.yml: --- - name: Render gunicorn.conf.py template: src: gunicorn/gunicorn.conf.py.j2 dest: "{{ gunicorn_config_path }}" owner: "{{ nginx_user }}" group: "{{ nginx_group }}" mode: "{{ '0o666' if is_vbox else '0o655' }}" notify: Restart Supervisor Thank you!! -
Django Hide unavailable dates
I have a simple application to have an appointment with a doctor. I would like to have an appointment when the doctor is available and hide the occupation date in my form. form: class ContactForm(ModelForm): class Meta: model = Appointment fields = ('doctor', 'date', 'timeslot', 'patient_name') model : from django.db import models class Appointment(models.Model): class Meta: unique_together = ('doctor', 'date', 'timeslot') TIMESLOT_LIST = ( (0, '09:00 – 09:30'), (1, '10:00 – 10:30'), (2, '11:00 – 11:30'), (3, '12:00 – 12:30'), (4, '13:00 – 13:30'), (5, '14:00 – 14:30'), (6, '15:00 – 15:30'), (7, '16:00 – 16:30'), (8, '17:00 – 17:30'), ) doctor = models.ForeignKey('Doctor',on_delete = models.CASCADE) date = models.DateField(help_text="YYYY-MM-DD") timeslot = models.IntegerField(choices=TIMESLOT_LIST) patient_name = models.CharField(max_length=60) def __str__(self): return '{} {} {}. Patient: {}'.format(self.date, self.time, self.doctor, self.patient_name) @property def time(self): return self.TIMESLOT_LIST[self.timeslot][1] class Doctor(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) middle_name = models.CharField(max_length=20) specialty = models.CharField(max_length=20) def __str__(self): return '{} {}'.format(self.specialty, self.short_name) @property def short_name(self): return '{} {}.{}.'.format(self.last_name.title(), self.first_name[0].upper(), self.middle_name[0].upper()) -
How to pass a list variable from java script to html?
I need to create a list "task_list" (in script part) based on a variable "letters_per_word" that is randomly drawn (either 1 or 2): [0,1] or task_list=[0,1,2], respectively. task_list = get_list(letters_per_word) Then I need to use "task_list" inside for loop: {% for l in task_list%} .... {% endfor %} The problem is that I cannot access task_list in that loop I tried using document.getElementById("task_list").value = task_list But it worked as if 'task_list' was empty How can I pass 'task_list' to use it in 'for' loop? -
Django dunder relation works but Django queryset dot notation doesn't?
I have a database with a couple of relations and I have tried to access this relation through both the dunder notation as well as the dot notation. The dunder notation works to get the information from inspection but the dot notation does not work. I get an AttributeError so it might have something to do with my query but I am not sure. Here is a little code snippet from the dunder notation: (simplification) I am trying to get from MRN to Inspection and this method works writer.writerow([ "Inspection Id", "Inspection Type", "Inspection Review" ]) args = [ "inspection__id", "inspection__type", "inspection__inspection_review", ] qs = MRN.objects.all().values_list( *args ) for q in qs: writer.writerow(q) Here is a little code snippet from the dot notation: (simplification) Again, I am trying to get from MRN to Inspection, but this method does not work. mrn_qs = MRN.objects.filter(created_date__range=(from_date, to_date)).distinct().filter( equipment__model__make_id=manufacturer) ind_list = [] mrn_list = [] for q in rma_qs: ind_list.append(q.id) ind_list.append(q.equipment.model.model_number) ind_list.append(q.inspection.id) mrn_list.append(ind_list) ind_list = [] mrn_df = pd.DataFrame(rma_list, columns=[ "_srn_id", "_model_number", "_inspection_inspection_id" ]) Please let me know if there is any further information that I can provide in order to make this easier to understand. My main question is why does one work … -
Populate Django form dropdown with data from outside a model
I would like to populate the dropdown in a Django app with data from a 3rd party API (ie, not from a Model) which is dependent on parameters in the view. All blogs/articles I have read cover forms which are dependent on Models, but not updating from another dataset (or data which is calculated or generated outside of a direct model query). Pseudo code for what I am trying to do is like this: forms.py class myform(forms.Form): # load the form with no choices because they will be populated dependent on what is in the view dropdown1=forms.ChoiceField(label="Dropdown 1",choices=[]) views.py from .forms import myform def get_dropdown_choices(person_id): # go to external data source and get a list of items as a function of the person_id return choices_list def index(request,person_id): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = myform(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: return HttpResponseRedirect('/thanks/') # if a GET (or any other method) we'll create a form # populated … -
Issue using the django usercreationform, not rendering form in HTML
im making a signup page in a django project using the UserCreationForm but when rendering my html i only see the submit button from django.shortcuts import render from django.contrib.auth.forms import UserCreationForm def register(request): form = UserCreationForm return(render(request, 'register.html', {form: form})) {% extends 'base.html' %} {% block title %}Sign Up{% endblock %} {% block body %} <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="button"> <button type="submit">Sign up</button> </form> {% endblock %} -
Naming convention for Django migrations
Is there a best practice naming convention for Django migrations? If it's a small migration the names are pretty obvious, but things get harry when multiple fields are being changed. Just wondering if anyone has a standard they like to use. -
Django - error from call to values_list: 'flat' is not defined
Here's a loop I'm using to process an Excel sheet with openpyxl. On occasion the partno field is missing and I try to derive it from another database table (booking) using a field called transmittal. I'm having trouble with this lookup and it returns an error. When I run the same thing under the Django shell, it works fine. parser = parse_defrev(book) brs = [] xmtl_part = {} invalid = [] for r in parser.process(): # If no partno, try to look it up in the bookings table if r.get('partno') is None: xmtl = r.get('transmittal') if xmtl: r['partno'] = xmtl_part.get(xmtl) if not r['partno']: parts = set(Booking.objects.filter(bookingtransmittal=r['transmittal']).values_list('bookingpartno', flat=True)) if len(parts) == 1: r['partno'] = parts.pop() xmtl_part[xmtl] = r['partno'] process is a generator function in the parse_defrev class which returns a dictionary with the processed fields from the workbook. If partno is missing, then it first tries to retrieve it from a caching dictionary and then from the booking table. The values_list returns any matching partno values, and if there is more than 1 match it just logs the problem and skips to the next row. I get the following error, and don't understand how it could fail to recognize the flat … -
How to run migration against a different database in Django?
I'm using two database instances in Django, one is in Postgis and the other is in Postgres itself. Postgis is a geospatial database that has some model fields and features that the PostgreSQL database which is its extender does not have. When I run the ./manage.py migrate, to avoid tracebacks, I want the migrations related to Postgis migrate to Postgis and the ones related to Postgres migrated to Postgres which is the default database. I could do this by specifying --database="postgis" while running the migration command but it would be best option to avoid doing that. -
ERR_CONNECTION_TIMED_OUT when trying to access AWS EC2 hosted Django application
I'm stuck with ERR_CONNECTION_TIMED_OUT in browser when trying to access Django application which is deployed to AWS EC2. A week ago I was able to connect but now when I relaunched instance, changed ALLOWED_HOSTS in .env file the browser just throw me this error. The output in the console says everything is ok. To fix this I've tried to create another instance and deploy the app there and also added Elastic IP address but still got the same error. How can I fix this issue? I'm using Django with Docker, Nginx proxy and UWSGI. Nginx proxy configuration (default.conf.tpl): server { listen ${LISTEN_PORT}; location /static { alias /vol/static; } location / { uwsgi_pass ${APP_HOST}:${APP_PORT}; include /etc/nginx/uwsgi_params; client_max_body_size 10M; } } Nginx proxy Dockerfile (Dockerfile): FROM nginxinc/nginx-unprivileged:1-alpine COPY ./default.conf.tpl /etc/nginx/default.conf.tpl COPY ./uwsgi_params /etc/nginx/uwsgi_params COPY ./run.sh /run.sh ENV LISTEN_PORT=8000 ENV APP_HOST=app ENV APP_PORT=9000 USER root RUN mkdir -p /vol/static && \ chmod 755 /vol/static && \ touch /etc/nginx/conf.d/default.conf && \ chown nginx:nginx /etc/nginx/conf.d/default.conf && \ chmod +x /run.sh VOLUME /vol/static USER nginx CMD ["/run.sh"] run.sh script: #!/bin/sh set -e envsubst < /etc/nginx/default.conf.tpl > /etc/nginx/conf.d/default.conf nginx -g 'daemon off;' .env: ... ALLOWED_HOSTS=18.119.35.216 ... (18.119.35.216 is the Elastic IP address) uwsgi_params: uwsgi_param QUERY_STRING $query_string; uwsgi_param … -
How to append/load Chatbot model in Django Website?
I have a django site on which machine learning chatbot model is needed to be appended. What I am unable to understand when I trained and saved my model using tensorflow, it created three files Now I am trying to load my model on django site in views. As I am beginner on this so I don't really know how should I do this. So I decided to load my model on site first but I really I don't know which file should I load bexause my model is saved as model.save('model.tflearn'). Should I load file using pickle or joblib. Any suggestion and solution will be appreciated! -
Django RestAPI, expose a function instead a model
In my django project i have a function like thisone: def calc_q(start_d, end_d, var_id): d = {"[": "", "]": "", ",": ""} var_results = VarsResults.objects.filter( id_res__read_date__range=(start_d, end_d), var_id_id=var_id, var_id__is_quarterly=False ).select_related( "id_res", "var_id" ).values( "id_res__read_date", "id_res__unit_id", "id_res__device_id", "id_res__proj_code", "var_val", "var_val_conv" ) df = pd.DataFrame(list(var_results)) df['id_res__read_date'] = pd.to_datetime(df['id_res__read_date']) df = df.set_index('id_res__read_date') df_15 = df.resample('15min')['var_val_conv'].agg(['first','last']) return pickle.dumps(df_15) well, function used instead of my project works well but i need to expose this function as an API for leave external user to call it specifying parameters (dates and var_id) and get pandas dataframe serialization results. How can i expose this function using Django Rest APi, i read something about serializers.SerializerMethodField but i don't understand how exactly it works and if it could be useful for my intention. So many thanks in advance Manuel -
Django's django-crispy-forms not showing asterisk for required field on form
As the title states I have a required field displayed on a form, and it doesn't show the asterisk to indicate that it is required. NOTE: The field is not required on the models side, but I set it on the forms.py side. models.py: class ErrorEvent(models.Model): """Error Event Submissions""" event_id = models.BigAutoField(primary_key=True) team = models.CharField(verbose_name="Team", blank=True, max_length=100, choices=teams_choices) event_name = models.CharField(verbose_name="Event Name", max_length=100) forms.py: from django import forms from .models import ErrorEvent class ErrorEventForm(forms.ModelForm): class Meta: model = ErrorEvent # fields = exclude = ['event_id'] widgets = { 'team': forms.Select(attrs={'required': True}),} When I check the website 'Team' is shown to be not required (but you can't finish the form without filling it) However 'Event Name' is shown to be required. Anyway I can fix this? Thank you for all help in advance! -
DJANGO MultiValueDictKeyError problem with UPDATE
I had a working update table. I am updating in the same form. But after entering the photo upload codes, the problem of updating other variables appeared. I am seeing the error page I mentioned below. I am updating these lines of code. I am updating the POSTed data in the database. Lastly, I added code related to uploading photos. There is no problem in uploading and changing photos. It works pretty well. However, this time the updating other variables part is broken. It was working normally. views.py def bilgilerim_guncel(request, id): if(request.method=='POST'): name_surname= request.POST['name_surname'] mobile_number= request.POST['mobile_number'] age= request.POST['age'] length= request.POST['length'] weight= request.POST['weight'] foot= request.POST['foot'] position= request.POST['position'] photo = request.FILES['photo'] if (os.path.isfile('static/players/' + str(id) + '.jpg')): os.remove('static/players/' + str(id) + '.jpg') storage=FileSystemStorage() filename=storage.save('static/players/'+str(id)+'.jpg',photo) storage.url(filename) players.objects.filter(user_id=id,).update(photo=str(id)+'.jpg',name_surname=name_surname,mobile_number=mobile_number,age=age,foot=foot,length=length,position=position,weight=weight,) return redirect(reverse('bilgilerim_x' ,args=(id,))) urls.py from django.contrib import admin from django.urls import path from uygulama import views urlpatterns = [ path('admin/', admin.site.urls, name='yonetim'), path('', views.anasayfa, name='home'), path('ligler/<int:id>', views.leagueLists, name='leagues'), path('haberler/',views.haberler, name='habers'), path('kayit/',views.kayit, name='kayit_x'), path('giris/',views.giris, name='giris_x'), path('cikis/',views.cikis, name='cikis_x'), path('bilgilerim/<int:id>',views.bilgilerim, name='bilgilerim_x'), path('bilgilerim-guncelle/<int:id>',views.bilgilerim_guncel, name='bilgilerim_guncel_x'), path('bildirimler/<int:id>',views.bildirimler, name='bildirimler_x'), ] players_models.py from django.db import models from django.contrib.auth.models import User from uygulama.models import teams class players(models.Model): name_surname=models.CharField(max_length=18,null=False,blank=False) mobile_number=models.IntegerField(null=False,blank=False) player_status=models.IntegerField(null=True,blank=True,default=0) team=models.ForeignKey(teams,on_delete=models.DO_NOTHING,null=True,blank=True,default=4) photo=models.ImageField(null=True,blank=True,default='resim-yok.jpg') awards=models.IntegerField(null=True,blank=True) dogecoin=models.IntegerField(null=True,blank=True) age=models.IntegerField(null=False,blank=False) foot=models.CharField(max_length=10,null=False,blank=False) length=models.CharField(max_length=4,null=False,blank=False) weight=models.IntegerField(null=False,blank=False) red_card=models.IntegerField(null=True,blank=True,default=0) position=models.CharField(max_length=2,null=False,blank=False) form_points=models.CharField(max_length=3,null=True,blank=True) user=models.ForeignKey(User,on_delete=models.CASCADE) ERROR PAGE -
Need to be able to execute a function for multiple items but it can't work, why?
I have a library app that issues books to students. My issue function is as follows. It works well. def issue_student(request,pk): if request.method == 'POST': form = OldIssueForm(request.POST,school= request.user.school,pk=pk,issuer = request.user) if form.is_valid(): try: book = form.cleaned_data['book_id'].id form.save(commit=True) books = Books.objects.filter(school = request.user.school).get(id=book) Books.Claimbook(books) return redirect('view_issue') except Exception as e: messages.info(request,f"{e}") else: form = OldIssueForm(school= request.user.school,pk=pk,issuer = request.user) return render(request, 'issue_student.html', {'form': form}) My Issue is I can't get the code to be able to issue a student with more than one book. My form is ashown below... class OldIssueForm(forms.ModelForm): def __init__(self,*args, pk,school,issuer, **kwargs): super(OldIssueForm, self).__init__(*args, **kwargs) self.fields['issuer'].initial = issuer self.fields['book_id'].queryset = Books.objects.filter(school=school,no_of_books=1) self.fields['borrower_id'].initial = pk class Meta: model = Issue fields = ['issuer','book_id','borrower_id'] widgets = { 'borrower_id':forms.TextInput(attrs={"class":'form-control','type':'hidden'}), 'issuer':forms.TextInput(attrs={"class":'form-control','type':'hidden'}), 'book_id':Select2Widget(attrs={'data-placeholder': 'Select Book',"style":"width:100%",'class':'form-control'}), } The Issue model is below class Issue(SafeDeleteModel): _safedelete_policy = SOFT_DELETE borrower_id = models.ForeignKey(Student,on_delete=models.CASCADE) book_id = models.ForeignKey(Books,on_delete=models.CASCADE) issue_date = models.DateField(default=datetime.date.today) issuer = models.ForeignKey(CustomUser,on_delete=models.CASCADE) def __str__(self): return str(self.book_id) -
Simple tag loosing the value set after leaving a FOR tag in template
I have this simple tag defined and loaded into my template: from django import template @register.simple_tag def defining(val=None): return val The tag works! My goal is, i want to set a value for a variable using this simple tag inside the FOR looping using some condition, and then, check the value of this variable after leaving the FOR. Simple right? {% defining 'negative' as var %} {% for anything in some_query_set %} {% if 1 == 1 %} {% defining 'positive' as var %} {% endif %} {% endfor %} <p>The value of var is: {{var}}</p> The problem is: I want this variable 'var' to be 'positive' after leaving the for, but it always turn into 'negative'. I've checked its values inside the IF and inside the FOR and it gets 'positive' as expected, but after leaving the FOR, it gets back to 'negative'. I may have some workaround using context variables through views, but i really need to do this in the template. I also searched the forum, but i couldn't find anything close enough to explain me why this is happening. Am i missing something? I'm kinda new to Django, so i'm trying to avoid more complex aproaches, …