Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to show different column in select field django admin?
I've a model Customer: class Customer(models.Model): customer_name = models.CharField(max_length=128, null=True) contact_name = models.CharField(max_length=64) def __str__(self) -> str: return self.customer_name Customer Model is related with Event and CustomerEvent Model by ForiegnKey. In Django Admin panel we like to show customer_name in dropdown with Event which is working fine as Customer object str representation is self.customer_name. But In CustomerEvent we'd like show contact_name in admin panel dropdown which is not in __str__ representation. Here is my sample code: def render_change_form(self, request, context, *args, **kwargs): context['adminform'].form.fields['customer'].queryset = Customer.objects.filter(customer_type__iexact='I') return super(CustomerEventAdmin, self).render_change_form(request, context, *args, **kwargs) Please give me some idea to make it. -
How to execute a command using Python script on a terminal from html page in Django
I have a command which I want to run on a terminal in Django using a python script and not going on a terminal so how should I write the python script for it. Python command:- python ./ConfigManagement.py device_init -hn hostname -nr where device_init,-hn, hostname and -nr are arguments for the command. -
Need to return the value of a foreign key ID in a different model using django rest framework
models.py class Project(models.Model): project_name = models.CharField(max_length=20) client= models.ForeignKey(Client,on_delete=CASCADE,related_name="Client1",default=None) user=models.ManyToManyField(Default_User,related_name='users',default=None) description=models.TextField() type=models.TextField() class Meta: db_table ='Project' def __str__(self): return self.project_name class Job(models.Model): job_name=models.CharField(max_length=50) user= models.ForeignKey(Default_User,on_delete=CASCADE) project = ChainedForeignKey(Project,chained_field="user", chained_model_field="user",related_name='projects',show_all=False, auto_choose=True, sort=True) date = models.DateField(max_length=10,default=None) class Meta: db_table ='Job' def __str__(self): return '{}'.format(self.job_name) Serializers class ProjectSerializers(serializers.ModelSerializer): class Meta: model= Project fields= '__all__' class Job_Serializers(serializers.ModelSerializer): class Meta: model= Job fields = '__all__' viewsets class ProjectViewSet(viewsets.ModelViewSet): authentication_classes =[JWTAuthentication] permission_classes=(permissions.IsAdminUser,) queryset=models.Project.objects.all() serializer_class=serializers.ProjectSerializers filter_backends = [filters.SearchFilter] search_fields = ['project_name'] class Job_Viewset(viewsets.ModelViewSet): renderer_classes = (CustomRenderer, ) authentication_classes =[JWTAuthentication] permission_classes=(permissions.IsAdminUser,) queryset=models.Job.objects.all().order_by('-id') serializer_class=serializers.Job_Serializers Actually I need to get the project name from the Project model in the Job model. As now as project is a foreign key in Job model it is returning the project_id in the Job model but i need to get the project name along with the id in the job model response. I have tried with the queryset but i couldn't able to get the results which i expected. Need to get ike below results while using get call function. Result expected: { "id": 1, "job_name": "API for Timesheet", "date": "2022-03-08", "user": 2, "project": 1, "project_name": timesheet #need to get like this } -
How to select multiple posts through django checkboxes for comparison on a seperate page but pagination not allowing it
I'm a beginner in Django. Thanks for your help and patience. I have a model which I use to show a list of posts. I am using django pagination as there are many posts. I want the visitor to be able to select some posts through checkboxes. The selected posts are then used for comparison on a seperate page. In the html template, I have all the posts inside a form - each post is associated with a checkbox (checkbox is not part of the model). When a visitor selects some posts and clicks a submit button, then a view function returns a page with the selected posts for comparison. It all works fine, but the problem is with the pagination - i.e., when the visitor selects posts from different pages. For example, when selecting posts from the second page, those that were selected in the first page are not considered (no longer checked ?). I have looked at using sessions, form wizard, etc. But I still can't figure out how they can help or what is the appropriate approach for me to investigate more. Any guidance would be appreciated. -
Django ORM QuerySet Takes Too Much Time in Docker
I have a simple query in my django. values = ['profile_url', 'name','profit'] home = Home.objects.get(homename='Valley Homes') user_filters = {"name":"san agustin", "age":21} user_excludes = {} users = (User.objects.annotate(distinct_user=ArrayAgg(*values, distinct=True)).filter(home=home, **user_filters).select_related(*user_filters.keys()).exclude(**user_excludes).values(*values)) On local ec2 instance it takes up to 4 seconds to query On docker it takes up to 84 seconds which is horrible. I thought using select_related would shorten time but still it doesnt. Really need help in improving performance on docker. How can i make it faster like in local? -
I want to show User Groups along with user details in ListView in Django
I am trying to add User Groups in List View along with User Info but...... I know how to do in it DRF, In DRF I add groups fields class meta in serailizers.py, and then it works fine. But here I can not do it. Here is my code class UserListView(LoginRequiredMixin, ListView): login_url = '/' redirect_field_name = 'redirect_to' model = User template_name = 'user/list.html' context_object_name = 'user_list' paginate_by = 10 def get_queryset(self): comp_id=User.objects.filter(email=self.request.user).values_list('company_id', flat=True).first() if comp_id != None: return User.objects.filter(company_id=comp_id) else: return User.objects.all() def get_context_data(self, **kwargs): context = super(UserListView, self).get_context_data(**kwargs) user = self.get_queryset() page = self.request.GET.get('page') paginator = Paginator(user, self.paginate_by) try: user = paginator.page(page) except PageNotAnInteger: user = paginator.page(1) except EmptyPage: user = paginator.page(paginator.num_pages) context['user'] = user return context -
django rewrite many to many add method
I am new to django, I have a Profile object and trying to write subscriptions. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # follow subscribe follower = models.ManyToManyField(User, blank=1, related_name='prof_follower_set') followed = models.ManyToManyField(User, blank=1, related_name='prof_followed_set') the thing is, I need to forbidden a user to subscript to himself, therefore, I want to rewrite the add method of many to many field. I had a look on Manager and did not work out a way. I will be very grateful for your help. -
Update a model field when another modal field is updated
Having two models: class A(models.Model): project_code = models.CharField(max_length=250, null=False, blank=False) reference_code = models.CharField(max_length=250, null=False, blank=False, unique=True) quantity = models.CharField( max_length=250, null=True, blank=True, ) class B(models.Model): project_id = models.IntegerField( null=False, blank=False, default=0, ) quantity = models.CharField( max_length=250, null=True, blank=True, ) I would like to update B.quantity when A.quantity changes. How could I synchronize the two fields? When creating a B object, B.quantity always gets the value from existing A.quantity. I am newbie using Django ORM. I have been researching and found this in the official documentation, but it is not clear to me how to 'synchronize' Many-to-one relationships with a single field since it seems to synchronize the entire table. -
Partial model match in django?
I have a table in my db and I am connecting it to a Django model using "managed=False". The thing is I don't want all 300 columns on that table. I only need two or three column, can I create a model with db_table pointing to that table but not defining all columns? Appreciate your time in advance. -
Django many-to-many attribute with "through" model displayed on parent form
I'm new to Django and have been banging my head against the desk for a few days now trying to figure this one out. I apologize in advance if it's been asked/answered already. I'm building a basic restaurant inventory tracking app that allows the user to create ingredient inventory, create menus, and create items on those menus. When creating an item, the user should be able to define the ingredients that go into making that item AND the quantity of each ingredient required. When creating a menu item, I am trying to generate a form that allows the user to name the item, give it a price, then add ingredients one by one, with a given ingredient's quantity being selected as an ingredient is added. So something like this: Name: _______ Price: _______ Ingredient: ______ Quantity: _______ Ingredient: ______ Quantity: _______ Ingredient: ______ Quantity: _______ [Add another ingredient button] Here is my current code: # models.py class Ingredient(models.Model): GRAM = 'GR' OUNCE = 'OZ' ITEM = 'IT' UNIT_CHOICES = [ ('GR', 'Grams'), ('OZ', 'Ounces'), ('IT', 'Item') ] name = models.CharField(max_length=200) unitType = models.CharField(max_length=2, choices=UNIT_CHOICES, default=ITEM) unitCost = models.DecimalField(max_digits=10, decimal_places=2) inventoryQuantity = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.name class Menu(models.Model): name … -
'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte '
how solve this error? "'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte ' . while uplaoding csv file in django. Here view function def upload_csv(request): template = "upload_csv.html" if request.method == "GET": return render(request,template) csv_file=request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.error(request,'This is not a csv file') data_set = csv_file.read().decode('UTF-8') io_string =io.StringIO(data_set) next(io_string) for row in csv.reader(io_string,delimiter=',',quotechar="|"): _, created = Company.objects.update_or_create( name = row[0], hr_name =row[1], hr_email=row[2], hr_verified=row[3], user_id=row[4], primary_phone=row[5], comments=row[6], ) context={} return render(request, template,context) -
Allauth get_user_model() CustomUser issue
I am currently trying to get the user model in a function-based view but keep getting the following error. I have allauth installed and created a customer user using the allauth.account model. I attached my model and the migration. I have looked in my database and have users in, however every time I call the user in the view it gives me a customer user error. I have tried the other 2 methods that are commented out in the function view. error { Environment: Request Method: POST Request URL: http://127.0.0.1:8000/store/add_listing/ Django Version: 3.1.14 Python Version: 3.9.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'crispy_forms', 'allauth', 'allauth.account', 'accounts', 'web_pages', 'store'] Installed 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'] Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/get_printed/store/views.py", line 93, in AddListing current_user = request.CustomUser #.objects.filter(current_user) #get_user_model() Exception Type: AttributeError at /store/add_listing/ Exception Value: 'WSGIRequest' object has no attribute 'CustomUser' Views.py def AddListing(request): if request.method == 'POST': form = List_Item_Form(request.POST) if form.is_valid(): itemName = form.cleaned_data['item_name'] price = form.cleaned_data['price'] desc = form.cleaned_data['description'] quan = form.cleaned_data['quantity'] main_img = form.cleaned_data['main_image'] current_user = request.CustomUser #.objects.filter(current_user) … -
Reuse same image Django
I have a django model that has an image field. I want to change the field so it can upload a new image or reuse the same image that was already been uploaded. But I want the field so it can have an option to reuse the same image only on admin. If it is on form, it only can upload an image. How can I do that? The main thing is that the admin can have an option to upload a new image or reuse the same image that was already been uploaded. But the regular user can only upload a new image and doesn't have an option to reuse an image. Is there any way to solve this problem? -
django unable to create superuser
models from django.contrib.auth.models import User from django.db import models from django.contrib.auth.models import AbstractBaseUser, UserManager, PermissionsMixin class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=255, unique=True) objects = UserManager() USERNAME_FIELD = 'username' error: (env) ➜ autherization python manage.py createsuperuser Username: soubhagya Password: Password (again): Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 189, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/django/contrib/auth/models.py", line 163, in create_superuser return self._create_user(username, email, password, **extra_fields) File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/django/contrib/auth/models.py", line 144, in _create_user user = self.model(username=username, email=email, **extra_fields) File "/Users/soubhagyapradhan/Desktop/upwork/polyverse/polyverse_api/env/lib/python3.8/site-packages/django/db/models/base.py", line 503, in __init__ raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg)) TypeError: User() got an unexpected keyword argument 'email' (env) ➜ autherization I am trying to create superuser inside django shell Getting above error. Please take a look what can be the reason -
Disable login form alert for IsAuthenticated API views - DRF
I have some views that have the IsAuthenticated permission class. However, whenever I access these views, a JS alert pops up asking for credentials like so: How can I disable this, so that users are unable to log in via this view? I want users to only be able to log in via the Login view, which has a 2FA system. -
HTML for loop won't pickup the variable I ask for
I have a for loop in my HTML template, I want it to display certain information for the author of the posts but it won't display anything: {% for post.author in post %} <img class="rounded-circle profile-img" src="{{ post.author.profile.image.url }}"/> <div class="media-body"> <h2 class="account-heading">{{ view.kwargs.username }}</h2> <!-- only This works --> <p class="text-secondary">{{ post.author.first_name }} {{ post.author.last_name }}</p> <p class="text-secondary">{{ post.author.email }}</p> <div class="container"> <p class="lead"><Strong>Sobre mi:</strong></p> <p class="lead">{{ post.author.description }}</p> </div> <br> <p class="text-secondary">Se unió el {{ post.author.date_joined }}</p> <p class="text-secondary">Última vez visto: {{ post.author.last_login }}</p> <p class="mb-0">{{ post.author.about }}</p> </div> {% endfor %} Before I made those changes to the for loop it was working, but not exaclty like I wanted it to. The loop is made to display certain user's information, so I can't have it display the same info more than 1 time, that's why I'm not satisfied with the for loop here: {% for post in posts %} <img class="rounded-circle profile-img" src="{{ post.author.profile.image.url }}"/> <div class="media-body"> <h2 class="account-heading">{{ view.kwargs.username }}</h2> <!-- only This works --> <p class="text-secondary">{{ post.author.first_name }} {{ post.author.last_name }}</p> <p class="text-secondary">{{ post.author.email }}</p> <div class="container"> <p class="lead"><Strong>Sobre mi:</strong></p> <p class="lead">{{ post.author.description }}</p> </div> <br> <p class="text-secondary">Se unió el {{ post.author.date_joined }}</p> <p class="text-secondary">Última … -
geodjango creating GEOS multi geometries fails after python upgrade (M!)
I have an @property on a model that gets a bounding box for all the geometries associated with a dataset. This code has worked fine for a couple of years. Now, on a new M1 mac laptop, I upgraded Python (3.7.4 to 3.9.7) and the configuration of GDAL and GEOS was difficult. But as I understand, django.contrib.gis includes its own versions of those libraries. Relevent code snippets: from django.contrib.gis.geos import GeometryCollection, MultiPoint, Point from places.models import PlaceGeom from datasets.models import Dataset class Dataset(models.Model): fields … @property def bounds(self): dsgeoms=PlaceGeom.objects.values_list(‘geom’,flat=True).filter(place__dataset=self.label) print(tuple(dsgeoms[:2])) # (<Point object at 0x12ee39988>, <Point object at 0x12ee39a08>) gc = GeometryCollection(tuple(dsgeoms[:2])) return json.loads(gc.envelope.geojson) if pg_geoms.count() > 0 else None This crashes when creating the GeometryCollection with no real clue as to why, in PyCharm: “process finished with exit code 138 (interrupted by signal 10: SIGBUS)” in django shell: “67692 bus error ./manage.py shell” in browser: simply quits runserver So I simply tried the examples from the Geodjango docs at https://docs.djangoproject.com/en/2.2/ref/contrib/gis/geos/, and though the Point and LineString creation worked, GeometryCollection and MultiPoint did not, with the shell error "68483 segmentation fault ./manage.py shell" I'm stumped, but before I try building the bbox with Shapely and multiple transformations, thought I'd ask … -
supervisor-win How to use for windows server
I downloaded it using pip install supervisor-win, but I didn't know how to configure my Django project file.ini and give Supervisor to manage it. I know how to operate on Linux, not how to write configuration files and use them on Windows. this is supervisor-win https://pypi.org/project/supervisor-win/ -
how can i change this SQL to Django ORM code? (group by)
I need to retrieve the process element (by maximum processid) per unique serial number. I'm using mysql and this is my django model. class Sample(models.Model): processid = models.IntegerField(default=0) serialnumber = models.CharField(max_length=256) ## create_at = models.DateTimeField(null=True) class Process(models.Model): sample = models.ForeignKey(Sample, blank=False, null=True, on_delete=models.SET_NULL) And this is sql query what i need to change to django. SELECT process.* FROM process WHERE id in ( SELECT max(sample.processid) as processid from sample group by serialnumber ); -
Using the django registration redux package for user authentication
Whenever I try to go to .../accounts/register/ it just seems to give me a blank white page, it won't even display an error. I'm not sure why this is happening because I have previously tried out the same code for user registration on another web application (using the Django registration redux package) and it seemed to work fine! Would appreciate any ideas or help on how to fix this. how my files are organised (uni_fit is the app name) html code for registration_form.html html code for registration_closedd.html code in urls.py code in settings.py code in settings.py (2) the results on chrome when I search for [http://127.0.0.1:8000/accounts/register/] This is what I'm trying to get What I'm trying to get -
django-apscheduler don't in django-admin
I install django-apscheduler ,an I acording to document registed in the view ,but it don't in the admin site,how can I get it? import time from apscheduler.schedulers.background import BackgroundScheduler from django_apscheduler.jobstores import DjangoJobStore, register_events, register_job scheduler = BackgroundScheduler() scheduler.add_jobstore(DjangoJobStore(), "default") @register_job(scheduler, "interval", seconds=1) def test_job(): time.sleep(4) print("I'm a test job!") # raise ValueError("Olala!") register_events(scheduler) scheduler.start() print("Scheduler started!") -
Set is_staff to true for userthat login via django allauth google
I am using allauth in Django in order for users to login via their Google accounts. Everything works fine, user logs in, account is created and saved in the db, but the problem is I want the new users to automatically be staff members by setting is_staff to true. I was looking at the official docs on how to override data and I did this: in settings.py: ACCOUNT_FORMS = { 'signup': 'myapp.forms.MyCustomGoogleSignupForm' } and in myapp/forms.py (the directory that has the wsgi.py file. Is this the right location? I have not created a new app directory for loggin in with google.) class MyCustomGoogleSignupForm(SignupForm): def save(self, request): # Ensure you call the parent class's save. # .save() returns a User object. user = super(MyCustomGoogleSignupForm, self).save(request) # Add your own processing here. user.is_staff = True # You must return the original result. return user but this does not work. Anyone has any ideas? Thank you -
Data cannot saved in django formview
I'm going to receive data and save it using form and save it. But I can't get any result. Let me know what I'm doing wrong. I set up a model. And I wrote a form to get the input. Forms.Form was used. At first, I used modelform, but I wrote it like this because there seemed to be no difference. Is label important in the form? You can't get the data value because you can't connect the label? heeelp! models.py class PayHistory(models.Model): branch = models.ForeignKey(Branch, on_delete=models.CASCADE, null=True) package_recommandation_date = models.DateField(null=True) package_payment_date = models.DateField(null=True) ... forms.py class PackageForm(forms.Form): package_recommandation_date = forms.CharField(label='package_recommandation_date') package_payment_date = forms.CharField(label='package_payment_date') ... views.py class PackageView(FormView): model = PayHistory template_name = 'branches/package-create.html' success_url = reverse_lazy('/') form_class = PackageForm def form_valid(self, form): form = form.save(commit=False) form.save() return super().form_valid(form) # HTML {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="table-content"> <!-- 검색 --> <table border="0"> <tr class="input-tr"> <td><input type="date" class="input1" name="package_recommandation_date" value="{{ form.package_recommandation_date.value|default_if_none:'' }}" required> </td> <td><input type="date" class="input2" name="package_payment_date" value="{{ form.package_payment_date.value|default_if_none:'' }}"> </td> ... <td><button type="submit" class="input-button input16">적용</button></td> # static/js const package_recommandation_date = document.querySelector("package_recommandation_date"); const package_payment_date = document.querySelector("package_payment_date"); console.info(package_recommandation_date, package_payment_date) #output -> null null -
can I build django project use javascript api and react? [closed]
as title I want to build a Django project use javascript(or node.js) write api and react Can it be achieved? thx -
Using unittest.mock to mock a DRF response
My example is pretty basic: # urls.py from django.urls import include, path from rest_framework.routers import DefaultRouter from core import views router = DefaultRouter() router.register(r'core', views.CoreViewSet) urlpatterns = [ path('', include(router.urls)), ] # views.py from rest_framework import mixins, viewsets from .models import Numbers from .serializers import NumbersSerializer class CoreViewSet(viewsets.GenericViewSet, mixins.ListModelMixin): queryset = Numbers.objects.all() serializer_class = NumbersSerializer # serializers.py from rest_framework import serializers from .models import Numbers class NumbersSerializer(serializers.ModelSerializer): class Meta: model = Numbers fields = '__all__' # models.py from django.db import models # Create your models here. class Numbers(models.Model): odd = models.IntegerField() even = models.IntegerField() class Meta: db_table = 'numbers' What I'm trying to do is mock the request to the /core/ URI so it returns a mocked response and not the response from the database. For example, considering unit testing in a CI pipeline when the database isn't available. The below is what I have, but print(response.data) returns the actual response and not the mocked one: import unittest from unittest.mock import patch from rest_framework.test import APIClient class CoreTestCase(unittest.TestCase): @patch('core.views') def test_response(self, mock_get): mock_get.return_value = [{'hello': 'world'}] client = APIClient() response = client.get('/core/') print(response.data) Not finding the documentation very intuitive in figuring this out, so asking how I should be implementing …