Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Which is the simplest way to define a dropdown box in Django?
I have a simple table, with 2 fields, code and description, and I need to generate a dropdown box on the table's values in Django. I want to display the description, but the selection to be done on the code value instead. Is it possible to do this in a simple way? The "to_field_name" doesn't seem to help me too much. class ChoiceTest (forms.Form): field_cd1 = forms.ModelChoiceField(queryset=ViewChoiceTest.objects.values_list(“code", flat=True), to_field_name=description, label="Choice ", required=False) Thank you very much! -
How to pass vairable name in python?
My Model is like: class member(models.Model): name = models.CharField(max_length=100,blank=True,null=True) I have a dictionary: form_values = { 'tableName':'member', 'queryCol':queryCol, 'queryValue':'5A1001', 'updateCol':'address', 'newValue':'Asia' } A function to update the model: def updater(**kwargs): kwargs['tableName'].objects.filter(kwargs['queryCol'] = kwargs['queryValue']).update(kwargs['updateCol'] = kwargs['newValue']) I assume you guessed what the problem is. 'member', 'member_id', 'address' those are passed as strings. But I need to pass them as variable names (member, member_id, address) to achieve my goal(update my database) How can I just pass variable names as variable name? Not as string? -
Django Quryset order_by is returning tuple instead of list
We have upgraded from django 1.8 to django 2.2 Previously when we do cust = Customer.objects.filter(id=2).order_by('id') cust.workorder.order_by is returning list in django 1.8 but it is returning list in django 2.2. Did django changed that? What is the replacement to make that again as the list. Note:- I can't explicitly convert it to list(cust.workorder.order_by) in every query -
Django3, boto3: How to upload media file to s3 and locally?
I've setup boto3 to upload media file to s3 successfully However, Is there a way to upload the file to locally and then s3? The media storage class is my_app/storage_backends.py class PublicMediaStorage(S3Boto3Storage): location = 'media' default_acl = 'public-read' file_overwrite = False and the my_app/settings.py PUBLIC_MEDIA_LOCATION = 'media' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/' DEFAULT_FILE_STORAGE = 'my_app.storage_backends.PublicMediaStorage' -
How to return csv from JSONResponseMixin
I wrote an Abstract Methodto return JSON response from REST APIs a few weeks back, Now I've come across a use case that returns a CSV file and tried to wrote one more method in that mixin to handle CSV response, but it doesn't seem to be working. tried debugging the code and found out that HttpResponse some issue and my API returning the Attribute Error exception. import io import csv from typing import Optional, Dict, List from django.http import JsonResponse, HttpResponse # catch customer exception from api.lib.exceptions import RequestFailureException class JSONResponseMixin: """ A mixin that can be used to render a JSON response. """ def __init__(self): super(JSONResponseMixin, self).__init__() def dispatch(self, request, *args, **kwargs): try: return super(JSONResponseMixin, self).dispatch(request, *args, **kwargs) except RequestFailureException as err: return self.render_to_json_response(data={'error': err.error_msg}, status=400) except Exception as err: return self.render_to_json_response(data={'error': str(type(err))}, status=500) def render_to_json_response(self, data: Optional[Dict] = None, status=200, **response_kwargs): """ Returns a JSON response, transforming 'data' to make the payload. """ return JsonResponse(data, status=status, **response_kwargs) def toCSVFileResponse(self, file_name, data, status=200): """ Return Response for csv File response Args: filename (str) data: [list of list] => [[1,2,3],[4,5,6]] """ buffer = io.StringIO() csv_writer = csv.writer(buffer, quoting=csv.QUOTE_ALL) csv_writer.writerows(data) buffer.seek(0) response = HttpResponse(buffer, content_type='text/csv', status=self.status_code) content_disposition = 'attachment; filename="{0}"'.format(file_name) … -
Email template variable, image src attribute issue with gmail (in Django)
I am having this problem and I have seen similar questions but I can't find an exact solution to this. I have an ecommerce site (written in Django) and I am sending out the order confirmation email, with the product image. The product image changes according to the product that is bought by the customer, and all images are hosted on aws s3 and are public. I am testing the app and it works in mac email app, while in the browser, when I check my gmail account the product image is not being displayed. All other images (hosted as well on aws s3, same bucket) are shown with no problems in the email. The issue is generated by some sort of gmail handling, because I fill in the src attribute in the email template programmatically ({{ product.get_image_url}}), but gmail adds some extra characters, so that the final part of the src link looks like this: /%0D%09%09%096-bottle-img.png instead of /6-bottle-img.png The rest of the long like (the first part) is correct. So, can anyone tell me what gmail is doing here? In my mac email app all looks good! There is no mistreating of the link. I guess this has … -
ReCapcha veryfication in django
I have a problem, because I added reCapcha field to my registration site, following this instruction: https://github.com/ImaginaryLandscape/django-nocaptcha-recaptcha but on google admin site I have information: We detected that your site isn't verifying reCAPTCHA solutions. This is required for the proper use of reCAPTCHA on your site. Please see our developer site for more information. Should I add something more? Doesn't django-nocaptcha-recaptcha do whole job for me? I feel confused, becouse from readme it seeded so. -
Django sign up multiple users by one form
I want to sign up multiple user by enter some word at first, e.g name to start with"test_user" and the number of users "3", and it will create user "test_user1", "test_user2", "test_user3" and this is my code view.py class CustomSignupView(SuccessMessageMixin, FormView): form_class = UserCreateForm success_url ="profile/" template_name = "account/signup.html" def form_valid(self, form): usernames = [] username = form.cleaned_data['username'] stuNumber = form.cleaned_data['stuNumber'] if int(stuNumber) != 1: for i in range(0, int(stuNumber)): usernames.append(username + str(i + 1)) form.instance.username = usernames[i] form.save() else: form.save() return redirect(self.success_url) forms.py class UserCreateForm(forms.ModelForm): username = forms.CharField(max_length=30, label='Username') password = forms.CharField(label='Password') stuNumber = forms.CharField(label='StuNumber') class Meta: model = user fields = ['username', 'stuNumber'] def generate_password(self): password = Account.objects.make_random_password(length=10) return password def save(self, commit=True): user = super(UserCreateForm, self).save(commit=False) user.set_password(self.cleaned_data['password']) if commit: user.save() return user The problem is when I want to create 3 users, and type number 3, it only create 1 form for user3, no user1 and user2. I can't fix it, help, thanks!! -
Django Ckeditor 5 toolbar not visible?
I am trying to add Ckeditor 5 in my Django project. When I run my project on local server I can see the CKeditor 5 toolbar. But when I run my application in the amazon EC2 server, the toolbar is not visible. Can anyone tell what could be the possible reason? -
Tag inside tag Django template
First of all, let me show our views.py file. context = { 'id' : id, 'durum' : durum, 'range': range(len(id)), } I have such data in template; context.id = [12, 10, 10] context.durum = ['UPL','PPL','FIUPL'] I want to match this data like this; 12 UPL 10 PPL 10 FIUPL I created a for loop for this, but need to edit {% for i in context.range %} {{ context.id }} {{ context.durum }} {% endfor %} Like this; {% for i in context.range %} {{ context.id.i }} {{ context.durum.i }} {% endfor %} But I can't use the variable i in the loop. -
Django - eliminate auth and contenttypes from istalled apps
I want to create my user authentication application for my django project. I don't want to use django.contrib.auth and django.contrib.contenttypes which are enabled by default. But when I eliminate them from INSTALLED_APPS, when I run server, I get error like: RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. RuntimeError: Model class django.contrib.auth.models.Permission doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Please help me figure out how to deal with this problem correctly? -
In admin sort by calculated boolean field
Django 3.0.8 class Post(models.Model): tags = TaggableManager() # django-taggit def is_featured(self): tags_aux_list = strip_and_split(self.tags_aux) return SPECIAL_TAGS.FEATURED.value in tags_aux_list is_featured.boolean = True is_featured.short_description = 'Featured?' is_featured.admin_order_field = 'is_featured' # Not working. Django-taggit is used here. In the admin site I'd like to sort by "Featured?". Could you help me organize it? -
How to implement multiple image upload for an instance of a model in Django admin
Hi there i am building an ecommerce site and would like to have my items to have alternative images but for this to happen i need to implement upload of multiple image files for each item in admin, How can i go about this? my current model just has the normal ImageField implementation class Product(models.Model): name = models.CharField(max_length=120) price = models.FloatField() image = models.ImageField(upload_to='pdt_imgs/') sku = models.IntegerField() category = models.ForeignKey(Category, on_delete=models.CASCADE) seller = models.ForeignKey(Seller, on_delete=models.CASCADE) def __str__(self): return self.name -
how to assign a search result with __iexact to a foreignkey value django
i need to assign a search result with __iexact to a foreign key value class ListInfo(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) name= models.ForeignKey(NameList,on_delete=models.CASCADE,blank=True) #others class NameList(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) name = models.CharField(max_length=60) #others i want to create object from List , with default name which assigned to the search name result! and this is my views.py def addNewNameInfo(request): qs = NameList.objects.values_list('name',flat=True) name = request.GET.get('name') name_info = NameList.objects.filter(name__iexact=name) add_new_name_info =ListInfoForm() if request.method == 'POST': add_new_name_info = ListInfoForm(request.POST) if add_new_name_info .is_valid(): obj = add_new_name_info .save(commit=False) obj.admin = request.user obj.name= name_info.name # i also tried this : obj.name= request.GET.get('name') obj.save() messages.success(request,'created') return render(request,'myfolder/my_template.html',{'names':qs,'name_info':name_info,'add_new_name_info':add_new_name_info }) and this is my template <form method='GET'> <select name="name" class="form-control" id="type"> <option selected="true" disabled="disabled">names</option> {% for value in names %} <option value="{{value}}">{{ value }}</option> {% endfor %} </select> <button type="submit">search</button> </form> <!--then --> {% if name_info%} {% for i in name_info%} <!--return some information about the selected name --> {% endfor %} {% endif %} {% if name_info%} <form method="POST">{% csrf_token %} {{add_new_name_info.errors}} <ul> {{add_new_name_info.as_p}} </ul> <button type="submit">save</button> </form> {% endif %} but it raise th 'QuerySet' object has no attribute 'name' while i have the name in my NameList? can we do something like that to assign a value from … -
I'm getting a syntax error for some reason when i want to add a path to my django application
from django.urls import path from . import views urlpatterns = [ ``path("", views.index, name="index") path("newpage/", views.new_page, name="newpage") ] -
Django,Error counting total number of ManyToMany related field
The model mention below, class Myclass(models.Model): name = models.CharField(max_length=200) bad=models.ManyToManyField(User,blank=True,related_name='bad') avarage=models.ManyToManyField(User,blank=True,related_name='avarage') I tried counting users who marked bad in the first object of Myclass Myclass.objects.filter(id=1).bad_set.all().count() but got error AttributeError: 'QuerySet' object has no attribute 'bad_set' Any idea what went wrong here ? -
How to autofill form box value filling other one?
I have created a form in django using this class model: #models.py class Example(models.Model): var_a=models.DecimalField() var_b=models.DecimalField() var_c=models.DecimalField() Suppose that I have created a form using this variable: #template.html <form id="example" method="post"> <div class="form-group col-2 0 mb-0" > {{form.var_a|as_crispy_field}} </div> <div class="form-group col-2 0 mb-0" > {{form.var_b|as_crispy_field}} </div> <div class="form-group col-2 0 mb-0" > {{form.var_c|as_crispy_field}} </div> Now I want to create a jQuery code that give me the possibility to autofill var_c when I insert value in the form box of var_a and var_b. In particular I want to figure out the following equation: var_c=var_a*var_b Is it possibile to get it? -
How to filter data in pandas from a list?
I have a list like l = [[Alex,Jan,Fri],[John,Feb,Mon],[Alex,Jan,Fri],[Alex,Feb,Mon],[John,Jan,Mon]] i want to filter out the list for a particular month say "Jan" and the list should look like this l=[[Alex,2],[John,1]] where 2 and 1 are their number of appearances in the list with a particular month -
User Click On Image Than User Go To That Image Category How To?
how to make when user click on image than user will redirected to that image category and show all the images of that category List item i will create every thing but i am stuck on when user click on image it not redirected to that category? i will create models of category class and post class. List item -
My Django Login/Signup forms save everything except the amount
I am making a bank website in which users can make accounts, withdrawal, deposit and see transaction history. I have been working on them for two weeks. The Login and Signup works and it saves the email, username and password but when I input the amount the request works and I get redirected without any errors but the amount(balance) doesn't get saved. I then tried hardcoding the amount and then change it later when a person withdraws or deposits. Still, the same results when I try displaying the current balance on the dashboard it stays blank. I have pasted the code down and I am using Django 3.0 + Views.py from django.shortcuts import render, redirect from django.contrib.auth import logout, authenticate, login from accounts.forms import SignUpForm from django.contrib.auth.forms import AuthenticationForm, User from django.contrib.auth.decorators import login_required from django.contrib import messages # Welcome, Login, Signup def welcome(request): return render(request, 'accounts/welcome.html') def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') user.amount = 500 user.save() u = authenticate(username=username, password=password) return redirect('login-page') else: messages.error(request, 'Invalid input or missing fields. Please try again!') return redirect('signup-page') else: form = SignUpForm() return render(request, 'accounts/signup.html', {'form': form}) def login_view(request): … -
which one is best django or flask for backend development
Which one is best for backend development Django or Flask what is the reason for choosing one of them -
SQL query in Django ORM
So i have my query that i made in SQL. What i'm trying to do now is to do the same query but in my viewset on Django. I'm having troubles with the filtering and the inner joins that I have to make. This is the query in SQL: SELECT CONCAT(a.column ,'-',a.row) as 'Seat', COUNT(CONCAT(a.id) as 'Reservations', s.name as 'Room', su.name as 'Office' FROM movie_reservation_seats as ra INNER JOIN movie_seat as a on a.id = ra.id_seats_id INNER JOIN movie_room as s on s.id = a.id_sala_id INNER JOIN movie_office as su on su.id = s.id_office_id GROUP BY Seat ORDER BY 'Reservations' DESC LIMIT 5; I don't know too much about filtering, so that's why I'm having troubles using this SQL query in my Django project Thanks in advanced. -
Unable to save information from parent model to inlines in django admin
Use case: We have an Orders Model and an OrderItems model. While adding Orders, we use an OrderItem model as inline. The idea now is to be able to save customer details and addresses etc from Orders to OrderItems while saving the form. I just started with Django about 2 days back, I searched and found that there are different options like save_model, save_related, save_formset, post_save signals etc, that can be overridden on Model, ModelAdmin or InlineModelAdmin Can you please help me with a simple approach that I should follow or a quick tutorial I can refer to. I have been searching only with this issue for almost a day and am unable to wrap my head around this. Thanks for your help -
Removed model instances and error "NoReversematch"
I am encountering the error message similar to this post here. However, I received this message only after I have done the following steps to my django model instances, particularly in the admin. I have a model, called "Product". In admin, I create a few instances of this Product, each with an "id" field. So, I have 5 products, each with "id" "1", "2", "3", "4" and "5". I have an html template that displays the list of all "products", with a url link to each product given by this: class Product(models.Model) ... def get_absolute_url(self): return reverse('catalog:product_detail', args=[self.id, self.slug]) Here is that part of the template: <a href="{{ product.get_absolute_url }}"> </a> I also created a context processor to keep track of the products created in all templates in this website in a context_processors.py. Now, when I delete the first few products in admin (product "1", "2", "3"), and at the same time, create new products in admin (add "6", "7", "8" and "9"), when I re-render the template, I got this "NoReverseMatch" error. I am guessing that since the products get removed in admin, but the context process still keeps a record of that products, the template could not find … -
django datefield migrations giving an error
This is my model I'm trying to add a date field , but when I run migrations I'm getting this error " in parse_date match = date_re.match(value)". I have tried deleting my migrations but I'm still getting this error models.py class Order(models.Model): date = models.ForeignKey('date', null=True, on_delete=models.CASCADE) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) quote_choices = ( ('Movie', 'Movie'), ('Inspiration', 'Inspiration'), ('Language', 'Language'), ) quote = models.CharField(max_length =100, choices = quote_choices) box_choices = (('Colors', 'Colors'), ('Crossover', 'Crossover'), ) box = models.CharField(max_length = 100, choices = box_choices) pill_choice = models.CharField(max_length=30) shipping_tracking = models.CharField(max_length=30) memo = models.CharField(max_length=100) status_choices = (('Received', 'Received'), ('Scheduled', 'Scheduled'), ('Processing/Manufacturing', 'Processing/Manufacturing'), ('In Progress','In Progress'), ) status = models.CharField(max_length = 100, choices = status_choices, default="In Progress") manu_date = models.DateField(("Date"), default=datetime.date.today) forms.py class OrderForm(forms.ModelForm): def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) super(OrderForm, self).__init__(*args, **kwargs) if not user.is_superuser: self.fields.pop('status') class Meta: model = Order fields = '__all__' widgets = {'manu_date': DateInput()} exclude = ['user','date']