Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error while accessing Django model in admin view
I was trying to access objects of StockDailyPrice model from my Django Admin view. But I'm seeing the following error while doing so Environment: Request Method: GET Request URL: http://localhost:8000/admin/api/stockdailyprice/ Django Version: 4.0.3 Python Version: 3.9.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api', 'rest_framework', 'corsheaders'] Installed Middleware: ['corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/Users/bharathkumargundala/otsiot/crosspoints-backend/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) The above exception (operator does not exist: character varying = bigint LINE 1: ..."api_stock" ON ("api_stockdailyprice"."symbol_id" = "api_sto... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. ) was the direct cause of the following exception: File "/Users/bharathkumargundala/otsiot/crosspoints-backend/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Users/bharathkumargundala/otsiot/crosspoints-backend/venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/bharathkumargundala/otsiot/crosspoints-backend/venv/lib/python3.9/site-packages/django/contrib/admin/options.py", line 683, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/Users/bharathkumargundala/otsiot/crosspoints-backend/venv/lib/python3.9/site-packages/django/utils/decorators.py", line 133, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/bharathkumargundala/otsiot/crosspoints-backend/venv/lib/python3.9/site-packages/django/views/decorators/cache.py", line 62, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/Users/bharathkumargundala/otsiot/crosspoints-backend/venv/lib/python3.9/site-packages/django/contrib/admin/sites.py", line 242, in inner return view(request, *args, **kwargs) File "/Users/bharathkumargundala/otsiot/crosspoints-backend/venv/lib/python3.9/site-packages/django/utils/decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) File "/Users/bharathkumargundala/otsiot/crosspoints-backend/venv/lib/python3.9/site-packages/django/utils/decorators.py", line 133, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/bharathkumargundala/otsiot/crosspoints-backend/venv/lib/python3.9/site-packages/django/contrib/admin/options.py", … -
Populating drop-down list with strings, but want to send integer 'id' in form
So I have a Django form where one of the fields selected_candidate is a drop down menu of candidates that exist in an election/vote. The field is currently a ChoiceField because when I use and IntegerField the dropdown menu is not populated. Here is the vote function def vote(request, id): election_to_vote = elections[id] candidates_to_vote = () for i in range(len(candidates)): if candidates[i][3] == id: candidates_to_vote += ((candidates[i][0], candidates[i][1]), ) if request.method == 'POST': form = VoteForm(request.POST) if form.is_valid(): data = form.cleaned_data pps = request.POST.get('user_pps') cand = request.POST.get('selected_candidate') context = { 'form':form } return render(request, 'vote/test.html', context) else: form = VoteForm() form.fields['selected_candidate'].choices = [(c[0], c[1]) for c in candidates_to_vote] context = { 'form': form, 'election': election_to_vote, 'candidates': candidates_to_vote } return render(request, 'vote/vote.html', context) I am never able to pass the form.is_valid() statement. It gives me the following error: selected_candidate: Select a valid choice. 0 is not one of the available choices. I know that this is because I am passing the id associated with the candidate, but populating the list with the candidates name, which is a string, but I'm not sure how exactly I would populate the list with a string, but send off the canidates ID which is an … -
How to pass data from form in template to django views?
So I have this little project with messages and comments and i don't know how to save particular comment to particular message. Does anybody know how can i get message.id from template and send it to views.py? {% for message in messages_all %} <ul> <li>@{{message.host}}</li> <li>{{message.body}}</li> </ul> {% for comment in comments_all %} {% if comment.message == message %} <ul> <li>{{comment.body}}</li> </ul> {% endif %} {% endfor %} {% if request.user.is_authenticated %} <form method="POST"> {% csrf_token %} {{form}} <input type="submit" value="Dodaj komentarz"> </form> {% endif %} <hr> {% endfor %} -
Issue importing modules with Django, but runs fine when I run it independently using '-m' flag
Currently I have a python project with the following directory structure. I can run the demo.py file directly fine (without importing it in my Django project) from the outermost directory shown above using the following command: python -m ObjectSegmentation.segmentation_api.apps.tools.demo However, in my Django project, I need to import the demo.py file in my django views.py file, but when I do so, I get the following error: from ObjectSegmentation.segmentation_api.apps.tools.test import * ModuleNotFoundError: No module named 'ObjectSegmentation' These are the first few lines from demo.py (including line 4) where the error occurs. My installed apps in settings.py for the whole project look like this: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.tools.demo', 'rest_framework' ] How can I make it so that the imports work with both the project run independently and imported in my django project? -
How to check script is still running or not (which is called within subprcoess) in django
I am working on Django framework, there inside some function need to call one script (it is shell script). So have called it through subprocess.Popen(command). def func(request): if request.method=="POST": '''Collect data''' subprocess.Popen(command, shell=True) return render() The command which is inside subprocess.Popem may run for sometime. Now have to check whether this command is still running or not, means status of command whether it is running or completed. Could anyone help here? Thanks. -
django dynamic content in query
I am trying to "DRY" my code and would like to create a function to make my query dynamic. The code that I currently use is : rightone = [] for item in taglist: #taglist is a list of model instances, not relevant here content = content.filter(tags__title=item.title) #tags here is a M2M key : my problem, content is a query rightone.append(content) tagproofquery = rightone[-1] and I would like to convert it to: def uniquetogether(queryset,data, model): rightone = [] for item in queryset: content = data.filter(tags__title=item.title) # <--- problem is here with tags rightone.append(content) tagproofquery = rightone[-1] return tagproofquery I have no idea how to replace my M2M "tags" as in tags__title=item.title with the "model" parameter of my function. I tried f strings but it failed miserably (of course). Is there a way to do this? Many thanks -
How to add actions to Python django admin page
I have a django project in which the the form records the name and the email addresses of the users and I was able to put that data using forms.py and models.py. What I want to do nextis to create an action through which I can download that in csv file. My admin page looks like this now and I want to add action right above. -
Django- how to add user profile permissions based for selected users
In my Django app, I have a user_profile model (below). This model has an is_adm boolean which is True/False depending on whether or not the user is an 'administrator': user_profile/models.py: class User(AbstractBaseUser, PermissionsMixin): username = models.CharField('username', max_length=50, unique=True) email = models.EmailField('email address', unique=True) first_name = models.CharField(max_length=20, blank=True, null=True) last_name = models.CharField(max_length=20, blank=True, null=True) is_adm = models.BooleanField(default=False) Separately I have a posts model for blog posts. There is an admin panel for this model. posts/models.py: class Posts(models.Model): title = models.CharField(max_length=300, default='') publish_date = models.DateField(blank=True, null=True) author = models.CharField(max_length=300) copy = models.TextField(blank=True, default='') link = models.URLField(blank=True) source = models.TextField(default='', blank=True) published = models.BooleanField(default=False) I want the ability for is_adm = True users to be able to: add a Post model instance in the admin panel delete any Post model instance in the admin panel view any Post model instance in the admin panel edit certain fields in the Posts admin panel (every field except for copy and source) I know that Django has Permissions and Authorization: https://docs.djangoproject.com/en/2.2/topics/auth/default/#permissions-and-authorization But how do I add these methods like: has_view_permission(), has_add_permission(), has_change_permission() and has_delete_permission()... do I add them to the User class? Or somewhere else in the user_profile/models.py file? -
'signupform' object has no attribute 'email'
i am trying to send mail using django when a person login but i get error ,'signupform' object has no attribute 'email' and it says error at line 84 which is mentioned in views.py here is forms.py signupform(UserCreationForm): email=forms.EmailField(max_length=50,help_text='Required',widget=forms.EmailInput(attrs={'placeholder':'email'})) password1=forms.CharField(max_length=50,widget=forms.PasswordInput(attrs={'placeholder':'password'})) password2=forms.CharField(max_length=50,widget=forms.PasswordInput(attrs={'placeholder':'Re Enter password'})) class Meta: model=User fields=['username','email','password1','password2'] widgets={ 'username':TextInput(attrs={'placeholder':'username'}) } here is views.py def signupview(request): form=signupform() if request.method=='POST': form=signupform(request.POST) if form.is_valid(): subject='welcome to blog ' message='its our pleasure to have you ' send_mail(subject, message, settings.EMAIL_HOST_USER [form.email],fail_silently=False,) #line 84 form.save() return redirect('/blogapp/') else: form=signupform() context={'form':form} return render(request,'blogapp/signupform.html',context) -
Django: Pass queryset from template to view
I'm trying to send a queryset from a filter (or the object itself) from a template to a view: Here is the first view sending my filter: def view_one(request): objects = Model.objects.all() filtre = ModelFilter(request.GET, queryset=objects) return render(request, 'template.html', locals()) Here is the template where i'm trying to send the queryset into my view_two {{ filtre.qs }} # With this i can access my queryset <a class="button" href="{% url 'view_two' %}">Send queryset</a> And now accessing the filter or queryset: def view_two(request): print(request.GET) print(request.GET.get('filtre')) How can i do that ? Because from what django can pass through url, object and queryset are not a possibility .... -
how do I filter all the shipping address objects associated with specific order
how do I filter all the shipping address objects associated with specific order, so when someone orders a product with a shipping address I wanna get that address and render it to the template specific to that order. I would really appreciate your help, thx! models.py class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) class Product(models.Model): name = models.CharField(max_length=150) description = models.TextField() class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) address_one = models.CharField(max_length=200) views.py @login_required def orders(request): orderitems = OrderItem.objects.filter(order__customer__user=request.user) #how do I get the shipping address associated with order shipping = ShippingAddress.objects.filter() context = {"orderitems": orderitems, "shipping": shipping} HTML {% for orderitem in orderitems %} <div class="order-data-view"> <div class="order">{{ orderitem.product.name }}</div> <div class="date">{{ orderitem.date_added }}</div> <div class="status">dummydata</div> <div class="delivering-to">{{ address_one }}</div> </div> {% endfor %} -
Django - how to make an imagefield store multiple image files and display in html
in my html I have a field called "all photos", which should contain all photos uploaded. my questions are: how to make an imagefield store multiple images files (e.g. .jpg/.png)? how to dispaly all files of this imagefield in html as one field, not as pictures but as multiple clickable links with file names, like it is shown in django admin, e.g. model.py class Order(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT, related_name="order_users",blank=True, null=True) user_name = models.TextField(blank=True, null=True) order_ref = models.TextField(blank=True, null=True) order_time = models.TextField(blank=True, null=True) ... remark = models.TextField(blank=True, null=True) image = models.ImageField(blank=True, null=True, upload_to='images') view.py @login_required def staff_order(request, id): if request.method == "POST": order = Order.objects.get(pk=id) order.email = request.POST['email'] order.image = request.FILES['pic'] order.save() return render(request, 'OnlinePricing/staff_order.html', {'order': order, 'id': id, 'message': ['success', 'order updated.']}) else: order = Order.objects.get(pk = id) return render(request, 'OnlinePricing/staff_order.html', {'order': order, 'id': id, 'message': ['success', 'order updated.']}) html: <form> ... <label>upload photos:</label> <input name="pic" type="file" /></th> <label>all photos: </label><img src= "{{ order.image.url }}"></th> </form> -
Allow the user to crop image manually django
I'm stuck with a problem for a long time on the website I'm working on with django. In my django model, I've added an Image field for the profile pic, using django_resized So now when an user is choosing a pic, I'm cropping and resizing it as a square of 315*315. But I can only choose where the pic is cropped (here in the middle). In some cases, the people's faces are not exactly in the center of the pic and that's a problem. I would like to allow the user to choose manually where to crop the image (with a square to move on the pic), just as all the social medias are doing when you upload a profile pic. Here's my code, thank you very much in advance. from django.db import models from django_resized import ResizedImageField class Account(models.Model): profile_pic = ResizedImageField(size=[315, 315], crop=['middle', 'center'], quality=99, default="default_profile_pic.png", null=True, blank=True) -
How to trim/strip leading whitespaces from StringField for list view in Django/Mongodb?
Want to sort data by names, but unfortunately there are many data with leading whitespaces, that is why rest_framework.filters.OrderingFilter doesn't work properly. Mongo, DRF are used in my project. My model: from mongoengine import DynamicDocument, fields class Book(DynamicDocument): name = fields.StringField(required=True) description = fields.StringField(blank=True, null=True) meta = { 'collection': 'books', 'strict': False, } My view: from rest_framework.filters import OrderingFilter from rest_framework_mongoengine import viewsets from core.serializers import BookSerializer from core.models import Book class BookViewSet(viewsets.ModelViewSet): serializer_class = BookSerializer queryset = Book.objects.all() filter_backends = [OrderingFilter] ordering_fields = ['name'] ordering = ['name'] Someone has any idea, how to solve that? Try to annotate queryset: from django.db.models import F, Func ... class BookViewSet(viewsets.ModelViewSet): ... def get_queryset(self): queryset = self.queryset.annotate(name_lower=Func(F('name'), function='LOWER')) -
Django query data based on checkbox
I am trying to query data, brands of a certain items based on checkboxes. If no checkboxes are checked, then all brands are shown, If a checkbox with, lets say django is checked, then all brands of brand django is query from the db. Here is the checkboxes of brands: {% for brand in brands.all %} <div class="card-body" id="tabl"> <label class="custom-control custom-checkbox"> <input type="checkbox" value="{{ brand.brand }}" class="custom-control-input"> <div class="custom-control-label">{{ brand.brand}}</div> </label> </div> {% endfor %} models.py class Product(models.Model): """ Containing the products, each product belong to a category and each product have a feedback system """ category = models.ForeignKey(Category, related_name='products', on_delete=CASCADE) name = models.CharField(max_length=55) brand = models.CharField(max_length=55) price = models.FloatField() featured = models.BooleanField(default=False) image = ResizedImageField(size=[460,460], quality=100, upload_to='products', default='None', blank=True, null=True) slug = models.SlugField(max_length=400, unique=True, blank=True) description = models.TextField(default='product', blank=True) def __str__(self): return self.name views.py def products(request, slug): """ List all products of a category """ category = get_object_or_404(Category, slug=slug) products = Product.objects.filter(category=category) brands = Product.objects.filter(category=category).distinct('brand') context = { 'products': products, 'category': category, 'brands': brands, 'title': Product, } return render(request, 'products/products.html', context) Then further down on the page I will query the products, but then how to do it, based on what checkbox is pressed, is lost on me. … -
How do I authenticate a Lambda function to access a Django endpoint?
Note: This question appears to be identical, but actual problem asked is unanswered and the OP ends up changing his entire approach. Suppose I have some lambda-based application that I want to let access my Django application. How do I authenticate it? I could just give the lambda function a username/password, but that's far from ideal in a long term security context. Is there a way to directly authenticate a lambda function in django? Alternatively, are there better security practices that could be employed (i.e. secret rotation) so that this can be done? -
Django : How can we display the filenames of multiple selected files before uploading them
I did an app to upload files to a blob storage and to display their names in a table, once they are uploaded. However, I would like to change the part where they select the files. I would like that the filenames of the files, that the user has selected, are shown in the template before that it click on the button update. Like that the user could verify that it is these files that he wants to upload. The best would be that the user could unselect few files if he did a mistake. Is it possible to do that on Django ? Is it a part in Javascript ? Anyone could show me what I should change or add ? Thank you Here is my Form.py class FilesForm(forms.ModelForm): class Meta: model = UploadFiles fields = ['Filename'] widgets = {'Filename': ClearableFileInput(attrs={'multiple': True}),} The models.py class UploadFiles(models.Model): Id = models.IntegerField(db_column='ID') # Field name made lowercase. Filename = models.CharField(db_column='FileName', max_length=255, blank=True, null=True) # Field name made lowercase. PreviousFilename = models.CharField(db_column='FileNameBeforeIndex', max_length=255, blank=True, null=True) # Field name made lowercase. User = models.CharField(db_column='User', max_length=255, blank=True, null=True) # Field name made lowercase. SizeFile = models.IntegerField(db_column='Sizefile') Uploaded_at = models.DateTimeField(db_column='Timestamp', auto_now_add=True) # Field name made lowercase. … -
Django Many To Many Field Query Admin Page
I have a field in my student model called counselors. All I am trying to do is list the users that are in the group counselors to be displayed in this many to many relationship. How do i go about doing this? Here is the field in my model. Thanks counselor = models.ForeignKey(User, related_name='Counselors', on_delete = models.PROTECT,null=True,blank = True) The current setup only shows all the users within the User table not Users associated in the Counselors group. -
Django rest framework POST request followed by GET request
I am using django rest framework and I want after a POST request in a URL to follow a GET request to another URL with processing some data coming from the POST request. I attach my views.py: from rest_framework.response import Response from rest_framework.decorators import api_view from importer import event_import_data from utils import optimization_solution @api_view(['POST']) def event(request): event_data_post = request.data return Response(event_data_post) @api_view(['GET']) def optimization(request): response_dict = {} event_data = event_import_data(event_data_post) response_dict = optimization_solution(event_data) return Response(response_dict) So, initially I POST a json file in a URL and then I expect by using the dictionary provided by the POST request to use it in the GET request in another URL. However, I am getting the following error: NameError: name 'event_data_post' is not defined Any idea of what is causing the error and how can I bypass it? -
how do I get all the product list that's been ordered in template
how do I filter all the objects associated with "orderitem" for a specific user, so when someone orders a couple of products I want to show the ordered products in the template, right now I'm getting "The QuerySet value for an exact lookup must be limited to one result using slicing". would really appreciate your help, thx! models.py class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) class Product(models.Model): name = models.CharField(max_length=150) description = models.TextField() views.py def orders(request): if request.user.is_authenticated: customer = request.user.customer orders = Order.objects.filter(customer=customer) orderitems = OrderItem.objects.filter(order=orders) else: print('error') context = {"orderitems": orderitems} return render(request, 'accounts/orders.html', context) HTML {% for orderitem in orderitems %} <div class="ordered-view"> <div class="order">{{ orderitem.product.name }}</div> <div class="date">dummydata</div> <div class="status">dummydata</div> <div class="total">dummydata</div> </div> {% endfor %} -
How to roundup and round down the decimal part in python
how to round down and round up the decimal vlaues in pytho. user input a =2.336 After round up it should be like a =2.34 a =4.13623 After round up it should be like a =4.14 Is there any built in functions in python to manipulate -
Why does Django ExtractWeekDay assign the same day to consecutive dates?
I have a model CustomerPurchase which records metadata about a purchase made. I am trying to filter complaints that these purchases are attached to via a foreign key and related name tickets then group by weekday to find which days of the week have the most complaints. I am running into an issue where I am having consecutive days listed as two different weekdays when using Django's ExtractWeekDay. Why does this happen? sample of my code: from django.db.models.base import model from django.db.models.functions import ExtractWeekDay, Trunc interval_type = 'days' class CustomerPurchase(model): business = ForeignKey('data.Business', on_delete=CASCADE) VISIT_TIME_CHOICES = ( ('L', 'Lunch'), ('M', 'Mid-day'), ('D', 'Dinner'), ('N', 'Late Night'), ('U', 'Unrecorded') ) visit_time = CharField(max_length=1, choices=VISIT_TIME_CHOICES, default='U') CustomerPurchase.objects.filter(business__company=1080, tickets__conversation__ci_priority__isnull=False ).exclude(visit_time='U').annotate( day=ExtractWeekDay('tickets__created_at') ).values('day').annotate( date_value=Trunc('tickets__created_at', kind=interval_type, output_field=DateField()) ) the output of the above query: <QuerySet [{'day': 1, 'date_value': datetime.date(2021, 5, 30), 'count': 99}, {'day': 1, 'date_value': datetime.date(2021, 5, 31), 'count': 102}, {'day': 1, 'date_value': datetime.date(2021, 6, 6), 'count': 92}, {'day': 1, 'date_value': datetime.date(2021, 6, 7), 'count': 126}, {'day': 1, 'date_value': datetime.date(2021, 6, 13), 'count': 104}, {'day': 1, 'date_value': datetime.date(2021, 6, 14), 'count': 130}, {'day': 1, 'date_value': datetime.date(2021, 6, 20), 'count': 64}, {'day': 1, 'date_value': datetime.date(2021, 6, 21), 'count': 51}, {'day': 1, 'date_value': datetime.date(2021, 6, 27), … -
How are resources allocated to Django processes/thread?
If I am hosting a website on a cloud server that I provisioned with a fixed amount of resources (CPU, RAM etc). If there are 3 clients accessing the webpage, how is the website served? Is one thread/process/Djandgo instance spawned to serve a client? Or can one single thread serve multiple client requests? How do I figure out how much resources I need for my server, or if I even need multiple servers? And how does this extend to application hosting in general? -
implementation of link decorator in RichTextField (CKEditor) to Django admin panel
I am using CKeditor in my Django app and I'd like to ask if there is any way to implement link decorator to my body field (RichTextField). What I want is a feature that will detect tags (I am using django-taggit to handle tags) in the text and will create a hyperlink that will redirect to the tag page. For example. I put python is amazing in my RichTextField where python is a tag so it will be automatically hyperlinked to http://127.0.0.1:8000/tag/python after I save the article. Right now, I need to do it manually by clicking cltr+K and inserting a link but I am wondering if this can be automated by any chance? -
Django format a request in a list
I need help to format a response of a django request, This is a exemple : With a model like this: Book(models): name = string author = string release = date A request : Book.objects.filter(author='Hergé').value('name') I got : [{'name':'Tintin au Tibet'}, {'name':'Tintin au Congo'}, {'name':'Tintin chez les Picarros'}] I want this : ['Tintin au Tibet','Tintin au Congo','Tintin chez les Picarros'] My question: How to I get what I want by changing only the request ?