Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
A Django query to find top 3 posts with maximum comments
here are my models BlogPost Comments post = models.ForeignKey('BlogPost', null=False, on_delete=models.CASCADE) -
Jquery ajax call not working in django application for dependent drop down
I am trying to fetch localities based on the city in my django application using jquery ajax call but this does not seem to be working. What is actually going wrong here? Help html <h1>Dependent Dropdown</h1> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $("#selectcities").change(function () { const city_id = $(this).val(); $.ajax({ url: '/getdetails', data: { 'city_id': city_id }, success: function (data) { console.log(data) $("#selectlocalities").html(data); } }); }); </script> <form action="/submit/" method="POST"> <h4>Select city</h4> <select id="selectcities" name="selectcity"> <option selected>Select City</option> {% for city in cities %} <option val="{{ city.id }}">{{city.name}}</option> {% endfor %} </select> <h4>Select Locality</h4> <select id="selectlocalities" name="selectlocality"> <option selected>Select Locality</option> </select> <input type="submit" class="btn btn-dark btn-lg"> </form> views.py def pageload(request): cities=city.objects.all() context={'cities': cities} return render(request,'index.html',context) def load_localities(request): city_id = request.GET.get('city_id') localities = locality.objects.filter(city_id=city_id).all() context={'localities':localities} return render(request, 'locality_dropdown_list_options.html',context) -
i Have a error in Django ,i deploy my weab app in heroku
[enter image description here][1] Help Me [1]: https://i.stack.imgur.com/fTgYO.jpg -
use serializer in that model properties
can i use serializer in that model properties? I have (most likely due to a circular import) Error for use curcular. ImportError: cannot import name 'Customer' from partially initialized module -
SQL error while making email field required and unique in Django
I'm developing an ReST API using DRF. I'm currently working on authentication module. I am using Djsoer to provide authentication API middle-ware. I am using token based authentication as it provides auto-logout (not provided by JWT). Library Version Python : 3.9 Django : 3.2.3 DRF : 3.12.4 Djsoer : 2.1.0 I'm currently using Postgres 13 for development but system is expected to work on all major SQL DB provider (i.e. Postgres, Oracle, MySQL and MsSQL) in production Windows 10 64-bit is used during development and Ubuntu or CentOS will be used for production deployment. I'm making email field required (null=False, blank=False) and unique. To do this I have extended AbstractUser model class in a custom user model created by me. The extended class hold additional user related information like phone number, etc. I refereed the following stack overflow article : Django: Make user email required User-Profile Model : from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ from phonenumber_field.modelfields import PhoneNumberField # Create your models here. class UserModel(AbstractUser): class Meta : db_table = 'user_profile' email = models.EmailField(_('email address'), null=False, unique=True, blank=False) mobile_number = PhoneNumberField(null=False, blank=True) whats_app_number = PhoneNumberField(null=False, blank=True) User-Profile Serializer: from .models import UserModel … -
/<int:id> doesn't redirect to html in django
So I have a image in html redirect to a certain url: <div class="image"> <a href="/accounts/startlistening/{{i.song_id}}"> <img src="{{i.image.url}}"> </a> </div> Here i.song_id gives a integer value. The url.py is: urlpatterns = [ url('register/', views.registration, name="signup"), url('login/', views.loginUser, name="login"), url('logout/', views.logoutUser, name="logout"), url('upload/', views.upload, name="upload"), url('startlistening/', views.startlistening, name="startlistening"), url('startlistening/<int:id>', views.player, name="player") ] The views.py for my player is: def player(request, id): song = Song.objects.filter(song_id = id).first() return render(request, 'accounts/player.html',{'song':song}) But for some reasons on runserver, on clicking the image, it changes the url but doesn't redirect to player.html Eg: on clicking it changed from http://127.0.0.1:8000/accounts/startlistening/ to http://127.0.0.1:8000/accounts/startlistening/17 but the content is same. -
how to import app rest to my app in projects django
enter image description here from mywebsite.statistical.models import ProfileUser mywebsite it is name projects and statistical.models it's path i want import to app ProfilePhoneBook -Please help me i has sister very beautiful -
Can not send email asynchronously
I have a Django view function to send email asynchronously . I think it should work asynchronously . Means return the response before sending email . But it is working synchronously. But why . Could you please help #helper function async def async_send_email(): send_a_mail = sync_to_async(send_mail) await send_mail( <subject>, <message>, <sender>, [<receiver>], fail_silently=False ) #View function async def emailSenderView(request): if request.method == 'GET': asyncio.create_task(async_send_email()) return JsonResponse({}, status=200) -
Django - inline formset data duplication
I have a create view with an inline formset. I'm trying to allow the user to create & save multiple budgets for the subprogram, it does save the budget for each row that I create but the data is the same for each regardless of what I enter in each field. Why is the data the exact same and not what I enter in each row? Views: class SubprogramCreateView(LoginRequiredMixin, CreateView): model = Subprogram form_class = SubProgramCreationForm login_url = "/login/" success_url = '/' def get_context_data(self, **kwargs): SubprogramBudgetFormSet = inlineformset_factory( Subprogram, SubprogramBudget, fields=('subprogram', 'budgetYear', 'budgetCost'), can_delete=False, extra=1, ) data = super().get_context_data(**kwargs) if self.request.POST: data['budget'] = SubprogramBudgetFormSet(self.request.POST) else: data['budget'] = SubprogramBudgetFormSet() return data def form_valid(self, form): context = self.get_context_data() budget = context["budget"] if budget.is_valid(): self.object = form.save() budget.instance = self.object budget.save() else: return self.form_invalid(form) return super(SubprogramCreateView, self).form_valid(form) Model: class SubprogramBudget(models.Model): subprogram = models.ForeignKey(Subprogram, on_delete=models.CASCADE) budgetYear = models.CharField(verbose_name="Budget Year", choices=BUDGET_YEAR_CHOICES, max_length=200) budgetCost = models.DecimalField(verbose_name="Subprogram Budget", decimal_places=0, max_digits=11) Form: class SubprogramBudgetForm(forms.ModelForm): class Meta: model = SubprogramBudget exclude = () SubprogramBudgetFormSet = inlineformset_factory(Subprogram, SubprogramBudget, form=SubprogramBudgetForm, extra=1) Template: <h2>Budget</h2> <table class="table table-light"> {{ budget.management_form }} {% for form in budget.forms %} {% if forloop.first %} <thead> <tr> {% for field in form.visible_fields %} <th scope="col">{{ field.label|capfirst }}</th> … -
how to make some fields only accessible by some type of Users in Django?
my model.py class User(AbstractUser): is_student = models.BooleanField('student status', default=False) is_creator = models.BooleanField('content creator status', default=False) is_mentor = models.BooleanField('mentor status', default=False) Here I am adding three additional fields like is_creator for superuser, is_mentor for a class mentor and is_student for a student, i want to know how to give a new user their role among from above three during signup, so that it can be checked while giving permissions -
Setting src={{form.image_url}} cannot render image but form.image_url does contain the URL (Django)
I have a list of forms which, among other fields, contain a URLField. I try, very simply, to display those images: {% extends "myapp/base.html" %} {% block extra_head %} {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'myapp/mycss.css' %}"> {% endblock %} {% block content %} {% load crispy_forms_tags %} <div class="form-group"> {% for form in forms %} <img src="{{form.image_url}}" alt="Image of product"/> # Not working {{form.image_url|as_crispy_field}} #shows image-url, thus it's not empty {% endfor %} </div> {% endblock content %} as you can see in the picture below the image is not rendered and it displays some om the HTML-code afterwards (it seems some character escaping is missing?), but it does indeed contain the URL (the url-bar below). If I copy-paste the image-url directly into src it works fine. -
Nested API testing in Django Test Framework
So, Situation is following. ParentModel -PM ChildModel Child 1 (Fk relation with "PM") Child 2 (Fk relation with "PM") .... I had built a custom API to creates all child objects when creating a Parent Object , well that is working fine(tested on POSTMAN). I was writing Test Cases for these API's but i was unable to create child objects using 1 single API that is working fine i have mentioned. I have used following Client Classes for writing test cases:- TestAPIClient APIClient etc . Can i find some standard way to test my application? Or there is any standard way to solve my problem?Please guide me. -
How to make all Hyperlinks in Django REST Framework relative?
Is there any easy way to use relative to Root urls instead of absolute ones? By default DRF returns something like this: { "url": "http://127.0.0.1:34503/items/4/", ... "parent": "http://127.0.0.1:34503/items/1/", "stargazers": "http://127.0.0.1:34503/items/4/stargazers", } I would like it to be: { "url": "/items/4/", ... "parent": "/items/1/", "stargazers": "/items/4/stargazers", } Any ideas? I am using HyperlinkedModelSerializer: class ItemSerializer(serializers.HyperlinkedModelSerializer): stargazers = serializers.HyperlinkedIdentityField(view_name='item-stargazers') class Meta: model = Item fields = ['url', 'id', ..., 'stargazers'] -
Multiple choices are not saving in Dango admin
I am building a BlogApp and I am storing user's multiple interest in a CharField. I have used multiple select field in html. Choices are showing fine BUT when i try to save multiple values at a time then only one is adding. models.py class Profile(models.Model): full_name = models.CharField(max_length=30) interests = models.CharField(max_length=30) template.html <div class="container-fluid"> <div class="row"> {% csrf_token %} <br> <br> <input type="text" name="full_name"> <label for="interests">Choose a car:</label> <select name="interests" id="interests" multiple> <option value="cricket">Cricket</option> <option value="piano">Piano</option> <option value="eating">Eating</option> </select> <div class = "col text-center"> <input type="submit" class="btn btn-primary" value="Save Name" /> </div> </div> <form> </div> When i try to select more than one interest and check admin then it is showing only one interest. Any help would be much Appreciated. Thank You in Advance. -
filter articles for category in Dango
Very good, I am doing a personal blog as the first project in the world of web development, which I am developing with django, but I have a problem, the truth is I cannot find a way to filter my articles by categories, I show you my viewed models. I have seen some examples using foreign keys but that causes me that the articles can only have a single category. I understand that to get the articles by categories I have to do a "fiilter" of categories but I even got there, if someone could guide me I would appreciate it very much class Article(models.Model): title = models.CharField(max_length=150, verbose_name='Titulo') subtitle = models.CharField(max_length=50,default='Máximo 50 carácteres, que no se te olvide' ,verbose_name='subtitulo') content = RichTextField(verbose_name="Contenido") image = models.ImageField(default="null", verbose_name="Imagen", upload_to = "media") user = models.ForeignKey(User, verbose_name="Usuario", on_delete=models.CASCADE, editable=False) categories = models.ManyToManyField(Category, verbose_name="Categorias") create_at = models.DateTimeField(auto_now_add=True, verbose_name="Creado el") update_at = models.DateTimeField(auto_now=True, verbose_name="Editado el") def __str__(self): return self.title class Meta: verbose_name = ('Articulo') verbose_name_plural = ('Articulos') ordering = ['id'] class Category(models.Model): name = models.CharField(max_length=100, verbose_name="Nombre") description = models.CharField(max_length=255, verbose_name="Descripcion") create_at = models.DateTimeField(auto_now_add=True, verbose_name="Creado el") def __str__(self): return self.name class Meta: verbose_name = ('Categoria') verbose_name_plural = ('Categorias') /views: def article(request, article_id): article = get_object_or_404(Article, id=article_id) … -
Parsing data-dict vs. model-instance to Django ModelForm
Is there a difference between doing instance = MyModel() form = MyModelForm(instance=instance) form.save(commit = False) form.instance.foo="foo" form.instance.bar="bar form.save() and data = {"foo":"foo","bar":"bar"} form = MyForm(data=data) form.save() when creating an object? -
Razorpay customize Payment options ( more than one option ) in django
I am using razorpay in a django project. I want customized payment methods ( not only one, but more than one options ). To be more specific, I want something like data-prefill.method = 'netbanking/upi' I want this two netbanking and UPI payment options only. I found something like "options": { "checkout": { "method": { "netbanking": "1", "upi": "1", "card": "0", "wallet": "0" } } } But how to implement this on django template? Thanks in advance, Hasnain -
How can I get a GraphQL query to respond with an array of multiple object types? I'm using Django GraphQL API using Graphene
I have a Django GraphQL API (using Graphene) that I am using to build a chat app. The app allows for either one to one chat or a group chat and in the UI (Angular-based), there is a single search bar. So when a user enters a search query, I would like to show them all of the following in a single list:- Members who's first or last name contain the query Group chats whose name contain the query Individual chat messages that contain the query Here are the models:- class Group(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=250) institution = models.ForeignKey(Institution, on_delete=models.PROTECT) avatar = models.CharField( max_length=250, blank=True, null=True, default="https://i.imgur.com/hNdMk4c.png") searchField = models.CharField(max_length=400, blank=True, null=True) # Type Choices class TypeChoices(models.TextChoices): CLASS = "CL", _('Class') TEAM = "TE", _('Team') COORDINATiON = "CO", _('Coordination') # End of Type Choices group_type = models.CharField( max_length=2, choices=TypeChoices.choices, default=TypeChoices.TEAM) admins = models.ManyToManyField(User, related_name="adminInGroups", through="GroupAdmin", through_fields=( 'group', 'admin'), blank=True) members = models.ManyToManyField( User, related_name="memberInGroups", through='GroupMember', through_fields=('group', 'member'), blank=True) active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class GroupAdmin(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) admin = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.group class GroupMember(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) member = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return … -
HttpResponseRedirect(reverse) and render
I am a rookie in Django and find that I don't quite understand two commands: HttpResponseRedirect(reverse) and render, though I have read official documentation a couple of times. I have two questions: what's the difference between HttpResponseRedirect and render? I usually use HttpResponseRedirect when it returns the result that I expect. Otherwise, I will use render. Though it did work sometimes, I still think that my understanding is probably incorrect. Another question is that why we always need reverse together with HttpResponseRedirect? In what circumstance I should use HttpResponseRedirect without reverse? Thanks in advance for your help. -
Connect django to Google Cloud SQL?
I am trying to migrate my db from sqlite3 to cloud sql but im getting some error DATABASES = { 'default': { # 'ENGINE': 'django.db.backends.sqlite3', 'ENGINE': 'django.db.backends.mysql', 'HOST': 'IP_OF_MY_SQL_INSTANCE', 'PORT': '3306', 'NAME': 'CONNECTION_NAME', 'USER': 'ROOT_USER', 'PASSWORD': 'ROOT_USER_PASSWORD' # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } Are these correct as the tutorial does not have proper way to configure for MySql and Django https://cloud.google.com/python/django/appengine#configuring_the_database_settings I am getting this error django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on 'MY_IP' (10060)") Can anyone help me out? Thanks -
How to make a unique URL for each user in Django?
I am making website with Django. I want each user to have their own URL, so if a user with the username "john" registers, the URL will be .../user/john or if a user with the username "tim" registers, the URL will be .../user/tim. I also want that when I log in as "tim" and enter .../user/john in the search, I will see John's page. This is my urls.py file: from django.contrib import admin from django.urls import path, include from webapp.views import welcome_page, register, user_page, settings, timeline urlpatterns = [ path('admin/', admin.site.urls), path("", welcome_page, name="welcome_page"), path("register/",register, name="register" ), path("", include("django.contrib.auth.urls"), name="login_logout"), path("user/",user_page, name="user_page"), path("settings/", settings, name="settings"), path("main/", timeline, name="main_timeline"), ] And this is my views.py file: from django.contrib.auth.forms import UserCreationForm from django.shortcuts import render, redirect from .forms import RegisterForm from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User def welcome_page(response): return render(response,"welcome.html") def register(response): error = "" if response.method == "POST": form = RegisterForm(response.POST) if form.is_valid(): form.save() return redirect("/login") else: error = form.errors form = RegisterForm() return render(response, "register/register.html", {"form":form, "error" : error}) @login_required def user_page(response): username = str(User.objects.get(username=response.user.username)) userphoto = username[0:2] return render(response, "user_page.html", {"userphoto": userphoto}) @login_required def settings(response): return render(response, "settings.html") @login_required def timeline(response): return render(response, "timeline.html") -
Show quantity based on chosen part name from dropdown
I was following this method to show the part quantity after choosing the part from the dropdown. To make it happen I created two tables Part and Order where Part is FK in the Order table. So whenever, the user chooses the part name in the Order form, then show the part quantity of that selected part. I am trying to solve it by using js, but I need help. The following picture from Order form. So choose the Part Name and then show that quantity into the Part Quan box. models.py class Order(models.Model): part = models.ForeignKey(Part, on_delete=models.CASCADE) qu = models.DecimalField(max_digits=10,decimal_places=2) class Part(models.Model): partname = models.CharField(max_length=50) quan = models.PositiveIntegerField(default= 0) Views.py def create_order(request): from django import forms form = OrderForm() if request.method == 'POST': for form_data in forms_data: forms = OrderForm(request.POST) if forms.is_valid(): product = forms.cleaned_data['product'] part = forms.cleaned_data['part'] qu = forms.cleaned_data['qu'] order = Order.objects.create( product=product, part=part, qu=qu, ) return redirect('order-list') context = { 'form': form } return render(request, 'store/addOrder.html', context) def fetch_quan(request, pk): part = get_object_or_404(Part, pk=pk) print('part',part) if request.method=='GET': response = HttpResponse('') quan = part.quan print('quan',quan) response['quan-pk'] = part.pk response['quan'] = quan return response URL url(r'^quan/(?P<pk>\d+)$', views.fetch_quan, name='fetch_quan'), HTML <form action="#" method="post" id="form-container" novalidate="novalidate"> {% csrf_token %} <div … -
Get non-valid fields from Django Form
Say I have the following view def add_list(request): user = request.user if request.method =="POST": instance = MyModel(user=user) form = MyForm(instance = instance) form.is_valid() #False is there a way to figure out, which fields are "wrong" and why? I tried form.errors which returned {} -
How to update model in Django using kwargs
I am writing update method for my model: class Task(models.Model): @staticmethod def update_task(task_id: int, calendar_path: str, **kwargs): cal = get_object_or_404(Calendar, path=calendar_path) task = get_object_or_404(Task, id=task_id) if task.calendar != cal: raise FieldError("Calendar does not contains this task") for field_name, value in kwargs: task I want all fields from kwargs to be renamed, for example like this: update_task(..., name = "New Name", description = "New description") But I have no idea how to do it, without of using eval, but that is not good idea. -
How do I display a date in a top of chat message with django
I want to do something like what is talking about in this post (How do I display the calendar date on the top of chat messages?) but in Django. Somebody can actually help me??