Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
with the help of django, what are the steps to show data in the website from Apache Solr?
Here I need to show the TEXT and URL in the website from apache solr. what will be the query or ORM? -
Django URL not mapping even there is no error why?
django startproject folder (URLS.PY):- from django.contrib import adminfrom django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('sub.urls')), ] django startapp folder (URLS.PY):- from django.urls import path from . import views urlpatterns = [ path('', views.home, name= 'home'), ] django startapp folder (VIEWS.PY):- from django.http import HttpResponse def home(request): return HttpResponse("hello world") -
How can i do multiple values filter for multiple fields in Django?
for loc,deg,dept,key,job_role,insti_loc,insti_name,mark,gen,job_type in zip(lst2,lst5,lst6,lst1,lst4,lst8,lst9,lst10,lst11,lst12): if sample_register.objects.filter(city=loc,job_role_1=job_role,qualification=deg,qualification_dept=dept).exists(): print("Inside location and jobrole1 and qualification and department search") for i,j,k,l in zip(lst5,lst2,lst6,lst4): pro_log=sample_register.objects.filter(Q(city=j) & Q(job_role_1=l) & Q(qualification=i) & Q(qualification_dept=k)) -
Django -Display a list of post's categories with a number of post
Hi i am trying to make a template in django that displays a post categories table and has a number of posts with it. I can't seem to make it right using annotate when making queries on my model. like this views.py categorylistcount = Post.objects.all().annotate(posts_count=Count('category')) for obj in categorylistcount: print(obj.category + ' : ' + obj.categories_count) #test im receiving list of posts instead and has a posts_count key with value of 1 models.py class Post(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE ) body = models.TextField() category = models.CharField(max_length=64, default="Uncategorized") date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('blog:post-detail', kwargs={"pk": self.pk}) class Category(models.Model): name = models.CharField(max_length=225) def __str__(self): return self.name where did i miss? thanks -
Set default "This month" choice and date in DateRangeFilter
Now all catalog items are displayed, I would need the default filter to be set to display only items from the current month. In forms I have: date_paid_range = DateRangeFilter(field_name='paid_date') date_range = DateFromToRangeFilter(field_name='paid_date', label='From-To', widget=RangeWidget(attrs={'type': 'date'})) -
Is there anyway to create related entites within a post request with django rest framwork?
If I sound confused, it's because I am. I'm unfamiliar with the django rest framework and I'm attempting to create a relatively simple Recipe-Managing app that allows you to automatically create your shopping list. Motivations : I know that DRF might not be needed and I could just use django, but the point of this app is to learn how to use the DRF. The goal is to create a back with DRF and do some fancy shenanigans with a front framework afterward. Problem: I have a Recipe model which contains a ManyToMany field to Ingredient through RecipeIngredient. And I am a bit confused on how I should approach the RecipeSerializer. So far it looks like that : class RecipeSerializer(serializers.ModelSerializer): class Meta: model = Recipe fields = ('id','name','ingredients','tags','prep_time','cook_time', 'servings', 'instructions') But I feel like whenever I will want to create a Recipe, I'll have to fire a post request to create the Ingredients (if they do not exist yet), one to create the Instructions, one to create the Recipe and one to create the RecipeIngredients. Question : Is there a way to make one request containing the recipe and all sub fields (ingredient, recipeingredient, instruction) and to create all the … -
Invalid parameter in django prefetch_related
These are my models: class MemberShip(models.Model): name = models.CharField(max_length=30, blank=False, help_text="Name shouldn't be longer than 30 characters") description = models.TextField(blank=False, null=True) class UserMembership(models.Model): user = models.OneToOneField('accounts.User', on_delete=models.CASCADE) as_member = models.ManyToManyField(MemberShip, related_name='memberships_as_member') as_affiliate = models.ManyToManyField(MemberShip, related_name='memberships_as_affiliate') def __str__(self): return self.user.email I want to get that which user has selected a membership as_member or as_affiliate, I tried following code: user_memberships_all = UserMembership.objects.filter(id=id).prefetch_related("as_member__usermembership_set") but got this error. AttributeError: Cannot find 'usermembership_set' on MemberShip object, 'as_member__usermembership_set' is an invalid parameter to prefetch_related() like in the picture: I want to get user:pradhumnts@gmail.com as_member when I pass Jai Shree Ram Membership. can anyone please tell me what am I doing wrong here? I can make myself more clear if the problem is not clear. Thank You. -
Filtering tags in M2M Field Django
So I have my models Class Category((models.Model) category = models.CharField() class Group(models.Model) Title = models.CharField() category = models.ManyToManyField(Category, related_name= tags) So I want to be able to filter all the groups with similar tags to the group currently in view In my views.py I tried group = Group.objects.get(id=pk) groups = Group.objects.filter(category=group.category) But that doesn't work -
How to display multiple models in one tab in Django admin?
I made the item and quiz apps with the startapp command. I added the apps to INSTALLED_APPS in settings.py, and registered them on the admin page. admin.site.register(Item) admin.site.register(Quiz) In the admin page, Item tab and Quiz tab exist separately, and models can be modified in each tab. I want to combine these two tabs into a tab called 'foo'. How can I solve this? -
TypeError: can't subtract offset Naive and offset-aware datetimes i want to minus two dates and I got this error?
#models.py from django.db import models class User(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) mobile_number = models.IntegerField() cnic = models.CharField(max_length = 13) blood_group = models.CharField(max_length= 10) last_donation = models.DateTimeField(auto_now_add=True) #views.py from django.shortcuts import render from .models import * from .forms import UserForm def home(request): return render(request, 'home.html') def donor(request): if request.method == "POST": userform = UserForm(request.POST) if userform.is_valid(): userform.save() else: userform = UserForm() return render(request, 'donor.html',{'userform':userform}) #forms.py from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import User from datetime import datetime,timedelta class UserForm(ModelForm): class Meta: model = User fields = "__all__" def clean_cnic(self): cnic = self.cleaned_data['cnic'] print("This is a cnic",cnic) existuser = User.objects.get(cnic = cnic) if existuser: print(existuser) previous_date = existuser.last_donation current_date = datetime.now() print(previous_date,current_date) Output:-> Previous:> 2021-12-17 12:38:35.717900+00:00 Current:> 2021-12-18 14:44:23.569193 Here I want to minus these two dates but I Got error this final = Current date - Previous date Last line is not working I want to minus the two dates Both date picked from system automatically -
How to use Substr with an F Expression
I'm trying to build a toolkit of Func classes built on the fuzzystrmatch postgres extension. For instance I have this wrapper which takes in an Expression and a search term and returns the levenshtein distance: class Levenshtein(Func): """This function calculates the Levenshtein distance between two strings:""" template = "%(function)s(%(expressions)s, '%(search_term)s')" function = "levenshtein" def __init__(self, expression, search_term, **extras): super(Levenshtein, self).__init__( expression, search_term=search_term, **extras ) Called like this, using an F Expression: Author.objects.annotate(lev_dist=Levenshtein(F('name'),'JRR Tolkien').filter(lev_dist__lte=2) However if the 'name' field here is greater than 255 it throws an error: Both source and target can be any non-null string, with a maximum of 255 characters. I can truncate the name when I annotate using Substr: Author.objects.annotate(clipped_name=Substr(F('name'),1,250)) But I can't seem to figure out how to place that logic inside the func, which I'm placing inside an ExpressionWrapper and setting the output_field as per the docs: class Levenshtein(Func): """This function calculates the Levenshtein distance between two strings:""" template = "%(function)s(%(expressions)s, '%(search_term)s')" function = "levenshtein" def __init__(self, expression, search_term, **extras): super(Levenshtein, self).__init__( expression=ExpressionWrapper(Substr(expression, 1, 250), output_field=TextField()), search_term=search_term, **extras ) -
How to display a model data dynamically in Html?
I have a model and in a function this model is updating. I want to display this model's data dynamically. So, new values should display without refreshing the page. How can I do it? models.py class MyLongProcess(models.Model): active_uuid = models.UUIDField('Active process', null=True, blank=True) name = models.CharField('Name', max_length=255) current_step = models.IntegerField('Current step', default=0) total = models.IntegerField('Total', default=0) @property def percentage_sending(self): # or it can be computed by filtering elements processed in celery with complete status return int((current_step / total) * 100) views.py def setup_wizard(request): process = MyLongProcess.objects.create(active_uuid=uuid.uuid4(), name=name, total=100) functions.myClass(..., process=process) .... return render(request, 'setup_wizard.html', context) functions.py class myClass(): def __init__(self, ..., process): self.download_all(..., process=process) @app.task(bind=TRUE) def download_all(self, ..., process): .... for s in scans: .... process.current_step += 1 process.save() ... setup_wizard.html <div class="progress-bar" role="progressbar" style="width: {{ my_model_object.percentage_sending }}%;" aria-valuenow="{{ my_model_object.percentage_sending }}" aria-valuemin="0" aria-valuemax="100">{{ my_model_object.percentage_sending }}% </div> All my function works fine. When I looking the MyLongProcess from Django admin and refresh the page, values are updating. Just I want to display it in frontend without refreshing. -
Many parameters with one name in form and get a list of them in
I have a form with dynamic fields.. When submit form, i have this: Localhost:8000/mysite.com/jobs_form?job="Job1"&job="Job2" And i cant get all of them in django with request.POST.get("job") What can i do? -
need to get data for choice fields in Django form a loop?
The choice field required in django is in the following format new_choices = ( (1, 'Data 1'), (2, 'Data 2'), (3, 'Data 3'), (4, 'Data 4'), (5, 'Data 5'), (6, 'Data 6'), (7, 'Data 7'), ) I am trying to get the data from db but the data is not getting properly CHOICES = heads.objects.filter(brcd=self.n_brcd, status=1, acmast=1) test =([('(' + str(p.head) + '-' + p.detail + ')') for p in CHOICES]) len_of_test = len(test) new_choices =[] for n in range(len_of_test): new_choices = '(' + str(n) + "," + test[n] + ')' The output I am getting from the above code is new_choices = ['(0,(Data 0))','(1,(Data 1))','(2,(Data 2))',...] -
Compile twice in django_tex
I need to compile a .tex file twice with django_tex in order for the table of contents to load correctly. Is there a way to tell the interpreter in django_tex to run the compiler twice (I use pdflatex)?? Code: \documentclass{article} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \begin{document} \tableofcontents \section{Introduction} Introduction text. \section{Second section} Second section text. \end{document} -
if add new blog in database than sent mail to all subscriber to notified current blog in Django
Note: Add new blog only admin panell. model.py class blog(models.Model): author = models.ForeignKey(User, null=True, on_delete=models.CASCADE) blog_id = models.AutoField(primary_key=True) blog_title=models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) slug = models.CharField(max_length=500, blank=True) tags = TaggableManager() blog_category_name=models.ForeignKey(blog_category,on_delete=models.CASCADE,null=True,blank=True) blog_sub_category_name=models.ForeignKey(blog_sub_category,on_delete=models.CASCADE,null=True,blank=True) written_by = models.CharField(max_length=200, default='Prymus Brandcom') image_banner= models.ImageField(upload_to='image_banner') medium_thumbnail = models.ImageField(upload_to='medium_thumbnail') content = RichTextField() # RichTextField is used for paragraphs is_authentic=models.BooleanField(default=False) class Meta: # Plurizing the class name explicitly verbose_name_plural = 'blog' def __str__(self): # Dundar Method return self.blog_title def save(self, *args, **kwargs): # Saving Modefied Changes if not self.slug: self.slug = slugify(self.blog_title) #super(blog, self).save(*args, **kwargs) super(blog, self).save(*args, **kwargs) def snippet(self): return self.content[:300] and it's my subscriber table: class subscriber(models.Model): name=models.CharField(max_length=150,default="") email=models.EmailField(max_length=100) def __str__(self): # Dundar Method return self.name Add new blog in blog table than send mail to all registerd user in subscriber table ??? -
Django vs Django Rest framework , security concern
A traditional website using Django over HTPPS vs Same website using Django rest framework and React JS or other platforms to consume the API. Which would be more secure against DDOS,Spoofing,etc like security breaches ? I hope Rest API is on HTTP and its less secure. Does enabling HTTPS on the REST API server make its API Secure ? -
How can updatee manytomanyfield data
i am trying to update manytomany field data in django. Here is my view: def editRolesView(request, role_id, shop_id): shopId = get_object_or_404(Shop, pk=shop_id) roleId = get_object_or_404(Roles, pk=role_id) permissions = Permission.objects.filter( shop=shopId.id, ) if shopId.user == request.user: if request.method == "POST": permissions = request.POST.getlist("permissions") # cnv_pp = ''.join(permissions) roleId.role_title = request.POST.get("role_title") roleId.shop = Shop.objects.get(id=shopId.id) roleId.save() roleId.permissions = roleId.permissions.set(permissions) roleId.save() return HttpResponse("Edited") # roleId.permissions_set.all() args = { "shopId": shopId, "roleId": roleId, "permissions": permissions, } return render(request, "roles/edit-role.html", args) else: return redirect("warning") Here i tried to update manytomanyfield data. Here is my Model class Permission(models.Model): shop = models.ForeignKey(Shop, on_delete=models.SET_NULL, null=True) permission_title = models.CharField(max_length=255) class Meta: ordering = ["-id"] def __str__(self): return self.permission_title class Roles(models.Model): shop = models.ForeignKey(Shop, on_delete=models.SET_NULL, null=True) role_title = models.CharField(max_length=255) permissions = models.ManyToManyField(Permission) class Meta: ordering = ["-id"] def __str__(self): return self.role_title Whenever i try t save the data it says this error: Direct assignment to the forward side of a many-to-many set is prohibited. Use permissions.set() instead. The data is saving but its throwing this error. Is there any way to solve this issue ? Here is my template <form action="" method="POST"> {% csrf_token %} <label>Set Role Title</label></br> <input type="text" name="role_title" value="{{ roleId.role_title }}"><br> {% for p in roleId.permissions.all %} <input … -
How to return to previous version of pip install in django
I have recently downloaded a django project from github, and I downloaded all of the pip install requirements using: pip install -r requirements.txt However, I realised that I did not set a virtual env for this project, so it seems that the pip installs have affect the entire computer. I am now getting an error like below when I try to runserver my other django projects: Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run self.check_migrations() File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 458, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__ self.build_graph() File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\loader.py", line 274, in build_graph raise exc File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\loader.py", line 248, in build_graph self.graph.validate_consistency() File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\graph.py", line 195, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\graph.py", line 195, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "C:\Users\jsooh\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\graph.py", line 58, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration leads.0001_initial dependencies reference nonexistent parent node ('auth', '0012_alter_user_first_name_max_length') Traceback (most recent call last): File "C:\Users\jsooh\projects\Sevenenglish\11-3\manage.py", … -
How to retrieve all fields from a ForeignKey after a filter query in django
I have the following models using django class Action(models.Model): name = models.CharField(max_length=100, unique=True) slug = models.SlugField(max_length=100, db_index=True, blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Concert(models.Model): action = models.ForeignKey(CoreAction, on_delete=models.SET_NULL, related_name="action_concert") is_live = models.BooleanField(default=False) name = models.CharField(max_length=100, unique=True) created = models.DateTimeField(auto_now_add=True) I am trying to display a list of Concert live, at the same time make sure that I get all the fields from the action table for each instance associated to it. concerts = Concert.objects.filter(is_live=True).values("id", "name") current result => All the concerts live This is the first step but i am stuck trying to join each instance of the list to it correspondent fields in Action. Any help would be helpful, thanks -
My GoDaddy domain serves a blank page when I connect it with my Heroku App
Recently, I built a Heroku app using Django and React. The app works wonderfully, however when connected to GoDaddy's domain, it serves a blank page. I won't say anything else, partly because I don't know what information is necessary, but request you to ask the right question for me to provide more information. Thanks. -
Django says: too many values to unpack (expected 2)
I'm using Django. In the upload_book function, I generate a 10-digit code for each book and I identify and distinguish two books from one another by their code, rather than their primary key. However, I get an error in the generate_code function: ValueError at /main/upload_book/ too many values to unpack (expected 2) Here is the generate_code() function with required imports: import random, string def generate_code(max_length): code = ''.join(random.choices(string.ascii_letters + string.digits, k=max_length)) while len(Book.objects.filter(code)) != 0: code = ''.join(random.choices(string.ascii_letters + string.digits, k=max_length)) return code I did the extra bit over there to prevent two books being of the same code, however low the probability of that might be with 629 possible combinations. And here's my upload_book() function: @login_required def upload_book(request): if request.method == 'POST': title = request.POST.get('title') description = request.POST.get('description') author = request.POST.get('author') code = generate_code(10) owner = request.user if 'thumbnail' in request.FILES: thumbnail = request.FILES['thumbnail'] book = Book(title=title, description=description, author=author, thumbnail=thumbnail, owner=owner, code=code) book.save() return redirect("/main/all_books/") else: return render(request, 'main/upload_book.html') And my Book model in models.py: class Book(models.Model): title = models.CharField(max_length=1000, blank=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) description = models.TextField() author = models.CharField(max_length=1000, blank=True, null=True) thumbnail = models.ImageField(upload_to='book_thumbnails', blank=True) creation_date = models.DateTimeField(default=timezone.now) status = IntegerField(default=1) min_age = models.IntegerField(blank=True, null=True) … -
Add one field to User
After I switched my Abstract User my login page not on the admin gets a 500 server error. Also my admin gets a weird extension while logged in /pages/profile/. All I wanted to do was add a single field to the user so they can upload a file. models.py from django.db import models from django.contrib.auth.models import AbstractUser class Profile(AbstractUser): """ bio = models.TextField(max_length=500, blank=True) phone_number = models.CharField(max_length=12, blank=True) birth_date = models.DateField(null=True, blank=True) """ avatar = models.ImageField(default='default.png', upload_to='users/', null=True, blank=True) admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import Profile class CustomUserAdmin(UserAdmin): pass admin.site.register(Profile, CustomUserAdmin) settings.py # Extends default user with additional fields AUTH_USER_MODEL = 'pages.Profile' -
How to add fields with default values to the User model in Django
I need to add fields to the User model with default values that will not be displayed in the registration form but I am new to Django. How can I implement it and what am I doing wrong? models.py: from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): level = models.IntegerField(default=0) forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from .models import CustomUser class RegisterUserForm(UserCreationForm): username = forms.CharField(label="Имя", widget=forms.TextInput(attrs={'class': 'register__form-title form-control form-input', 'placeholder': 'введите ваше имя'})) email = forms.CharField(label="Почта", widget=forms.TextInput(attrs={'class': 'register__form-title form-control form-control', 'placeholder': 'введите вашу почту'})) password1 = forms.CharField(label="Пароль", widget=forms.TextInput(attrs={'class': 'register__form-title form-control form-input', 'placeholder': 'введите пароль'})) password2 = forms.CharField(label="Подтверждение пароля", widget=forms.TextInput(attrs={'class': 'register__form-title form-control form-input', 'placeholder': 'подтвердите ваш пароль'})) def __init__(self, *args, **kwargs): super(UserCreationForm, self).__init__(*args, **kwargs) for field_name in ['username', 'email', 'password1', 'password2']: self.fields[field_name].help_text = None class Meta: model = CustomUser fields = ('username', 'email', 'password1', 'password2') views.py: from django.contrib.auth import logout from django.contrib.auth.views import LoginView from django.shortcuts import render, redirect from django.urls import reverse_lazy from django.views.generic import CreateView from .forms import RegisterUserForm, LoginUserForm class RegisterUser(CreateView): form_class = RegisterUserForm success_url = reverse_lazy('login') template_name = 'users/register.html' -
django rest framework: building 2 separate auth and service system
how to implement 2 separate django rest framework system 1 for auth and 1 for service the goal is you get your auth from one api and use other api for services which use the auth for authentication and permission of it's services. my question is on Django rest framework and have 1 database is preferable for me but if you have answer and road to implementation such system with multiple database it would be appreciated too. i want to build entire system for authentication and permission. so i can integrated it with all of my other services