Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how do I style and align errorlist from django forms?
This form errorfield comes with ul and li elements and I can't find a way to change it. So is it possible to have "email is taken" as error instead of having the whole ul element "email" before that, if that's not possible then can we at least align it inline together the ul and li. Thx in advance. css .errorlist li { list-style-type: none; display: inline-block; } .account-errors { font-family: "Circular Std Book"; color: black; } html {% if form.errors %} <div class="account-errors"> <div class="container-error"> {{ form.errors }} </div> </div> {% endif %} -
Changing column names of a database table created using django
Actually, I've created a model class in which I have a few attributes(column names). Is it possible for me to change the names of the column using class Meta? I'm just curious. I do know that we could just directly change the attributes themselves. I'm just exploring Meta Class. I'm new to Django and the whole framework thing. So a basic detailed answer would be of real help. You can correct me if I misunderstood the purpose of Meta Class. Thanks in advance :) -
Django_custom_filter for orders and servicess
i want to make a filter on orders model which filters orders based on services provided by a launderette in the order Here are my models: class Launderette(models.Model): launderer = models.ForeignKey(Launderer, null=True, on_delete= models.SET_NULL) name = models.CharField(max_length=200, null=True) available_time = models.CharField(max_length=500, null=True, blank=True) cover_photo = models.ImageField( default="0_GettyImages-1068728612.jpg") location = models.CharField(max_length=200, null=True) isBlocked = models.BooleanField(default=False) date_joined =models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.name) class Services(models.Model): launderette = models.ForeignKey(Launderette, null=True, on_delete= models.SET_NULL) title = models.CharField(max_length=200, null=True) price = models.FloatField(default=0) def __str__(self): return str(self.title) class StatusChoice1(models.TextChoices): PENDING = 'pending', 'Pending' FINISHED = 'finished', 'Finished' ONGOING = 'ongoing', 'Ongoing' DECLINED = 'declined', 'Declined' Canceled = 'canceled', 'Canceled' class Order(models.Model): client = models.ForeignKey(Client, null=True, on_delete= models.SET_NULL) launderette = models.ForeignKey(Launderette, null=True, on_delete= models.SET_NULL) description = models.TextField(blank=True, null=True) price = models.FloatField(default=0) amount = models.FloatField(default=0) services = models.ManyToManyField(Services) status =models.CharField(max_length=50, blank=True, null=True, choices=StatusChoice1.choices,default=StatusChoice1.PENDING) date_started = models.DateTimeField(null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) date_end = models.DateTimeField(null=True, blank=True) def __str__(self): return str(self.client.user.username) Here is my current filter: class OrderFilter2(django_filters.FilterSet): start_date = DateFilter(field_name="date_started", lookup_expr='gte') end_date = DateFilter(field_name="date_end", lookup_expr='lte') start_price = NumberFilter(field_name="price", lookup_expr='gte') end_price = NumberFilter(field_name="price", lookup_expr='lte') start_amount = NumberFilter(field_name="amount", lookup_expr='gte') end_amount = NumberFilter(field_name="amount", lookup_expr='lte') client_name = CharFilter(field_name='client__name', lookup_expr='icontains') status = ChoiceFilter(choices=FILTER_CHOICES, ) class Meta: model = Order exclude = '__all__' fields = ['start_date', 'end_date', … -
Nested serializers and data representation
Working on a django project I am a bit stuck on data representation through APIs. In fact when designing models the data model is quite stratighforward : I have a one to many relationship A--> B therefore I have added a FK to object B. Object B has a boolean attribute "active". I would like to make an API call to list all A objects having at least one assoicated object B with active = true. The api could be like this : /api/objectA/?investment.active=True Thanks for your help. -
django write signal handler as class (write class based django signal handlers)
From django docs it is clear that we can write signals handlers as function. from django.db.models.signals import pre_save from django.dispatch import receiver from myapp.models import MyModel @receiver(pre_save, sender=MyModel) def my_handler(sender, **kwargs): ... Is it possible to write the signal handlers as classes? If yes HOW? -
Cannot render data from REST API's GET (managed in Django) response in React
I am having the issue of data not being rendered from API response in React even though I do receive it. I have the following "Admin-Notification" component: import React from "react"; import './Admin-notifications.css'; import axios from 'axios'; class AdminNotifications extends React.Component { constructor(){ super(); this.state = { events:[ { "id": 1, "name": "Fotosinteza plantelor", "start_date": 1637496120, "end_date": 4098071460, "location": "Cluj-Napoca", "description": "Aduceti planta", "status": "pending", "id_organizer": 2, "id_type": 1 }, { "id": 2, "name": "Cantecul greierilor de peste imas", "start_date": 1637669280, "end_date": 4098071460, "location": "Imas", "description": "In padurea cu alune aveau casa 2 pitici", "status": "pending", "id_organizer": 2, "id_type": 1 }, { "id": 4, "name": "test", "start_date": 1637518260, "end_date": 4098071460, "location": "test", "description": "test", "status": "pending", "id_organizer": 2, "id_type": 1 } ] } this.state2={ events:[], } } getEvents(){ axios .get("http://127.0.0.1:8000/api/getevents") .then(response =>{ this.state2.events = response.data; }) .catch(err => console.log(err)); }; render(){ this.getEvents(); console.log(this.state); console.log(this.state2); const {events} = this.state2; return( <main className="mw6 center main"> { events.map((event)=>{ return( <article key={event.id} className="dt w-100 hight padd bb pb2 component" href="#0"> <div className="col-md-3"> <div className="dtc w2 w3-ns v-mid"> {/* <img src={event.img} alt="event image from organizator" className="ba b--black-10 db br-100 w2 w3-ns h2 h3-ns"/> */} </div> <div className="dtc v-mid pl3"> <h1 className="f6 f5-ns fw6 lh-title black … -
Display only one value of column value in django templates
I'm using post_list for my website. I added a column "type in my model" But i can only load it in a loop "for" and it finaly display multiple "type" in my template. But I want to display it just one time in the top of my web page: Here is example with 2 posts with same "type" : bad If i have only one post in this "type" it's good : good model.py class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) postpic = models.TextField(max_length=140, default='SOME STRING') type = models.TextField(max_length=140, default='blog') class Meta: ordering = ['-created_on'] def __str__(self): return self.title I used "queryset" with filter to created different view depending of the type of post: views.py: class ProgList(generic.ListView): queryset = Post.objects.filter(status=1, type="programmation").order_by('-created_on') class WebList(generic.ListView): queryset = Post.objects.filter(status=1, type="web").order_by('-created_on') class OsintList(generic.ListView): queryset = Post.objects.filter(status=1, type="osint").order_by('-created_on') class ForensicList(generic.ListView): queryset = Post.objects.filter(status=1, type="forensic").order_by('-created_on') class PostList(generic.ListView): queryset = Post.objects.filter(status=1, type="blog").order_by('-created_on') I think there is a better way to do this but i'm noob in django. And finaly I load the posts in one template called post_list.html : template Thanks for your help ! … -
Print foreign key value in template without doing a query
I have a query that I do in my view to get a bunch of team stat objects... team_stats = NCAABTeamStats.objects.filter( name__name__in=teams_playing).order_by(sort) One of the fields 'name' is a foreign key. I pass team_stats to my template to display the data in a chart via a 'for loop'. {% for team in team_stats %} <tr> <td> {{ team.name }} </td> </tr> {% endfor %} So in my template, for every object in team_stats it is doing a query when it prints {{ team.name }} and it really slows things down, especially when there are 50-100 teams. My question is, is there a way to print 'team.name' without it doing a query every time? -
onchange select works after second time - jquery - django
I'm trying to show some data base on selected data in a drop down field , the form is formset dynamic (modelformset_factory) but it calls back the data two times , and doesnt calls back any data in the first selection , in the second time then return the data ! and in the python function returns nothing as well at the first selection , in the second selection returns the data two times ! here is my views.py code @login_required def return_back_imei_oddinfo(request): query = request.GET for item in query: if item.startswith("imei-") and item.endswith("-item"): item_id = query.get(item) print(item) break selling_price= Imei.objects.get(id=item_id).mobile.selling_price, data = { 'selling_price' : selling_price, 'mobile':mobile, 'giga':giga } return JsonResponse(data) forms.py class ImeiInvoiceForm(forms.ModelForm): item = ImeiModelChoiceField(queryset=Imei.objects.filter(status=True),widget=forms.Select(attrs={'onchange':'imeiInfo(this);'})) class Meta: model = ImeiInvoice fields = ['item','price'] and here is my template function imeiInfo () { $('select').change(function() { let elm = $(this); data = {}; data[elm.attr("name")] = elm.val(); $.ajax({ url:'/ajax/return_back_imei_oddinfo/', data:data, success:function(data){ console.log(data.selling_price) if (data){ elm.closest("div.child_imeiforms_row").find("input.price").val(data.selling_price); } else{ alert('not inserted') } } }) }) } imeiInfo(); {{imei_forms.management_form}} <div id="form-imeilists"> {% for imei in imei_forms %} {{imei.id}} <div class="child_imeiforms_row"> <div class="row no-gutters table-bordered"> <div class="col-md-3"> <div class="form-group"> {{imei.item | add_class:'form-control'}} <div class="text-danger text-center" hidden></div> </div> </div> <div class="col-md-2"> <div class="form-group"> {{imei.price | … -
Django: norm for handling un-created OneToOneFields
Here's an example model: class User(models.Model): ... Later, I want to add an Invite OneToOne model: # This is arbitrarily named. class InviteCode(models.Model): user = models.OneToOneField(User, related_name="invite_code") ... # signals.py @receivers(signals.post_save, sender=User) def create_invite_code(sender, instance, created, **kwargs): if created: invite_code = InviteCode.objects.create(user=user) Now, for new users I can conveniently do user.invite_code for any new users. Is there any standard way to handle this for old users? There seem to be many possible solutions, but none of them seem very clean: I could try: catch RelatedObjectDoesNotExist every single time I use user.invite. This isn't great and seems very unclean. I could create an accessor method, like get_invite_code which does the try/catch, and always fetch the user.invite_code via user.get_invite_code() I could run a migration, such that all old users have an Invite Code created, and all new users have an invite code object via the signal. Anyone have any suggestions on the most pythonic way to handle this? -
How to send Email without using settings.py ? (smtp parameters in database)
I would like to be able to send emails with django but without using the email parameters in settings.py. (EMAIL_HOST, EMAIL_USE_TLS, EMAIL_HOST_PASSWORD, etc ...) These parameters are stored in db because they can be different depending on the user. How to use these parameters in base to send emails and not those in settings.py ? class EmailThread(threading.Thread): """ Class email (Thread) """ def __init__(self, subject, html_content, recipient_list): self.subject = subject self.recipient_list = recipient_list self.html_content = html_content threading.Thread.__init__(self) def run (self): msg = EmailMessage(self.subject, self.html_content, settings.EMAIL_HOST_USER, self.recipient_list) msg.content_subtype = "html" msg.send() def send_html_mail(subject, html_content, recipient_list): """ send an email asynchronous """ EmailThread(subject, html_content, recipient_list).start() I can get the parameters using: email_params = EmailParameter.objects.get(user=request.user) class EmailParameter(models.Model): email_use_tls = models.BooleanField(_("email use tls"), default=True) email_use_ssl = models.BooleanField(_("email use tls"), default=False) email_host = models.URLField(_("email host"), max_length=200) email_host_user = models.CharField(_("email host user"), max_length=200) email_host_password = models.CharField(_("email host password"), max_length=200) email_port = models.PositiveIntegerField(_("email port")) default_from_email = models.EmailField(_("default from email"), max_length=200) signature = models.TextField(_("signature")) user = models.ForeignKey( User, verbose_name = _("user"), related_name = "user_email_parameter", on_delete=models.CASCADE ) -
Django ImageField get username
models.py def upload_to(instance, filename): return 'verify/%s/%s' % (instance.user_idx.username, filename) class UserVerifyImg(models.Model): user_idx = models.ForeignKey( User, db_column='user_idx', on_delete=models.CASCADE ) business_type = models.CharField(max_length=255) image = models.ImageField(upload_to=upload_to) upload_date = models.DateTimeField(auto_now = True) class Meta: managed = False db_table = 'account_user_verify' This is my model. but It is showed me error. account.models.UserVerifyImg.user_idx.RelatedObjectDoesNotExist: UserVerifyImg has no user_idx. I don't now what is the problem. help me please. -
Annotate and aggregate by month Django queryset?
I have a model where I would like sum a specific field by month and would like to do it in a single query. e.g I would feed in a date range and this would filter the queryset. Then I would like to be able to aggregate by month for that queryset. My current implementation produces a total aggregate instead of aggregating by month. Is there a better way to approach this problem? def reading_by_month(queryset): return queryset.annotate(month=TruncMonth('reading_date')).values('month').annotate(total=Sum('reading')) -
Handling forms from class based view
Hello how can I pass form into template from class based view? In HTML everything inherits and I can render elements inside block content but I can not render form. This is my code. : views.py: class Signup(TemplateView): model = Profile template_name = 'home/sign-up.html' form_class = UserCreationForm() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = UserCreationForm HTML: {% extends "home/todo.html" %} {% block content %} <form method="POST"> {{form}} </form> {% endblock content %} -
how can i avoid no reverse match in django
idk why this error occurred no revers match this code is a practice . it 3 part : 1_home 2_shops 3_pizza i modified shops.html code to link pizza but after this modifying this error occrrued Reverse for 'pizza' with arguments '('',)' not found. 1 pattern(s) tried: ['shops/(?P<pizza_id>[0-9]+)$'] first code : <ul> {%for shop in shops%} <li> {{shop}} </li> second code: <ul> {%for shop in shops%} <li> <a href="{% url 'pizzas:pizza' pizza.id %}">{{shop}}</a></li> i paste all codes in pastebin if needed: https://pastebin.com/u/Nicolas_Darksoul/1/KUBPPDTG -
Django: web model form: Question followed by radio-buttoned answers
1.OBJECTIVE. Roll out a web model-based form with questions and their possible radio-button answers. i can't get it formatted with ctrl-k Model: class Question(models.Model): description = models.TextField(max_length=2000) def str(self): return self.description class Answer(models.Model): answer = models.TextField(max_length=2000) fk_question_id = models.ForeignKey(Question, related_name='answers', on_delete=models.CASCADE) def __str__(self): return self.answer VIEW: def formulario(request): form = FormularioForm() return render(request, "formulario.html", {'form': form}) HTML TEMPLATE: {{form}} WHAT I HAVE TRIED: The file below forms.py displays the whole rollout of querysets of questions followed by all of the answers. Naturally we want alternating question answers, question answers... It does not work because it needs to be splitted somehow and dealt separately in the template. FORMS.PY Answer = forms.CharField(label=Question.objects.all(),widget=forms.RadioSelect(choices=RESPUESTAS)) RESPUESTAS is simply a list of tuples. I noticed that this is what choices seems to take as imput so I created such list from Answer.objects.all() and zipping it onto itself SO, QUESTIONS: A) the forms.py needs to have splitted queries for question and answers. The html.template should work with this. The visual I have in my mind is a Django representation of this: SELECT description, answer, fk_question_id_id FROM Answer JOIN Question on answer.fk_question_id = question.id but which has to have the html formatting for radio buttons something like: for … -
I gave a command django-admin but i got error
getting this error I gave command django-admin program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + django-admin + ~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (django-admin:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException``` -
how to get data from html form into a json format
I am building an ecommerce site. so, i created a billing form, and in that form, i want to collect stuffs like email, address etc and pass it into a json format so i'll pass it to the payment gateway. I tried creating it in a variable and passing it, but on the payment gateway redirectedmodal form, it is saying invalid email input Code const publicKey = "{{ key }}"; var email = document.getElementById('email').value; var fullname = document.getElementById('fullName').value; var address1 = document.getElementById('custAdd').value; var address2 = document.getElementById('custAdd2').value; var country = document.getElementById('country').value; var state = document.getElementById('state').value; var address1 = document.getElementById('postCode').value; function payWithRave() { var x = getpaidSetup({ PBFPubKey: "xxxxxx", email: email, amount: '{{cart.get_total_price}}', customer_phone: "234099940409", currency: "USD", address: 'address1', address2: 'address2', country: 'country', state: 'state', postcode: 'postCode', }) <div class="col-sm-7"> <label for="firstName" class="form-label">Full Name</label> <input type="text" class="form-control" id="fullName" placeholder="" required> <div class="invalid-feedback"> Valid first name is required. </div> </div> <div class="col-12"> <label for="email" class="form-label">Email <span class="text-muted">(Optional)</span></label> <input type="email" class="form-control" id="email" placeholder="you@example.com"> <div class="invalid-feedback"> Please enter a valid email address for shipping updates. </div> </div> <div class="col-12"> <label for="address" class="form-label">Address</label> <input type="text" class="form-control" id="custAdd" placeholder="1234 Main St" required> <div class="invalid-feedback"> Please enter your shipping address. </div> </div> <div class="col-12"> <label for="address2" class="form-label">Address 2 … -
How to saving multiple forms also has cloned forms in django?
views.py @login_required def add_product(request): productform = ProductForm() variantsform = VariantsForm() productvariantsform = ProductVariantsForm() if request.method == 'POST': productform = ProductForm(request.POST, request.FILES) variantsform = VariantsForm(request.POST, request.FILES) productvariantsform = ProductVariantsForm(request.POST, request.FILES) if productform.is_valid(): product = productform.save(commit=False) vendor = CustomUser.objects.filter(id=request.user.id) print(vendor) product.vendor = vendor[0] product.slug = slugify(product.product_name) product.save() if variantsform.is_valid(): variantsform.save() #finally save if productvariantsform.is_valid(): productvariantsform.save() #finally save return redirect('vendor:vendor-admin') else: return HttpResponse("Nothing submitted...") else: productform = ProductForm variantsform = VariantsForm() productvariantsform = ProductVariantsForm() return render(request, 'vendor/add_product.html', {'productform': productform, 'variantsform':variantsform, 'productvariantsform': productvariantsform}) add_product.html <div class="container mt-5" id="p"> <h1 class="title">Add Product</h1> <div class="card" style="width: 38rem;"> <form method="POST" action="{% url 'vendor:add-product' %}" enctype="multipart/form-data"> {% csrf_token %} <div class="row"> <div class="col-lg-12 col-md-12"> {{ productform.vendorid|as_crispy_field }} </div> <div class="col-lg-12 col-md-12"> <a id="vendor_id_search" class="btn btn-info mt-4">search</a> </div> </div> <div id="show_vendorname"> </div><br> {{ productform.maincategory|as_crispy_field }} {{ productform.productcategory|as_crispy_field }} {{ productform.subcategory|as_crispy_field }} {{ productform.product_name|as_crispy_field }} {{ productform.brand_name |as_crispy_field }} <br> <div> <p></p> </div> <hr> <div id="order-details-booking"> <div class="row"> <div class="form-holder"> <div class="col"> <h1>Variant Form</h1> {{ variantsform.variant_type|as_crispy_field}} {{ variantsform.variant_value|as_crispy_field}} {{ productvariantsform.price|as_crispy_field}} {{ productvariantsform.initial_stock|as_crispy_field}} {{ productvariantsform.weight_of_product|as_crispy_field}} <div class="input-group mb-3"> <label class="input-group-text" for="upload_file">Upload Images</label> <input type="file" id="upload_file" onchange="preview_image();" multiple class="form-control"> </div> <div id="image_preview"></div> {% comment %} {{ productvariantsform.images|as_crispy_field}} {% endcomment %} {{ variantsform.sleeve|as_crispy_field }} {{ variantsform.material|as_crispy_field }} {{ variantsform.neck|as_crispy_field }} <div class="col s1"> … -
how to use local host server for domain django
my problem seems to be a funny one...... i'm developing a django ecommerce app. the problem is that when the link for activation of a user account is sent on the console, instead of getting my local server as an domain e.g http://127.0.0.1:8000/account/activate/OQ/awzscp-c1075f82b127ff18fb676523a9a02d71)/ i get http:// example.com /account/activate/OQ/awzscp-c1075f82b127ff18fb676523a9a02d71)/ instead -
Adding settings to settings.py - Django
I'm following this Django Tutorial to add photos to my Django webpage. It says to put the following codes into my settings.py. However, I'm sort of confused because I know the two "span class" lines are definitely not Python codes. Therefore, does anyone know what I should do? Do I just include the two Python codes instead? span class="hljs-comment"> # Base url to serve media files</span> MEDIA_URL = <span class="hljs-string">'/media/'</span> <span class="hljs-comment"> # Path where media is stored</span> MEDIA_ROOT = os.path.join(BASE_DIR, <span class="hljs-string">'media/'</span>) Thanks in advancd! -
Password not hashing while using Django Rest Framework and Custom User Modelh
Problem: I needed a backend for authenticating with phone number and I decided to make it in Django. I am using Django Rest Framework for API and Custom User Model. When I create a user using Django Admin, the password is hashed and I can log in using the login API I created. But when I create a user using API ( created using DRF ) the password is not hashed due to which I am not able to log in. Note: I am using KNOX authentication for token authentication but that is working fine and I do not think that that is the problem Project Structure ( only files that are needed are included ): server\ accounts\ admin.py forms.py models.py serializers.py urls.py views.py server\ settings.py urls.py manage.py Code: # settings.py """ Django settings for server project. Generated by 'django-admin startproject' using Django 3.2.9. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from datetime import timedelta from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: … -
502 occurs when creating environment on elastic beanstalk
I'm having an issue deploying my first Django project. Here's my config.yml: global: application_name: testapp branch: null default_ec2_keyname: aws-eb default_platform: Python 3.8 running on 64bit Amazon Linux 2 default_region: us-west-2 include_git_submodules: true instance_profile: null platform_name: null platform_version: null profile: eb-cli repository: null sc: null workspace_type: Application And here's my django.config: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: djangoproject.wsgi:application I have followed this doc. But after I did eb create testapp-env, I get 502 error: image of the error I will provide further information if you need. Thank you in advance for your help. -
HTML audio tag play button is greyed out on Django project
For some reason the play button is greyed out on my Django website. I used this same exact HTML code in a blank HTML document and it worked as it should, so I don't think there's a problem finding the file, or a syntax error. While running the server locally I am not seeing any errors in the command line either. How it looks on blank HTML file How it looks on website Code: <audio src="C:\Users\zach2\music\download.mp3" controls> </audio> Is there something that I need to change in one of the Django files to enable audio to work properly? I am very new to Django and Web development so please forgive my ignorance. If you want to see another file please let me know and I will update the post ASAP. Thank you. -
Save Temporary Data in Django
Is there any way to save temporary data in django framework? For example I need to save temp notices in a table, with expiration date. To give a better example, I have a table called product and in this table there are several fields such as: title, description, notices and others... is it possible to create a product with a temporary notice? like, this product has this notice until tomorrow.