Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to execute an if statement in ManyToMany Field in Django
I am trying to check if voter already exists in database and execute a different command id the voter exists or not but my if statement returns False if there is a match in the database. My views is: def vote(request, position_id, voting_id): voter = Voter.objects.filter(pk=voting_id) print(voter) position = get_object_or_404(Position, pk=position_id) try: selected_choice = position.candidate_set.get(pk=request.POST['choice']) except (KeyError, Candidate.DoesNotExist): return render(request, 'landing/detail.html', { 'position': position, 'error_message': "You didn't select a Choice." }) else: print(selected_choice.voted_by.all()) if voter in selected_choice.voted_by.all(): print("THIS DOES") else: print("THIS DOESN'T") # selected_choice.votes += 1 # selected_choice.save() return HttpResponseRedirect(reverse('results', args=(position.id,))) When I run this, I have some print statements and it prints; <QuerySet [<Voter: BIS/2019/12345>]> <QuerySet [<Voter: BIT/2020/54321>, <Voter: BIT/2019/12345>, <Voter: BIT/2018/12345>, <Voter: BIS/2020/54321>, <Voter: BIS/2019/12345>]> THIS DOESN'T I was hoping it will print 'THIS DOES' since the voter is in the selected_choice. What might I be doing wrong -
Django- ValueError: signal only works in main thread
is it at all possible to execute Django's call_command code within or alongside Django's signals? What I have tried so far is use a ModelForm to try and update a Model class using a function based views like so: # models.py class Foo(models.Model): ... many = models.ManyToManyField("FooMany") class FooMany(models.Model): ... many = models.CharField(choices=CHOICE, max_length=2) Now, every request to update this triggers a signal that's designed to run specific tests using Django's call_command # signals.py import ntpath from my_dir import execute @receiver(m2m_changed, sender=Executor.path.through) def run_test(sender, instance, action, **kwargs): files = instance.path.all() base = [ntpath.basename(str(f)) for f in files] for file in base: execute(file) # execute function comes next # my_dir.py def execute(file): with open("executor/results/output", "w") as FILE: call_command("test", f"executor.tests.{test}", verbosity=3, interactive=False, stdout=FILE) However, these all yield a server 500 error. Further investigation yielded a ValueError: signal only works in main thread, the reason I asked if it is possible to do it this way and if not could you suggest a different approach. Thank you. -
django model's inheritance
I want to have two registration type. for example : employee and employer type. i want two different form. i override AbstractUser and after i use this class (inheritance) class User(AbstractUser): age=models.BooleanField(default=True) class employee(User): is_employee=models.BooleanField(default=True) ser=models.BooleanField() sag=models.CharField(max_length=1) class Meta: verbose_name="employee" class employer(User): is_employer=models.BooleanField(default=True) address=models.CharField(max_length=100) but when i save employee or employer class also created User class. can i do when i save only employee save just that and not User -
django static png not found
when i go to localhost/static/images.png it shows image cannot be found i have added STATIC_URL = '/static/' staticfile_dir = [static_dir, ] please ignore .html and .css and .js file is polls folder already tried pycharms default path and base_dir then changed it to os.join also tried adding static file finder -
How to capture dropdown selection into a view for conversion to excel
Hello fellow learned friends. I'd like to add a filter to a model query from a dropdown selection before converting the results to excel for download. I can't get it right since I don't know how to capture the dropdown selected item into the view. How do I get it working?? def convert_to_excel(file_name, columns, values): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="{}.xls"'.format(file_name) wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet(file_name.capitalize()) # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() for row in values: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response def archive_to_excel(request): mark_list = Marks.objects.filter(school=request.user.school).annotate(total = \ F("eng") + F("kis") + F("mat") + F("che") + F("phy") + F("bio") + F("cre")+ F("ire")+ \ F("hre") + F("geo") + F("his") + F("agr") + F("hsc") + F("bst")+ F("mus")+ F("ger")+ F("fre"))\ .order_by('-total').annotate(mean = F('total')/15).values_list('student__name',\ 'student__adm', 'student__form__name', 'student__stream__name', 'student__kcpe','eng','kis','mat','che','phy','bio','cre','ire','hre','geo',\ 'his','agr','total','mean').order_by('-id') columns = [('name'), ('adm'),('form'),('stream'), ('kcpe'), ('eng'), ('kis'), ('mat'), ('che'), ('phy'), ('bio'), ('cre'),\ ('ire'), ('hre'), ('geo'), ('his'), ('agr'),('total'),('mean') ] return convert_to_excel("Marks", columns, mark_list) -
How to filter objects according to the selected month in Django?
I have a Customer model. This model has a created_date field. I want to list all customers created in the selected month. I think I can use timedelta for that but I cannot figure out how can I applied that. How can I filtering the customers according to the selected month? views.py def log_records(request): .... form = MyForm() if request.method == 'POST': form = MyForm(request.POST) if form.is_valid(): cd = form.cleaned_data months = cd.get('months') selected_month = datetime.today() - timedelta(days=...somethin...) selected_month_customers = Customer.objects.filter(company=userP[0].company, created_date__gte=last_month.count() ... context = {'selected_month_customers': selected_month_customers,...} return render(request, 'logs.html', context) models.py class Customer(models.Model): ... created_date = models.DateTimeField(auto_now_add=True) ... forms.py class MyForm(forms.Form): MONTH_CHOICES = [ ('January', 'January'), ('February', 'February'), ('March', 'March'), ('April', 'April'), ('May', 'May'), ('June', 'June'), ('July', 'July'), ('August', 'August'), ('September', 'September'), ('October', 'October'), ('November', 'November'), ('December', 'December'), ] months = forms.CharField(widget=forms.Select(choices=MONTH_CHOICES), label="Select a month ") -
hardcoded url issue when drag & drop images with django-markdownx through S3
My website works perfectly fine with django-markdownx, unless I upload images. When I drag and drop image on markdownx form, auto generated image url is added in form like below: As you see, image is shown just fine. My storage is AWS s3, and I'm using private bucket. The problem occurs, however, an hour later. In the markdown url query parameter X-Amz-Expires=3600, which is an hour. So after that the url is no longer valid, saying request has expired. This is another expired url, but you get the idea. I use django-storages, boto3, AWS S3 for file storages. According to django-storages doc, AWS_QUERYSTRING_EXPIRE (optional; default is 3600 seconds) The number of seconds that a generated URL is valid for. I might extend expiry time like super long as suggested in other post in SO, but doesn't that mean I should update at least once every super long time period? That doesn't seem the right way. Some suggested making S3 bucket public, but I don't want allow anyone to download my image. I delved in django-markdownx doc and github, without making much progress. How can I get dynamically made presigned url when uploading image using djang-markdownx? Let me know if I'm … -
FieldDoesNotExist error with django-mongoengine?
I want to use mongoDB as my primary database in my new django (v 3.1.2) project. So far I have not created any models and only created a django project with one app and then installed pip install django-mongoengine. I then edited my settings.py file and included these custom codes. Mongodb is running as a service in my system. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home.apps.HomeConfig', 'django_mongoengine', 'django_mongoengine.mongo_auth', 'django_mongoengine.mongo_admin', ] # MongoDB settings MONGODB_DATABASES = { 'default': {'name': 'django_mongoengine'} } DATABASES = { 'default': {'ENGINE': 'django.db.backends.dummy'} } AUTH_USER_MODEL = 'mongo_auth.MongoUser' AUTHENTICATION_BACKENDS = ( 'django_mongoengine.mongo_auth.backends.MongoEngineBackend', ) SESSION_ENGINE = 'django_mongoengine.sessions' But when I started my server python manage.py runserver I am getting this error File "/home/Eka/.virtualenvs/Env/lib/python3.6/site-packages/django_mongoengine/forms/document_options.py", line 4, in <module> from django.db.models.fields import FieldDoesNotExist ImportError: cannot import name 'FieldDoesNotExist' I also tried to import django_mongoengine using a different terminal, which also yield the same error. How can we solve it? -
Django: How to retrieve a Queryset of the latest, uniquely named records with a MySQL database
I require a query that can search my model for the latest, unique records and return a queryset of the results. I need distinct on setup_name and latest on updated models.py class VehicleSetupModel(models.Model): inertia = models.IntegerField() tyre_pressure = models.IntegerField() class StandardVehicleSetupModel(VehicleSetupModel): setup_name = models.CharField(max_length=20) updated = models.DateTimeField(auto_now=True) vehicle = models.ForeignKey(VehicleModel, on_delete=models.CASCADE) What I've tried I tried the following: StandardVehicleSetupModel.objects.all().order_by('updated').distinct('updated') but MySQL does not support DISTINCT ON querys. Table Layout (DD-MM-YYYY) setup_name | updated | vehicle ---------------------------------------------------------- TEH 10-10-2020 1 TEH 11-10-2020 1 TEL 10-10-2020 1 TEL 08-10-2020 1 TEL 01-10-2020 1 TEP 01-10-2020 1 Expected Result (DD-MM-YYYY) setup_name | updated | vehicle ---------------------------------------------------------- TEH 11-10-2020 1 TEL 10-10-2020 1 TEP 01-10-2020 1 -
import models from another directory
I'm new in Django. i am following a tutorial and now i have a problem . my directory tree is like and in /pages/views i have this from django.http import HttpResponse from django.shortcuts import render def home_view(*args, **kwargs): return "<h1>Hello world</h1>" and in urls.py i have this from django.contrib import admin from django.urls import path from pages.views import home_view urlpatterns = [ path('', home_view, name='home'), path('admin/', admin.site.urls), ] ***but it can't recognize pages *** i also tried these solution but didn't work!what do i missing? even i added these codes to settings.py import os import sys BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(os.path.join(BASE_DIR, 'pages')) { django 3.1 } -
django- django admin Modify External Model Field Name
I added fields from existing models(ProUser), fields from external models(Point) to Admin. @admin.register(ProUser) class ProUserAdmin(admin.ModelAdmin): list_display = [ "id", "user_nm", "user_ty", "user_tel", "user_email", "point_amt", **One of the fields in the 'Point' model, not in the 'ProUser' model** "user_join_dts", ] In ProUser's model, [user_nm = models.CharField ("app user name", max_length=10)] As such, the field name "app user name" was specified. Therefore, the field name appears to be [app user name] instead of [user name] in Admin. As such, I would like to name the fields imported from the Point model. For now, [pointamt] is the name of the field. I want the field "point_amt" to be the field name "user point" in Admin. Is there a way? -
django_filters pass arguments (choices) to FilterSet
I am building an Electronics e-commerce website with Django. I am struggling with django_filters. I have models Category, Subcategory and Product. When user visits Category Page I would like to render Product brands filter depending on that Category. For example, if user visits Phone Category I would like to render brands filter: Apple, Samsung, Xiaomi etc. I achieved something similar like that but downside is it shows all brands (product brands not related to Category): Canon, Samsung, Apple, Bosch etc. So I am trying query Product brands related to that Category and pass them as choices to Filterset. How can I pass brand choices from view to FilterSet? #===models.py===== class Category(models.Model): title = models.CharField(max_length=30, verbose_name=_('Названия')) slug = models.SlugField(null=False, unique=True) image = models.ImageField(blank=True, upload_to='category_images/', verbose_name=_('Основное фото')) created_at = models.DateTimeField(auto_now_add=True, verbose_name=_('Добавлено в')) updated_at = models.DateTimeField(auto_now=True, verbose_name=_('Изменено в')) class Subcategory(models.Model): category = models.ForeignKey(Category, related_name='subcategories', null=True, blank=True, on_delete=models.SET_NULL, verbose_name=_('Категория')) title = models.CharField(max_length=150, blank=True, verbose_name=_('Названия')) image = models.ImageField(blank=True, upload_to='subcategory_images/', verbose_name=_('Основное фото')) slug = models.SlugField(max_length=150, unique=True) created_at = models.DateTimeField(auto_now_add=True, verbose_name=_('Добавлено в')) updated_at = models.DateTimeField(auto_now=True, verbose_name=_('Изменено в')) class Product(models.Model): recommended_choices = (('YES', 'ДА'), ('NO', 'НЕТ')) title = models.CharField(max_length=200, blank=True, verbose_name=_('Названия')) category = models.ForeignKey(Category, related_name='category_items', on_delete=models.SET_NULL, null=True, blank=True, verbose_name=_('Категория')) subcategory = models.ForeignKey(Subcategory, related_name='subcategory_items', on_delete=models.SET_NULL, blank=True, null=True, verbose_name=_('Подкатегория')) price … -
trying to get my views.py and urls.py to work properly
I am currently trying to get my database that I created to display on my Djnago server however I keep getting errors for my FruitModel saying that there are no objects however I have created objects for the FruitModel in my datbase using "record = FruitModel.objects.create(name='banana', price='4.00'). I am also getting an unable to display error for my urls when I loaded up my server. Here is my code for Views.py and for urls.py: (views.py code) from django.shortcuts import render, redirect from catalog.models import FruitModel from catalog.forms import FruitForm from django.http import HttpResponse # Create your views here. def FruitView(request): fruit = FruitModel.objects.all() html = '' for fruits in fruit: var = f'<li> {fruits.name} </li><br>' html = html + var return HttpResponse(html,status = 200) def FruitIDView(request,name): fruits = FruitModel.objects.get(name = f'{fruits.name}') html = f'<h2>{fruits.name}</h2><br>' return HttpResponse(html, status=200) (urls.py code) from django.contrib import admin from django.urls import path from django.conf.urls import url from catalog import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^FruitView/?$', views.FruitView), ] -
Django: best way to redirect empty results pages to root page
I have an app that paginates and show objects in a Django list view. I'm using paginate_by=20 in my list view. When I have 20+ objects and Google indexes the second results page /results/?page=2. Then when results go below 20 objects, this second page goes to 404. What is the best way to redirect page 2 to /results/ when page 2, 3 etc don't return any results. I thought about writing a custom 404 view to strip out the URL parameters, but I guess it's best to catch this in the list view itself? -
Iterating a Django Form over a FileField which accepts multiple file uploads
I have a list containing files (say images) uploaded by a user. I need a user input against each file (say if he likes the image or not). User input can be collected through Django Forms. How can I do this if I need to : In a single view and URL Saving user input relative the file in the database I am only struggling with looping through the files in a single view and saving user inputs. -
Automatically updating a model field when it is created
I would like to automatically update a model field when it is created. So this is my situation. I have a custom User model that my customer can use to login. After they login, they will go to the account/profile page, which has a link to a form. Currently, when the user submits the form, it creates an instance of the LevelTest model(which is something I just need for the website to work). Here is the view class for the form: class LevelTestView(generic.CreateView): template_name = "leads/leveltest.html" form_class = LevelTestModelForm def get_success_url(self): return reverse("profile-page") and here is the LevelTestModelForm: class LevelTestModelForm(forms.ModelForm): class Meta: model = LevelTest fields = ( 'first_name', 'last_name', 'age', 'username', ) What I want to fill in automatically is the username field. In fact, I wish it doesn't even show up on the form itself when the user types in. The username is a field in the User Model, so I just want the new LevelTest's username field filled in with the current user's username. Hence, I used a post_save signal like below(which doesn't work): def post_leveltest_created_signal(sender, instance, created, **kwargs): if created: instance.objects.update( username=instance.user.username, description='Add Description', phone_number=instance.user.cellphone, email=instance.user.username, ) post_save.connect(post_leveltest_created_signal, sender=LevelTest) I hope you guys could help me … -
how to send an alert message to other web page when any model field in changed
i have an model in django with name offer : class Offer(models.Model): Auction_id=models.CharField(max_length=20,verbose_name = "Auction ID",default=number) Offer_Name=models.CharField(max_length=200,verbose_name = "Auction Name") Auction_des=models.CharField(max_length=50,verbose_name = "Auction Description") Bid_Start_Time=models.TimeField(auto_now=False, auto_now_add=False) Bid_End_Time=models.TimeField(auto_now=False, auto_now_add=False) and I have a Bid web page displaying details related to offer. I want to display an alert message to Bid web page everytime Bid end time in offer is changed. Through init and save method in offer i can check whether Bid end time is modififed or not but i'm not able to display alert message in Bid web page. -
How to decide where to put a function in django fat model implemantation
I want to know where to put a function on models that related to multiple models. I have four models: 1- custom user 2- office 3- company 4- vehicle every vehicle, user and office has a foreign key to company. I want to have all vehicles from a company I have tried to put a staticmethod on vehicles to get appropriate vehicles but I am not sure this is the right way of doing things because I have to pass request to models. @staticmethod def get_current_company_vehicles(request): Vehicle.objects.filter( located_office__in=CompanyOffice.objects.filter(company=request.user.company).values_list('pk') ) Where would you guys put the function and how to decide where a functions should go? -
Spring password encoder for the default Django password format (pbkdf2_sha256)
I am working on a Spring Boot application using Spring Security connected to a database originally generated by Django, in which all of the user passwords are stored in Django's pbkdf2_sha256 format. <algorithm>$<iterations>$<salt>$<hash> Looking at Spring Security's Pbkdf2PasswordEncoder, I was able to mostly figure it out and create an encoder that is able to encode and match Django's format. After successfully unit testing it, I tried it on a sample value generated by Django... and it failed. Why is this encoder not matching Django-generated values? Is Django performing some ~magic~ under the hood? I have also tried multiple replacements for Java's SecurityFactory implementation. This line in Django's source code caught my attention as well, but writing the equivalent Kotlin did not fix the issue. class DjangoPbkdf2PasswordEncoder : PasswordEncoder { companion object { private const val PREFIX = "pbkdf2_sha256" private const val SEPARATOR = "\$" private const val ITERATIONS = 180000 private const val HASH_WIDTH = 256 private const val ALGORITHM = "PBKDF2WithHmacSHA256" } private val saltGenerator: BytesKeyGenerator = KeyGenerators.secureRandom() private fun base64Decode(string: String): ByteArray { return Base64.getDecoder().decode(string) } private fun base64Encode(bytes: ByteArray): String { return Base64.getEncoder().encodeToString(bytes) } override fun encode(rawPassword: CharSequence): String { val salt = saltGenerator.generateKey() val hash = … -
To add values to a django model while I add value to another model
Let's say I have a model 'Books' and another model 'Products'. When I add a Book from django admin, I want the Book name and Book Code to be added to the Model 'Products'. -
"instance = my_model(user=user)" throws "my_model.user" must be a "User" instance when using AbstractBaseUser
I have created an AbstractBaseUser by the following #users/managers.py from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifiers for authentication instead of usernames. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('Du skal indtaste en email')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) #users/models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.utils.translation import gettext_lazy as _ from django.utils import timezone from .managers import CustomUserManager from django.conf import settings class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('E-mail'), unique=True) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) wants_email = models.BooleanField(_("Send mig emails"),default=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email my creation-form #users/forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField(error_messages={"unique":"This … -
'User' object has no attribute 'is_staff'
I have created my own user model by using AbstractBaseUser . I create the super user through terminal , which is created successfully . But when I go to the admin side and wrote the password and email there, This throw me the error that 'User' object has no attribute 'is_staff'. My models.py file is: class UserManager(BaseUserManager): def create_user(self, email, full_name=None, password=None, is_staff=False, is_admin=False): if not email: raise ValueError("User must have an email") if not password: raise ValueError("User must have a password") user_obj = self.model(email=self.normalize_email(email), full_name=full_name) user_obj.set_password(password) user_obj.staff = is_staff user_obj.admin = is_admin user_obj.save(using=self._db) return user_obj def create_staffuser(self,email,full_name=None,password=None): user = self.create_user(email, full_name=full_name,password=password) return user def create_superuser(self,email, full_name=None,password=None): user = self.create_user(email, full_name=full_name, password=password) return user class User(AbstractBaseUser): full_name = models.CharField(max_length=255, blank=True, null=True) sur_name = models.CharField(max_length=255, blank=True, null=True) email = models.EmailField(max_length=255 ,unique=True) choose_subject = models.CharField(choices=SUBJECT_CHOICES , max_length=100) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) time_stamp = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] object = UserManager() def __str__(self): return self.full_name -
T Format date inside json
I am getting json from backend like this : { "datas":[ { "id":4, "create_date":"2021-03-18T21:11:57.239Z" }, { "id":5, "create_date":"2021-03-19T19:37:05.829Z" } ] } and looping through json like below : $(data.datas).each(function(index,value){ html += `<tr><th scope="row">${index+1}</th> <td>${value.id}</td> <td>${value.create_date}</td> <td><a href="#" class="btn btn-outline-dark">View Car</a></td> </tr>` }) But, here create_date is just printing in td column like this 2021-03-18T21:11:57.239Z . So, how can i make this display like this 2021-03-18 & 21:11 am/pm in each tds ? My attempt : var created_date = value.create_date; console.log(created_date.split("T")[0]);//2021-03-18 console.log(created_date.split("T")[1])//21:11:57.239Z (how can i remove 57.239Z..) I am open for both solution i.e : backend as well as frontend . For my backend i am using django let me know if you need to see any code from backend . -
Django Reloading specific part of a page using AJAX
I am attaching another stackoverflow answer here. I have no idea on Javascript or Ajax. So can someone please let me know how to reload a div using Ajax to get the data from the included html into the original HTML , Thanks. The motive is to reload a div alone without refreshing the whole page. Other Stackoverflow answer : To treat the same view in a different way if you receive an ajax request. I would suggest splitting your result-page.html into two templates, one that contains only the div that you want, and one that contains everything else and includes the other template (see django's include tag). In your view then you can do something like the following: views.py : def sort(request): objs = any_models.objects.all() context = { 'objs' : objs , } if request.is_ajax(): template = 'partial-results.html' else: template = 'result-page.html' return render_to_response(template, context ,context_instance=RequestContext(request)) results-page.html: <html> <div> blah blah</div> <div id="results"> {% include "partial-results.html" %} #I want to reload only this div by sending ajax req to views and getting the partial html uploaded and thus this section which includes the partial gets updated without reloading the entire page... </div> <div> some more stuff </div> </html> partial-results.html: … -
django -View screen on django admin page
if I click ID 1 on the current screen, I want to decorate it with a non-modifiable and read-only screen. However, currently, clicking on the ID 1 value will access the screen that can be modified. What are the options? There is a separate modification button, and I want to be read-only before I modify it.