Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django keeps returning local variable 'product' referenced before assignment error
I stored a list of products in my django models with multiple images attached to each product as a foreignkey. I am trying to retrieve all the products and their respective images in my django views so that I can print them on the screen. However no matter what I do I keep getting the local variable 'product' reference before assignment error. Models.py: class product(models.Model): title = models.CharField('', max_length=100, db_index=True) price = models.CharField('', max_length=100, db_index=True) description = models.CharField('', max_length=100, db_index=True) class productimage(models.Model): product = models.ForeignKey(product, on_delete=models.CASCADE) product_images = models.FileField(blank=True) views.py: template = loader.get_template("selling/shop.html") if product.objects.exists(): products = product.objects.all() for product in products: productimages = product.productimage_set.all() for productimage in productimages: imageurl = productimage.product_image.url context = { "products" : products, "productimages" : productsimages, } -
DRF Viewset - Do not create but return if object already exists
Is it possible to override the create of a Viewset to first check if an object exists and, if so, return that object rather than creating it? Specifically, in my viewset, I have overriden the create function as follows: def perform_create(self, serializer): try: item = Item.objects.get(recipe=serializer.instance.recipe) except Item.DoesNotExist: serializer.save(owner=self.request.user) However, this always fails as the object cannot be found. When I print serializer.instance it is undefined. -
how to display checked items and uploaded images value while editing the template in django
I have a simple curd application.this is the edit/update,where everything working properly.The only thing is while i want update i can not see the already checked courses,already added date and already uploaded image.how can i retrieve the course,date and image in edit_student page models.py class Student(models.Model): name = models.CharField(max_length=100) courses = models.CharField(max_length=250) address = models.CharField(max_length=200) email = models.EmailField() phone = models.CharField(max_length=15) image = models.ImageField(upload_to='Students',blank=True) joined_date = models.DateField() def __str__(self): return self.name views.py def editstudent(request,id): student = Student.objects.get(id=id) courses = Course.objects.all() return render(request,'students/edit_student.html',{'student':student,'courses':courses}) def updatestudent(request,id): student = Student.objects.get(id=id) form = AddStudentForm(request.POST,instance=student) if form.is_valid(): student = form.save(commit=False) student.save() messages.success(request,'Student with name {} updated'.format(student.name)) return redirect('students:view_student') else: messages.error(request,'Error in form.Try Again') return render(request,'students/profile_student.html',{'student':student}) edit_student.html <form action="{% url 'students:update_student' student.id %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <h5>Full Name <span class="text-danger">*</span></h5> <div class="controls"> <input type="text" name="name" class="form-control" value="{{student.name}}" required data-validation-required-message="This field is required"> </div> </div> <div class="form-group"> <h5>Courses <span class="text-danger">*</span></h5> <div class="controls"> {% for course in courses %} <input name ="courses" type="checkbox" id="course-{{course.id}}" value="{{course.title}}"> <label for="course-{{course.id}}">{{course.title}}</label> {% endfor %} </div> </div> <div class="form-group"> <h5>Address<span class="text-danger">*</span></h5> <div class="controls"> <input type="text" name="address" class="form-control" value="{{student.address}}" required data-validation-required-message="This field is required"> </div> </div> <div class="form-group"> <h5>Phone Number <span class="text-danger">*</span></h5> <div class="controls"> <input type="text" name="phone" value="{{student.phone}}" data-validation-required-message="This field … -
Unable to deploy to elastic beanstalk
I'm attempting to deploy my django project to elastic beanstalk. Before runnning 'eb deploy', I logged into AWS and saw that the health status of my instance was 'Severe': 100.0 % of the requests are erroring with HTTP 4xx. Insufficient request rate (6.0 requests/min) to determine application health. Command failed on all instances. Incorrect application version found on all instances. Expected version "app-3c6b-190420_220506" (deployment 1). ELB processes are not healthy on all instances. ELB health is failing or not available for all instances. I looked at the logs and noticed the following error repeating: [Sun Apr 21 06:15:42.463620 2019] [:error] [pid 28281] [client 172.31.24.0:64074] Target WSGI script not found or unable to stat: /opt/python/current/app/application.py Is this a file that will populate aws once I sucessfully deploy? I'm having trouble running 'eb deploy' right now and I'm not sure if it's because of this error or another error. The error that I'm getting is as follows: Collecting pywin32==224 (from -r /opt/python/ondeck/app/requirements.txt (line 19)) Could not find a version that satisfies the requirement pywin32==224 (from -r /opt/python/ondeck/app/requirements.txt (line 19)) (from versions: ) No matching distribution found for pywin32==224 (from -r /opt/python/ondeck/app/requirements.txt (line 19)) At this point, I'm not sure if the missing … -
How to fix Field defines a relation with the model 'auth.User', which has been swapped out
I am trying to change my user model to a custom one. I do not mind dropping my database and just using a new one, but when I try it to run makemigrations i get this error bookings.Session.session_client: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out. HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'. booking/views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from bookings.models import Session from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User # Create your views here. def book(request, Session_id): lesson = get_object_or_404(Session, pk=Session_id) try: client = request.user.id except (KeyError, Choice.DoesNotExist): return render(request, 'booking/details.html', { 'lesson': lesson, 'error_message': "You need to login first", }) else: lesson.session_client.add(client) lesson.save() return HttpResponseRedirect("") settings.py INSTALLED_APPS = [ #Custom apps 'mainapp.apps.MainappConfig', 'bookings.apps.BookingsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] AUTH_USER_MODEL = 'mainapp.CustomUser' bookings/models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Session(models.Model): session_title = models.CharField(max_length=300) session_time = models.DateTimeField("Time of session") session_difficulty = models.CharField(max_length=200) session_duration = models.IntegerField() session_description = models.TextField() session_client = models.ManyToManyField(User, blank=True) def __str__(self): return self.session_title I'm trying to change the user model to abstractuser. -
Django does not see the static files images
I`m trying to do online store with Django. I want to add photos of goods, but django for some reason does not see them. Please help to solve the problem. Here is screenshot with error ! [error screenshot] (https://imgur.com/P1GlikU) Here an error, although there are pictures along this path here is settings.py BASE_DIR = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = 'staticfiles' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), '../static/products/media/product_images/', ) models.py from django.db import models # Create your models here. class Product(models.Model): name = models.CharField(max_length=70, blank=True, null=True, default=None) price = models.DecimalField(max_digits=10, decimal_places=2, default=0) description = models.TextField(blank=True, null=True, default=None) short_description = models.TextField(blank=True, null=True, default=None) is_active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __str__(self): return "%s, %s" % (self.price ,self.name) class Meta: verbose_name = 'Товар' verbose_name_plural = 'Товары' class ProductImage(models.Model): product = models.ForeignKey(Product, blank=True, null=True, default=None, on_delete=models.CASCADE) image = models.ImageField(upload_to='static/media/product_images/') is_active = models.BooleanField(default=False) is_main = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __str__(self): return "%s" % self.id class Meta: verbose_name = 'Фотография' verbose_name_plural = 'Фотографии' main urls.py file from django.contrib import admin from django.urls import include, path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('online_shop.urls', namespace='online_shop')), path('', include('products.urls', namespace='products')), path('', include('orders.urls', namespace='orders')), ] … -
Update model field when creating from another model instance which is ForeignKey related
I started car fleet app and created a few models in models related file , I did models hierarchy that on top I have the car brand, below ForeignKey related car models to each brand, and ForeignKey for each car id that eventually consists the car inventory ,wich is called "class CarPool", in this model i have value "car_sale_status = models.BooleanField(default=False)" , what i would like to achieve is each time i create instance from associated ForeignKey of seller will update automatically "car_sale_status = models.BooleanField(default=False)" to True Please advice Thanks class CarPool(models.Model): # Relationship Fields car_inventory = models.ForeignKey( 'cardealer.CarTypes', on_delete=models.CASCADE, related_name="carpools", ) car_id = models.CharField(max_length=30,default="") car_location = GeopositionField() car_sale_status = models.BooleanField(default=False) YEAR_CHOICES = [] for r in range(1980, (datetime.datetime.now().year+1)): YEAR_CHOICES.append((r,r)) year_manufacture = models.IntegerField(('year_manufacture'), choices=YEAR_CHOICES, default=datetime.datetime.now().year) def __str__(self): return self.car_id def __unicode__(self): return self.car_inventory class CustomerBuyer(models.Model): buyer_car_buy = models.ForeignKey( 'cardealer.CarPool', on_delete=models.CASCADE, related_name="customer_buyer",default='0' ) buyer_private_name = models.CharField(max_length=80,default='') buyer_family_name = models.CharField(max_length=80,default='') buyer_private_id = models.IntegerField(default=0) transaction_date = models.DateTimeField(default=datetime.datetime.now()) transaction_amount = models.IntegerField(default=0) def __str__(self): return self.buyer_private_name + ' '+ self.buyer_family_name def __unicode__(self): return self.buyer_private_name + ' '+ self.buyer_family_name -
Combine and filter unrelated models
I have a few vehicle types (cars, planes, trains) with distinct models and want to have an API endpoint that will give me a filterable list of all the models combined. I've modified a ViewSet's list method to combine the serialized results of each models ModelViewSet and serve them through one endpoint. The format of the response is correct, but I want to be able to filter it. I have tried the endpoint with about 50,000 randomly generated vehicles (evenly spread across the models) and the unfiltered response can be very slow. Current response format: { "Car": [ { "url": "http://127.0.0.1:8000/myapp/api/cars/1/", "name": "Mitsuoka", "ground_clearance": null, "road_legal": true, "active": true, "bought_by": null } ], "Train": [ { "url": "http://127.0.0.1:8000/myapp/api/trains/1/", "name": "What", "freight_capacity": null, "wheel_config": null, "active": false, "bought_by": null }, { "url": "http://127.0.0.1:8000/myapp/api/trains/2/", "name": "Manufacturer", "freight_capacity": null, "wheel_config": null, "active": false, "bought_by": null } ], "Plane": [] } Example desired filters: Only Cars Only vehicles (cars, planes, AND trains) with status=Active Code models.py from django.db import models class Buyer(models.Model): name = models.CharField(unique=True, max_length = 20) class Car(models.Model): name = models.CharField(unique=True, max_length = 50) ground_clearance = models.CharField(unique=True, max_length = 50, null=True, blank=True) road_legal = models.BooleanField(default=True) active = models.BooleanField(default=True) bought_by = models.ForeignKey(Buyer, null=True, … -
Why VirtualENV as django run well without venv?
I am trying to learn Django since long but I always run the server without any venv, yet it runs well. My Question is: Why people install venv to run their project? What is the benefit of it? -
How to get media images in url in django url with reactjs
static and media configuration in settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'frontend','build', 'static') ] MEDIA_URL='/media/' MEDIA_ROOT=os.path.join(BASE_DIR, 'media') urls.py from django.contrib import admin from django.urls import path, include, re_path from django.views.generic import TemplateView from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), re_path('', TemplateView.as_view(template_name='index.html')), ] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) Here i am using django with reactjs. i have given the path of build folder in react app like this. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'frontend','build')], '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', ], }, }, ] When i am going to http://127.0.0.1:8000/media/images_OkG6q2k.jpeg path to get images in side media folder which are uploaded by users i am getting the react route page. I am not getting the image from media folder. How i can see the media photos through url. Project structure react home is coming instead media image like this when i amgoing url -
Not receiving any emails from my Django project to reset user password
Django Version: 2.1 Problem: I am currently make a blog with Django and I am working on a feature which allows user to reset their password by sending the users email through. However I am not able to receive/send any emails through my PasswordResetView. What did I do wrong? Things I've tried: I have already set "Allow less secure apps: ON" in my google account. I tried looking everywhere on Google and the answers provided are mostly asking me to try to Allow less secure apps on Google. It's been 24H I can't seem to find what have I done wrong.. Thanks in advance! settings.py 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 = 'pwpcp@sy66r-ve4(o1o3_a3+2g6(zj)lp1g^q($mspw(kr6q$o' # 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', 'blog.apps.BlogConfig', 'user.apps.UserConfig', 'crispy_forms', ] 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 = 'django_blog.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], … -
error Your credentials aren't allowed in django-rest-framework-social-oauth2 google sigin from android
i have installed Django social-auth-app-django==3.1.0 for Django web for google sign in (working fine) but in same project i installed django-rest-framework-social-oauth2 to client android app to google sigin(firebase) when user click google sigin in button in android it show available google email accounts and get the id token now i need to convert id token to access token but i am getting error postman tried admin settings -
Django database dropped and cannot re-migrate
For reasons best not explained, I deleted all tables in the database for my personal Django project. I thought running makemigrations and migrate would set it back up, however the migrate command fails. Running python manage.py migrate results in: django.contrib.auth.models.DoesNotExist: User matching query does not exist. I can run the server. However when going to the admin page (http://127.0.0.1:8000/admin/), I get the exception: During handling of the above exception ('SessionStore' object has no attribute '_session_cache'), another exception occurred: The above exception (relation "django_session" does not exist LINE 1: ...ession_data", "django_session"."expire_date" FROM "django_se... ^ ) was the direct cause of the following exception: The request information shows "[unable to retrieve the current user]". Checking the PostgreSQL database in pgAdmin 4 shows that there are no tables, as expected. Is Django noticing I don't have any users in the database? Is there a way to set up the admin user again? -
Django model form save() method not creating profile object
Consider following code: class CandidateSignUpForm(forms.ModelForm): first_name = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'placeholder': 'Ime', 'class': 'validate'})) last_name = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'placeholder': _('Prezime'), 'class': 'validate'})) class Meta: model = User fields = ('email', 'password', 'first_name', 'last_name') widgets = { 'email': forms.EmailInput( attrs = { 'placeholder': _('E-mail'), 'class': 'validate' }, ), 'password': forms.PasswordInput( attrs = { 'placeholder': _('Lozinka'), 'class': 'validate' }, ), } def signup(self, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] user.password = self.cleaned_data['password'] user.save() candidate = Candidate() candidate.user = user candidate.save() and my models.py: class User(AbstractUser): is_candidate = models.BooleanField(default=True) is_employer = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) first_name = models.CharField(max_length=50, null=True) last_name = models.CharField(max_length=50, null=True) mobile = models.IntegerField(null=True, unique=True) address = models.CharField(max_length=250, null=True) def __str__(self): return self.email class Candidate(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=True ) available_from = models.DateField(blank=True, null=True) dob = models.PositiveSmallIntegerField(blank = True, null=True) about = models.TextField(max_length=500, blank = True, null=True) def __str__(self): return self.user.first_name + ' ' + self.user.last_name Now, given I'm using Django AllAuth, I needed to override signup method, to be able to save User object. Using said code, my User is saved properly, while Candidate is not saved at all, ie, no records in candidate table. I've tried literally everything, but still can't figure out what may have … -
Could not connect to server: Connection refused (0x0000274D/10061) - PostgreSQL on remote server
I've been trying to set up a new postgresql database with a remote server (Ubuntu) a Django project for the last 2 days but keep having this same issue over and over again. What should I do? Here's the error output that I'm getting when I try to make migrations to the database: $ python manage.py makemigrations Traceback (most recent call last): File "C:\Users\loicq\desktop\coding\uvergo\venv\lib\site-packages\django\db\backends\base\base.py", line 217, in ensure_connection self.connect() File "C:\Users\loicq\desktop\coding\uvergo\venv\lib\site-packages\django\db\backends\base\base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\loicq\desktop\coding\uvergo\venv\lib\site-packages\django\db\backends\postgresql\base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\loicq\desktop\coding\uvergo\venv\lib\site-packages\psycopg2\__init__.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused (0x0000274D/10061) Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\loicq\desktop\coding\uvergo\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\loicq\desktop\coding\uvergo\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\loicq\desktop\coding\uvergo\venv\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\loicq\desktop\coding\uvergo\venv\lib\site-packages\django\core\management\base.py", line … -
how to manage checkbox in django template
This code is checking all the courses. and if i uncheck only one item then it is not performing any action. I want only the selected items to be checked.How can i do that html template <div class="form-group"> <h5>Courses <span class="text-danger">*</span></h5> <div class="controls"> {% for course in courses %} <input name ="courses" type="checkbox" id="{{course.title}}" required value="{{course.title}}" {% if course.title %}checked="checked" {% endif %}> <label for="{{course.title}}">{{course.title}}</label> {% endfor %} </div> </div> -
Django forms.ModelForm - placeholder not showing
I've the following code in my forms.py: class CandidateSignUpForm(forms.ModelForm): first_name = forms.CharField(max_length=50) last_name = forms.CharField(max_length=50) class Meta: model = User fields = ('__all__') widgets = { 'first_name': forms.TextInput( attrs = { 'placeholder':'Ime', 'class': 'validate' }, ), 'last_name': forms.TextInput( attrs = { 'placeholder': _('Prezime'), 'class': 'validate' }, ), 'email': forms.EmailInput( attrs = { 'placeholder': _('E-mail'), 'class': 'validate' }, ), 'password': forms.PasswordInput( attrs = { 'placeholder': _('Lozinka'), 'class': 'validate' }, ), } Part in templates is simply {{ form.first_name }}. Now, placeholder doesn't work for first_name and last_name form fields, but does for email form field. Would someone please share some info on what am I doing wrong here? -
How to do "USERNAME" Encryption in Django website database.?
I made a simple student information system using Django framework. I already encrypt the password in Django database admin/login using Pbkdf2 library and it display the password encryption in database which uses sha256 encryption algorithm. i tried to apply the same library to encrypt the username as well, When i check the log it display the encryption but does not display in actual database. How can i encrypt the username any other way so the username will not be display in django database. -
django middleware error with middleware takes no argument
please i have been encountering this error since and i have checked django docs and search many sites through google but still dont get the solutuion to this error,thanks in advance.this error come whenever i want runserver from datetime import timedelta from django.core.cache import cache from django.utils import translation, timezone from django.conf import settings as global_settings import pytz from djangobb_forum import settings as forum_settings class TimezoneMiddleware(object): def process_request(self, request): if request.user.is_authenticated(): profile = request.user.forum_profile try: timezone.activate(profile.time_zone) except pytz.UnknownTimeZoneError: profile.time_zone = global_settings.TIME_ZONE profile.save() this is the error am getting System check identified 48 issues (0 silenced). April 21, 2019 - 00:34:43 Django version 2.2, using settings 'hayhealth_v_2.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Exception in thread Thread-1: Traceback (most recent call last): File "c:\users\hay square\appdata\local\programs\python\python37-32\Lib\threading.py", line 917, in _bootstrap_inner self.run() File "c:\users\hay square\appdata\local\programs\python\python37-32\Lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\HAYSQU~1\Desktop\NE86E9~1\ALLPRO~1\HAYHEA~1\HAYHEA~1\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\HAYSQU~1\Desktop\NE86E9~1\ALLPRO~1\HAYHEA~1\HAYHEA~1\lib\site-packages\django\core\management\commands\runserver.py", line 137, in inner_run handler = self.get_handler(*args, **options) File "C:\Users\HAYSQU~1\Desktop\NE86E9~1\ALLPRO~1\HAYHEA~1\HAYHEA~1\lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 27, in get_handler handler = super().get_handler(*args, **options) File "C:\Users\HAYSQU~1\Desktop\NE86E9~1\ALLPRO~1\HAYHEA~1\HAYHEA~1\lib\site-packages\django\core\management\commands\runserver.py", line 64, in get_handler return get_internal_wsgi_application() File "C:\Users\HAYSQU~1\Desktop\NE86E9~1\ALLPRO~1\HAYHEA~1\HAYHEA~1\lib\site-packages\django\core\servers\basehttp.py", line 45, in get_internal_wsgi_application return import_string(app_path) File "C:\Users\HAYSQU~1\Desktop\NE86E9~1\ALLPRO~1\HAYHEA~1\HAYHEA~1\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "C:\Users\HAYSQU~1\Desktop\NE86E9~1\ALLPRO~1\HAYHEA~1\HAYHEA~1\lib\importlib\__init__.py", line 127, in … -
How can you loop and display an element in a template depending on an integer passed as context?
Im having trouble displaying some divs using the context passed in through my view. In my views.py, i'm passing a value "total_used"" and "total". views.py: def home(request): context = { "reward": [ { "total": 5, "total_used": 2 } ] } return render(request, "web/index.html", context) Template: {% with ''|center:reward.total_used as range %} {% for _ in range %} <div class="red"></div> {% endfor %} {% endwith %} <div class="blue"></div> <div id="reward-count"> <h5>{{ reward.total_used }}/{{ reward.total }}</h5> </div> So for example, I want 2 divs with class red, and 3 divs (reward.total- reward.total_used) with the class blue. I have tried this but it didn't work: {% with ''|center:reward.total_used as range %} {% for _ in range %} <div class="red"></div> {% endfor %} {% endwith %} {% with ''|center:reward.total-reward.total_used as range %} {% for _ in range %} <div class="blue"></div> {% endfor %} {% endwith %} <div id="reward-count"> <h5>{{ reward.total_used }}/{{ reward.total }}</h5> </div> -
Create a new model based on two other existing models
I'm setting up a django project, I have 2 existing models Offers and Candidates, what I want to do is to create a new model (Scoring model) based on the two models Offers and Candidates, so i created a function add_line() in my Offer model that should create the Scoring object but it wont work even when I used the post_save signal, any suggestion? Candidates model: class Candidates(models.Model): nom = models.CharField(max_length = 50) prenom = models.CharField(max_length= 50) email = models.EmailField() phone = models.CharField(max_length=100) niveau_d_experience = models.IntegerField() etablissement_universitaire= models.CharField(max_length=150) niveau_options = (('Licence', 'Licence'), ('Master', 'Master'), ("Diplôme d'ingénieur", "Diplôme d'ingénieur"), ('Doctorat', 'Doctorat')) niveau_educatif = models.CharField(choices=niveau_options, max_length=100) profil = models.CharField(max_length=100) sexe_options = (('Mâle', 'Mâle'), ('Femelle', 'Femelle')) sexe = models.CharField(choices=sexe_options, max_length=100) offre = models.CharField(max_length= 200) CV = models.FileField() date_creation = models.DateTimeField(auto_now_add=True, auto_now=False) text_resume = models.TextField(editable=False) language = models.CharField(max_length = 20, editable=False) Offers model: class Offers(models.Model): titre = models.CharField(max_length=120) description = models.TextField() technologies = models.TextField() softskills = models.TextField() expérience = models.IntegerField() contrat_options= (('CDI', 'CDI'), ('CDD', 'CDD'), ('Freelance', 'Freelance'), ('Stage', 'Stage')) contrat = models.CharField(choices=contrat_options, max_length=100) mission_options = (('Interne', 'Interne'), ('Externe', 'Externe')) mission= models.CharField(choices=mission_options, max_length=100) validation_options = (('Offre validée', 'Offre validée'), ('Offre pourvue', 'Offre pourvue')) validation = models.CharField(choices =validation_options, max_length=100) def add_line(self, **kwargs): queryset = Candidates.objects.all() for … -
Why the attribute of an instance model does not change
I create a financial manager and I need the user to change the account activity (indicate an active account or not), but when I send the form for change, then the model attribute does not change and always remains TRUE I also tried to do this through a copy of the Account, but it was also not a result of the outcome Account.objects.get(user=self.request.user, id=id).is_active = False models.py class Account(models.Model): type_of_currency = models.CharField(max_length=20) user = models.ForeignKey(get_user_model(), blank=True, related_name='user_account', on_delete=models.CASCADE) count = models.DecimalField(max_digits=12, decimal_places=2, blank=True) created = models.DateTimeField(default=datetime.datetime.now) is_active = models.BooleanField() def __str__(self): return f'{self.type_of_currency} - {self.count}' views.py class AccountDetailView(DetailView, UpdateView): model = Account form_class = AccountCreateForm template_name = 'account_detail.html' def post(self, request, *args, **kwargs): id = self.request.POST['accountid'] self.request.user.user_account.get(id=6).is_active = False print(self.request.user.user_account.get( id=id).is_active) # always True why? return redirect('/counts/' + id) template {% extends 'base.html' %} {% block content %} <div class="col-sm-5"> <h1>account: {{ account.id }}</h1> <p><strong>Author:</strong> {{ account.user }}</p> <!-- author detail link not yet defined --> <p><strong>Type:</strong> {{ account.type_of_currency }}</p> <p><strong>count:</strong> {{ account.count }}</p> <p><strong>IsCreated:</strong> {{ account.created }}</p> <p><strong>IsActive:</strong>{{ account.is_active }}</p> <a class="btn btn-outline-primary" href="{% url 'account-list' %}">Back</a> {% if account.is_active %} <form method="post"> {% csrf_token %} <input type="hidden" value="{{ account.id }}" name="accountid"> <button type="submit" class="btn btn-outline-danger">Deactivate</button> </form> {% else … -
Handle Custom User Model Django-Allauth
I have a custom User Model that extends from Django's User and I want to register that user model instead of only the default one. For this, I am using the ACCOUNT_SIGNUP_FORM_CLASS setting as per allauth doc. This is what I have in settings.py: ACCOUNT_SIGNUP_FORM_CLASS = 'myapp.forms.SignupForm' And in myapp/forms.py: class SignupForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = MyUser def signup(self, request, user): print('test') user.save() MyUser(user=user).save() The signup() function should be executed: This class [SignupForm] should implement a def signup(self, request, user) method, where user represents the newly signed up user. But it isn't (test is not printed). Only User is saved, MyUser isn't. What am I doing wrong? -
Permission based on field value that user POSTs
A simplified view of my models: # models.py class User(models.Model): first_name = models.CharField() last_name = models.CharField() team = models.ForeignKey('Team') ... class Team(models.Model): name = models.CharField() class ToDo(models.Model): task = models.CharField() description = models.TextField() owner = models.ForeignKey('User') # serializers.py class ToDoSerializer(serializers.ModelSerializer): id = serializers.ReadOnlyField() class Meta: model = ToDo fields = '__all__' I want to create a POST endpoint to add a new ToDo object Users can create ToDo items for themselves Users can create ToDo items for others in their Team Users cannot create ToDo items for others who aren't in their team Question: Where do is write this logic I attempted this by using Permission classes but I don't know if that is the best place to do this # views.py class ToDoViewSet(viewsets.ModelViewSet): serializer_class = ToDoSerializer permission_classes = (CanAddToDo,) # permissions.py class CanAddToDo(BasePermission): def has_permission(self, request, view): owner_id = request.data.get('owner', None) # owner_id must be set if not owner_id: return False # User can create items if owner is themselves or someone in their team if User.objects.get(pk=owner_id).dealer == request.user.team: return True return False def has_object_permission(self, request, view, obj): """ Checks if the user owns the todo to edit """ return obj.owner == request.user What's bugging me about that is … -
Django Queryset - Issue with retrieving data from 3rd model
I want to get the 'profilephoto' from the Profile model for each Review that a Product has but that requires the Review models profile_id which is already apart of a context. Is there any way to do this? models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) fullname = models.CharField(max_length=100, null=True) dob = models.DateField(null=True) address = models.TextField(null=True) city = models.CharField(max_length=100, null=True) country = models.CharField(max_length=100, null=True) profilephoto = models.ImageField(default='profiles/default_profile.jpg', upload_to='profiles') class Product(models.Model): name = models.CharField(max_length=100) brand = models.CharField(max_length=100) cost = models.DecimalField(max_digits=8, decimal_places=2, default=0.00) category = models.CharField(max_length=100) releasedate = models.DateField() description = models.TextField() productphoto = models.ImageField(default='products/default_product.jpg', upload_to='products') class Review(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) rating = models.PositiveSmallIntegerField(default=1, validators = [MinValueValidator(1), MaxValueValidator(5)]) reviewtext = models.TextField() postdate = models.DateTimeField(auto_now_add=True) lastmodified = models.DateTimeField(auto_now=True) views.py class ProductDetailView(TemplateView): # template_name = 'reviewApp/test.html' template_name = 'reviewApp/product_detail.html' def get_context_data(self, **kwargs): prod = self.kwargs['pk'] context = super(ProductDetailView, self).get_context_data(**kwargs) context['Products'] = Product.objects.filter(id=prod) context['Reviews'] = Review.objects.filter(product=prod) prof = Review.objects.only('profile_id') context['Profiles'] = Profile.objects.filter(id__in=prof) return context