Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Adding model without default ModelAdmin permissions (add, change, delete, view)
I am facing problems with adding simply new permission to admin panel In my models.py i have: class search_hostname(models.Model): class Meta: permissions = [("search_hostname", "Can search hostname")] def __str__(self): return self.application but after makemigrations and migrate in my admin page i get "Can search hostname" and other four default: app | search_hostname | Can add search_hostname app | search_hostname | Can change search_hostname app | search_hostname | Can delete search_hostname app | search_hostname | Can view search_hostname app | search_hostname | Can search hostname i have no old migrations which would cause this is there any way to avoud adding those default permissions and have only Can search hostname in DB -
How to add CheckConstraint between related models
I want to add CheckConstraint which concerned different related models. Users are attached in a particular site (research team/institute) for a given study/project. A user can only be attached to one site for a given study. Sites can be involved or not in differents studies/projects. I want to add a constraint that prevent User to be attached to a study and a site id this site is not involved in this study. Below database model -
How to sent password reset mail from another view?
I have a view to create a restaurant. In the same view a user is also being created. After the user creation, I have to sent a mail to the user with the link to reset the password. My view looks like: def create_restaurant(request): form = RestaurantForm() user_form = RestaurantUserForm() if request.method == 'POST': form = RestaurantForm(request.POST, request.FILES) user_form = RestaurantUserForm(request.POST) if form.is_valid() and user_form.is_valid(): #----user is saved here------ user_obj = user_form.save() #----have to sent the mail here------ #-----restaurant is saved here----- restaurant_obj = form.save() restaurant_obj.user = User.objects.get(id=user_obj.id) restaurant_obj.save() messages.success(request, 'Restaurant Added Successfully.') return redirect('create_restaurant') context = { "title": "Add restaurant", "form": form, "user_form": user_form } return render(request, "restaurant/restaurant.html", context) I have implemented the password reset procedure using urlpatterns = [ path('reset_password/', auth_views.PasswordResetView.as_view(template_name="password_reset.html"), name='password_reset' ), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name="password_reset_sent.html"), name='password_reset_done' ), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="password_reset_form.html"), name='password_reset_confirm' ), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="password_reset_done.html"), name='password_reset_complete' )] How can I sent the email as mentioned above? -
Unable to delete a user in django's built in auth app
When I try to delete a user from Django's built in auth app, I have this error: django.db.utils.OperationalError: no such table: main.auth_user__old I searched on the web and I found this question : Django - No such table: main.auth_user__old So I updated Django and I am now using the version 3.2.4 (I am using sqlite). Then I tried to delete auth tables from the db but when I did a ptyhon manage.py makemigrations auth, it told me that no changes were detected. Also, I can't delete the whole database. Does someone have an idea what I can do to fix this? -
Display Hierarchical Tree (Parent & Child) From Django Self Reference Model
I am trying to generate a nested/hierarchical structure (categories & sub-categories) that will appear on the Django Admin side. This is my current model for the Category. class Category(models.Model): name = models.CharField(blank=False, max_length=200) slug = models.SlugField(null=False) parent = models.ForeignKey('self',blank=True, null=True ,related_name='children', on_delete=models.SET_NULL) class Meta: db_table = "dj_categories" # Add verbose name verbose_name = 'Category' verbose_name_plural = "Categories" unique_together = ('slug', 'parent',) def get_categories(self): if self.parent is None: return self.name else: return self.parent.get_categories() + ' -> ' + self.name def __str__(self): return self.get_categories() This is how my category table looks like.Category table The above code generate the structure like this in the Django admin panel. Category Layout Instead I want to achieve the following structure: Electronics - Mobile - Digital Cameras Fashion - Men Footwear -- Casual Home Appliances - Washing Machine - Air Conditioner -- Windows -- Split Note: I don't want to leverage any third party package such as: Django MPTT or Django Treebeard A complete example to the problem is highly appreciated. -
Updating an existing Serializer class partially for transactional data in mongodb
I have setup the following model for my transactions data from several invoices and I want to be able to update them on API call in case the same invoice's data is passed again. My model is as follows: class GSTTransactions(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) gstin = models.ForeignKey(GSTMaster, on_delete=models.CASCADE, to_field='gstin') transactionType = models.TextField() gstNumber = models.TextField() invoiceDate = models.DateField() invoiceNumber = models.TextField() totalTransactionValue = models.TextField() CGSTAmount = models.TextField() SGSTAmount = models.TextField() IGSTAmount = models.TextField() CSAmount = models.TextField() rate = models.TextField() transactionValue = models.TextField() month = models.TextField() year = models.TextField() dataType = models.TextField() class Meta: db_table = 'gst_transactions' unique_together = (('gstin','gstNumber','invoiceDate','invoiceNumber'),) enter code here My serializer class looks like this: class GSTTransactionsSerializer(serializers.ModelSerializer): class Meta: model = GSTTransactions fields = ['gstin','transactionType','gstNumber','invoiceDate','invoiceNumber','totalTransactionValue','CGSTAmount','SGSTAmount','IGSTAmount','CSAmount','rate','transactionValue','month','year','dataType'] My function for adding/updating data looks like this: def gstTransactionsSave(context): gstin = context['analysisResult']['gstin'] salesData = context['analysisResult']['salesData'] for sales in salesData: try: sales['gstin'] = gstin sales['dataType'] = 'sales' sales['invoiceDate'] = str(sales['invoiceDate']) snippet = GSTTransactions.objects.get(gstin=gstin,gstNumber=sales['gstNumber'],invoiceDate=sales['invoiceDate'],invoiceNumber=sales['invoiceNumber']) serializer = GSTTransactionsSerializer(snippet) sale = serializer.data sale['totalTransactionValue'] = float(sale['totalTransactionValue']) sale['CGSTAmount'] = float(sale['CGSTAmount']) sale['SGSTAmount'] = float(sale['SGSTAmount']) sale['IGSTAmount'] = float(sale['IGSTAmount']) sale['CSAmount'] = int(sale['CSAmount']) sale['rate'] = int(sale['rate']) sale['transactionValue'] = float(sale['transactionValue']) sale['year'] = int(sale['year']) for key in list(sales.keys()): if sales[key] == sale[key]: pass else: print(key) print('Overwriting in progress') newSerializer = … -
Why is_valid returns None when I use PasswordChangeForm? I'm perfectly sure that the credentials I entered are correct
When I try to submit the form, it throws a ValueError. Below is my code. def passchange(request): if request.user.is_authenticated: if request.method == "POST": print(request.POST) fm = PasswordChangeForm(user=request.user, data=request.POST) print(fm) if fm.is_valid(): fm.save() update_session_auth_hash(request, fm.user) messages.success(request, 'Password Changed Successfully') if fm.user.location=="Latur": return HttpResponseRedirect('/laturhome/') elif fm.user.location=="Nashik": return HttpResponseRedirect('/nashikhome/') elif fm.user.location=="Dhule": return HttpResponseRedirect('/dhulehome/') elif fm.user.location=="Akola": return HttpResponseRedirect('/akolahome/') elif fm.user.location=="Solapur": return HttpResponseRedirect('/solapurhome/') else: print(fm.error_messages) return HttpResponse('Not valid') else: fm = PasswordChangeForm(user=request.user) return render(request, 'account/passchange.html', {'form':fm}) else: return HttpResponseRedirect('/login/') The fm.error_messages part in the else part of is_valid shows me the following in the terminal: {'password_mismatch': 'The two password fields didn’t match.', 'password_incorrect': 'Your old password was entered incorrectly. Please enter it again.'} Where did I go wrong? -
Anchor href doesn't work when i add dynamically hr tag after user clicjk
<div class="nav-center"> <ul class="center"> <a class="nav-item" href=""> <li>Random facts</li> <hr class="line"> </a> <a class="nav-item" href="/blog/technology/"> <li>Technology</li> </a> <a class="nav-item" href="/blog/sport/"> <li>Sports</li> </a> <a class="nav-item" href=""> <li>About poeters</li> </a> </ul> </div> //JavaScript Code let navItems = document.querySelectorAll(".nav-item"); let addchild = document.createElement("hr"); addchild.classList.add("line"); let Handler = (e) => { e.preventDefault(); navItems.forEach((node) => { if (node.contains(removechild)){ node.removeChild(removechild); } }); e.currentTarget.appendChild(addchild); }; navItems.forEach((node) => { node.addEventListener("click", Handler); }); See the first anchor tag i added hr tag through html it is showing line below Random Facts and also works fine for my expected link.. But when i add dynamically after user click, line shows but anchor link does not work after user click why?? -
Django REST framework One-to-many relationship and database queries
I am new to django and I am developing my first project with Django REST framework. Models: class Sticker(Model): image = models.ImageField(upload_to=sticker_image_directory_path, null=False) title = models.CharField(max_length=150) def __str__(self): return self.title class StickerTag(Model): name = models.CharField(max_length=100) sticker = models.ForeignKey(Sticker, on_delete=models.RESTRICT, related_name='tags') def __str__(self): return self.name Serializer: class StickerSerializer(serializers.ModelSerializer): tags = serializers.StringRelatedField(many=True) class Meta: model = models.Sticker fields = ['id', 'image', 'title', 'tags', 'countries'] View: class StickerView(mixins.ListModelMixin, viewsets.GenericViewSet): serializer_class = serializers.StickerSerializer queryset = models.Sticker.objects.all() I was debugging call to http://127.0.0.1:8000/stickers/ with django-debug-toolbar. I was surprised to see that for each sticker instance Django makes a query to stickertag table like that: SELECT `stickerapp_stickertag`.`id`, `stickerapp_stickertag`.`name`, `stickerapp_stickertag`.`sticker_id` FROM `stickerapp_stickertag` WHERE `stickerapp_stickertag`.`sticker_id` = 1 Means it is grabbing sticker tags for each sticker one by one. So if there are 10 stickers it will make 10 DB calls with that above query. But I think that those are too many queries and can be reduced by using "IN" clause of MYSQL for example: SELECT * FROM stickerapp_stickertag where sticker_id in (1,2,3,4,5); I don't know how to do that in Django REST framework. Kindly guide! -
Django ORM: recursive query with select_related and prefetch_related
Consider having a family tree, Grandpa, Father and Son models. Facing 2 problems fetching the tree.. First: if we need to fetch all family member we would use recursion for that. psudo code: * get person * if person has a childPerson * execute first step Second: if we want to breakdown the results by filtering psudo code: * get person 'Grandpa' (and filter results for grandpa if filter applied) * if person has a childPerson (father) * execute first step (with filter result 'Father' if filter applied) //filter changes here and changes again with 'Son' How To apply this approach with Django ORM and Models? because I'm searching for days I found this link might help to figure out solution (the closest to my approach), but need expert support to make code works for the approach. -
How to solve NoReverseMatch at / (Error during template rendering) in django 3.2?
Here is the screenshots of error i am getting. and App Name is greeting_app Now greeting_app/urls.py has the following code from django.urls import path from . import views urlpatterns = [ path('', views.home, name="home"), path('about/<int:id>/', views.about, name="about"), ] greeting_app/views.py has the following code from django.shortcuts import render, HttpResponse from .models import basicinformation # Create your views here. def home(request): information = basicinformation.objects.all() return render(request, 'index.html', {"info":information}) def about(request, id): data = basicinformation.objects.get(id=id) return render(request, 'about.html', {"data":data}) templates/index.html has the following code. I have included only the url part in index.html file. <a href="{% url "about" data.id %}">Description</a> -
What exactly is the cause to my InconsistentMigrationHistory in Django
I've noticed that there's some question on this website about this and i've got some solution from them. but my goal with this question is to know the exact problem so I can avoid this in the future and some extra solution is fine I've had this issue after I applied my custom user model account.models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # Create your models class Account(AbstractBaseUser): email = models.EmailField(unique=True, max_length=255) username = models.CharField(max_length=255) is_active = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.email fakeapp.models.py from django.db import models from django.conf import settings # from django.contrib.auth.models import User # Create your models here. class Text(models.Model): text = models.CharField(max_length=30) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return self.text for some more context before I made this custom user model I was using default User model and I've already made data stored in the Text table with it. So by best guess is that is why this error occurred. Is that true or maybe there's other things that caused this?. -
django production server allow user to access requirements.txt and other file like manage.py
I find a big security breaches server allow user to access files example: a user can access https://example.com/app_directory/requirements.txt and the worst is i can download all file.py by doing https://example.com/app_directory/site/manage.py Content-Encoding deflate can be the cause. How can i fix that? -
Can't Send Mails on given schedule using Django Crontab
Hi i want to send emails to clients in every 1 minute. I follow this https://pypi.org/project/django-crontab/ documentation but it works only when i want to create objects in my models but it will not work on sending mail. The data i want to send through my mail is fetch from mysql database and i want to send this data as a tabular form in HTML. Code Not work and also i can't find my error. Here is my cron.py from django.shortcuts import render from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string from django.utils.html import strip_tags from .models import Test from project.settings import EMAIL_HOST_USER from django.http import HttpResponse def my_scheduled_job(): query= Test.objects.all() html_content = render_to_string("email.html",{'result':query}) text_content = strip_tags(html_content) msg = EmailMultiAlternatives( "Today Test Report", text_content, EMAIL_HOST_USER, ['reiever@gmail.com'] ) msg.attach_alternative(html,"text/html") msg.send() Here is my email.html file <!DOCTYPE html> <html> <head> <title>Report</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> </head> <body> <table class="table table-dark"> <thead> <tr> <th scope="col">Testing Name</th> <th scope="col">Testing Date</th> </tr> </thead> <tbody> {% for i in result %} <tr> <td>{{ i.test_name}}</td> <td>{{ i.test_date}}</td> </tr> {% endfor %} </tbody> </table> </body> </html> Here is my models.py file from django.db import models … -
Django webhooks
Need help in creating and understanding webhooks in Django.From where should I start ? How should I get to learn to implement a simple webhook in which I pass 2,3 parameters like id and name and it should get printed through the URL into the view without any third party or package. -
Django api stopped working as postgres uses 100% cpu on ubuntu server?
I have deployed a Django application on a 32GB ram ubuntu server while calling an API CPU uses reaching 100% due to Postgres, which I track through the top command. Postres configuration is already tuned up. Please suggest how to resolve thi. -
Filter queryset using child object fields
I have two models Parent, Child class Parent(models.Model): id = models.IntegerField(...) class Child(models.Model) id = models.IntegerField(...) parent = models.ForeignKey(Parent, ...) wanted = models.CharField(default="yes") I want to filter all Parent objects where all the children present with that parent will have 'wanted' as 'yes' My code: def containsYes(self): yes_ids = [] qs = self.get_queryset() for q in qs: children = Child.objects.filter(parent_id = q.id) count = children .count() if children.filter(wanted = 'yes).count() == count yes_ids.append(q.id) return qs.filter(id__contains = yes_ids) I know that this code is dead inefficient, and want a better solution using only querys PS: Im new to django -
Query on BooleanFields using string representations of the fields
How can I filter on the boolean fields of a model, given a string representation of the attribute, taken to mean true for that attribute? As an example, given: class MealBooking(models.Model): breakfast = models.BooleanField() lunch = models.BooleanField() dinner = models.BooleanField() meal = "breakfast" How can I filter on all MealBookings containing True for the field represented by meal? -
Django DRF unit tests added with dynamic mixins via metaclass not being executed
I am trying to test DRF endpoints, and trying to add mixings dynamically to a test in order to execute tests again each method allowed in the endpoint (get, post, put, patch, delete) So, my idea is to make a base test class that will automatically add some mixings to test endpoints if they are allowed. And I can create the actual test that will inherit from this base class. The code: from rest_framework.test import APITestCase class GetTestMixin: def test_get_all(self): response = self.client.get(self.uri) self.assertEqual(response.status_code,status.HTTP_200_OK) class AutoMixinMeta(type): def __call__(cls, *args, **kwargs): allowed_methods = ['get', 'post'] # cls would be the Test class, for example TestExample # cls.__bases__ is a tuple with the classes inherited in the Test class, for example: # (<class 'unit_tests.endpoints.base_test.RESTTestCase'>, <class 'rest_framework.test.APITestCase'>) bases = cls.__bases__ for method in allowed_methods: bases += (cls.method_mixins[method.lower()],) # Create a new instance with all the mixins cls = type(cls.__name__, bases, dict(cls.__dict__)) return type.__call__(cls, *args, **kwargs) class RESTTestCase(metaclass=AutoMixinMeta): uri = None method_mixins = { 'post': PostTestMixin, 'get': GetTestMixin, } class TestExample(RESTTestCase, APITestCase): uri = reverse('somemodel-list') I was expecting test_get_all to be executed, but it is not. Mixings are in place. I made a dummy method inside TestExample and put a debugger in place, and … -
Django Tenant with permissions
I'm working on a small project using Django Tenants package https://django-tenants.readthedocs.io/en/latest/install.html, and i would like to know how can i use permissions since i'm using different schemas, Thank you -
Is there a way to force usage of the DB Router, even if some model queries have specific the database using
We have a legacy project where traditionally developers explicitly specified the database to be used like so:- Fruits.objects.using('db_xyz').filter(id__in=12,23) But now we have introduced a custom DB Router that decides the DB to be used, thus taking away the decision from every individual that writes such code. This works very well. But we still need to fix all older code to avoid passing "using", since doing this causes the DB Router to get bypassed. My question is, is there any way that we can force usage of the DB Router, even for model usage that specifies the database to be used? Basicall, the above code exists in 100s of places, and we don't want to have to fix it in all places to look like Fruits.objects.filter(id__in=12,23) -
what exactly does request.user return in django, can we compare it with a string?
I am new to Django and trying out somethings. I am thinking to return a page named "in_accessable.html" if a normal user access the "\create" page (which calls the function named medicine_create_view"), else medicine_create.html. The name of admin is "npend" so I gave a if statement to check if the user name is 'npend' or not, I used request.user method to get the user name, even if I access the page with admin I am getting a false in if statment I tried printing request.user == "npend", which prints False every time. Can anyone help me rectifing this problem, Thank You. Code Used: def medicine_create_view(request, *args,**kwargs): my_form = Raw_Medicine_Form() if request.method == 'POST': my_form = Raw_Medicine_Form(request.POST) if my_form.is_valid(): print(my_form.cleaned_data) Medicine.objects.create(**my_form.cleaned_data) else: print(my_form.errors) my_form = Raw_Medicine_Form() context ={ "form" : my_form, } #print(request.user=="npend") if(request.user=="npend"): return render(request,"App_1/medicine_create.html",context) else: return render(request,"error_files/not_acessable.html",{}) -
Member is not adding in Group after Accept Request
I am building a simple BlogGroupApp in which users can make a group and post blogs init, AND i build feature of join group by Request, in which user have to send a join request and then creater will approve it, BUT When i click on accept_it then members is not adding in group. models.py class Group(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) title = models.ForeignKey(max_length=30,default='') members = models.ManyToManyField(User,related_name='group_member',blank=True) class GroupRequest(models.Model): group = models.ForeignKey(Group,on_delete=models.CASCADE) request_sender = models.ForeignKey(User, on_delete=models.CASCADE) views.py def accept_it(request,pk): group_request = get_object_or_404(Group,pk=pk) sent_request = get_object_or_404(GroupRequest,pk=pk) group_request.members.add(sent_request.request_sender) return redirect('home') Group_detail.html {% for requests in group_requests %} {{ requests.request_sender }}<a href="{% url 'accept_it' requests.id %}">Accept it</a> {% endfor %} When i click on Accept it then it redirects on another group BUT is is not adding the member in the group. AND When i try <a href="{% url 'accept_it' requests.request_sender.id %}">Accept it</a> Then it is saying :- Page not found (404) I have no idea, what am i doing wrong. Any help would be much Appreciated. Thank You in Advance. -
What is the thing wrong with my code ? It is not working
enter image description here This is the code in image :- <div class="m-3 p-3"> <a href="#" data-toggle="modal" data-target="#exampleModal" class="btn btn-outline-info border rounded col-lg-3 float-right">Check out</a> </div> -
How to use same backend (django) api cookie to frontend(vuejs)?
I've got confusion when dealing with cookies on frontend vs backend. I've a cookie generated in backend as class JWTAuthentication(BaseAuthentication): def authenticate(self, request): token = request.COOKIES.get('jwt') if not token: return None try: payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256']) except jwt.ExpiredSignatureError: raise exceptions.AuthenticationFailed('unauthenticated') user = get_user_model().objects.filter(id=payload['id']).first() if user is None: raise exceptions.AuthenticationFailed("Unauthenticated") return (user, None) When i use login in frontend vuejs, a cookie is generated through api , which cookie is a also added by frontend and marked as httpOnly . I want to use same cookie without making new one in frontend. In frontend When I console.log document.cookie the generated cookie is not available , although it shows cookies generated, but at same time at backend when i access api and see console.log(document.cookie) it is available there. How can i access access that cookie even in frontend, through vuejs/javascript through document.cookie , so that i can do authentication and global guards in frontend. Thank you for helping.