Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
List_editable in django-django admin when check a boolean field modify other tables in database
I want to ask a question about the list_editable column in django-admin. If I have something like this: class fooAdmin(admin.ModelAdmin): list_display = ('name', 'age', 'boolean_field') list_editable = ('boolean_field') is it possible that when i enable (or disable) this list_editable field i trigger something that modify other table in database? e.g. if boolean_field became checked and I save it, automatically add or delete a row in another table? Thanks in advance. -
ValueError: The 'image' attribute has no file associated with it. when testing a model with a NULLABLE image field
I'm testing a model called Category that looks like this: class Category(models.Model): image = models.ImageField(upload_to='images', null=True, blank=True) title = models.CharField(max_length=200, unique=True, blank=False, null=False) As you can see the image field is nullable but when I try to create a Category instance in my TestCase Im getting the following error: raise ValueError("The '%s' attribute has no file associated with it." % self.field.name) ValueError: The 'image' attribute has no file associated with it. Here's the test: def setUp(self): self.category = Category.objects.create(title='test_category') I already tried creating it like this: Category.objects.create(title='test_category', image=Null) But it didn't work. -
I need to create a formatted reference code in django. the increment should be based on the category. any idea on how to this
class Category(models.Model): categories = models.CharField(max_length=100) shortterm = models.CharField(max_length=20, null=True, blank=True) class Requestor(models.Model): id = models.AutoField(primary_key=True) date_filed = models.DateTimeField(auto_now_add=True, null=True, verbose_name='date_filed') category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True, verbose_name="Category") **reference_code = models.CharField(max_length=500, verbose_name=( 'Reference'), default='Auto Assign', blank=True)** The result for the reference code should be like this. |id|date_filed|category|reference_code| |1 |01012021 |local |lsp-01012021-1| |2 |01012021 |foreign |fsp-01012021-1| |3 |01012021 |local |lsp-01012021-2| -
Getting <django.db.models.query_utils.DeferredAttribute object at 0x7fca8f1d3d50> in model fields instead of actual values
In the code below, I've created an endpoint to create a user in the database. class ClientViewSet(viewsets.ModelViewSet): serializer_class = ClientSerializer queryset = Clients.objects.all() @action(detail=True, methods=["POST"]) def create_client(self, request, pk=None): Clients.objects.create(client_id=pk, username=Clients.username, password=Clients.password, first_name=Clients.first_name, last_name=Clients.last_name, address=Clients.address) return Response("User Created", status= status.HTTP_200_OK) This indeed creates an instance in the the model, but each field contains texts similar to "<django.db.models.query_utils.DeferredAttribute object at 0x7fca8f1d3d50>" instead of the actual values. I used Postman as a tool, and is how I created this instance, if I just use a 'Post' method on the url ../client/ instead of ../client/pk/create_client/ it returns the correct values. -
Conditionally insert a piece of Django template with HTML code into my template using Javascript
I am trying to create a template with Django to use with all the pages I have in my project. All the pages display similar tables which makes it easier but some of them require an extra check or two. So in writing this one-size-fits-all template, I would like to have this piece of code if it is one type of page: {% if not package_check %} <p style="color:red">Package not found, so script did not run. Install package and try again</p> {% elif count|length %} <!-- rest of html template --> {% endif %} Otherwise, I would like to have this piece of code: {% if count|length %} <!-- rest of html --> {% endif | length %} Since they are very similar I am wondering if it's possible (and how can I do it) to insert it into the HTML with Javascript when loading the page and make it test for the Django variables in the template tags. -
How to send a query from the frontend (React) to Django with Rest Framework
i want to receive a particular input from the frontend react textarea to perform a certain function in django backend. Anybody to help. i want to send a input's from the textarea to my backend React Frontend import React, { Component } from 'react'; import axios from 'axios'; class QueryBuilder extends Component{ render() { return ( <div> <form> <textarea cols="100" rows="20" name="text" /> <br /><br /> <button>Execute Query</button> </form> </div> ) } } export default QueryBuilder; import React, { Component } from 'react'; import axios from 'axios'; class QueryBuilder extends Component{ render() { return ( <div> <form> <textarea cols="100" rows="20" name="text" /> <br /><br /> <button>Execute Query</button> </form> <br /><br/> </div> ) } } export default QueryBuilder; views.py from django import db from django.shortcuts import render, HttpResponse from rest_framework import generics from .models import Test from .serializers import TestSerializer from pymongo import MongoClient from ast import literal_eval from rest_framework import viewsets, permissions # from .models import Test # from .serializers import TestSerializer #Test Viewset class TestViewset(viewsets.ModelViewSet): client = MongoClient() db = client.test # collect = db['state_entry'].find({}) queryset = db['queryTest_test'].find({}) permission_classes = [ permissions.AllowAny ] serializer_class = TestSerializer ---------- Serializer.py from rest_framework import serializers from queryTest.models import Test # Test Serializers … -
Django import Error(from extras.plugins import PluginConfig)
I'm new to Django and I try to develope a plugin for NextBox using this framework. To get familliar with it I'm using documentation from NextBox for this. My Problem is that I try to import a class as shown in the tutorial I get an Error that the package is unkown. When I want to install the package via PyCharm it seems to be the wrong one. Maybe someone of you can help me? Doc: https://netbox.readthedocs.io/en/stable/plugins/development/ from extras.plugins import PluginConfig class NextBoxUIConfig(PluginConfig): In the IDE it says that extras is unkown after installing the package, .plugins is unkown as well as PluginConfig -
Find entities for specific user through multiple tables in Django Admin
I searched through stackoverflow about this particular scenario, but could not find a concrete answer, so i'm posting this. So my problem is that i need to display specific records to a specific user in Django Admin. I'm aware that i can get the concrete user through the get_queryset method extracting it from the request object. But the issue is i need to look through 6 tables to get to the information about the user. For example, if the records i need to display come from a Recommendation table, it has a reference to TableA, which has a reference to TableB .... which has a reference to TableF which has a reference to the User. I'm aware i could do this by executing a plain SQL query with multiple joins, but my guess is that there must be a pythonic or Django sophisticated solution to this. But i may be wrong. The model is unfortunately not in my control, nor i can change it, so i'm left to work with the state of the model that there is. Thanks in advance. -
How to access child class object that inherits parent class?
I have parent class and child class, that inherits parent class. And that is okay, I can iterate with for loop. Now I want to access child class (example: 'details = models...' So basically, I'm confused how we inherits stuff from child class inside the same loop... views.py from django.views import generic from . models import Category from django.shortcuts import render class CategoryListView(generic.ListView): model = Category template_name = 'category_list.html' models.py from django.db import models import uuid class Category(models.Model): name = models.CharField(max_length=100, help_text='Category name') def __str__(self): return self.name class Meta: verbose_name_plural = 'Categories' class Product(models.Model): product_name = models.CharField(max_length=255, help_text='Product name') # product_spec = models.TextField(max_length=5000, help_text='Product specs') product_type = models.ForeignKey('Category', on_delete=models.SET_NULL, null=True) def __str__(self): return self.product_name category_list.html {% extends 'base.html' %} {% block body %} {% for page in category_list %} <li>{{ page.name }}</li> <li>{{ page.product_name }} #<---------------- Now this is the point of # my problem, I want to get product name from child class, this returns empty <li> {% endfor %} {% endblock %} -
Correct way to pass parameters to django view
I'm implementing the Rango project from the Tango with Django 2 book and I need to add a view that counts redirects to external pages for each page. I thought that a good way to do this is to use angle brackets in the url mapping to capture the id of the page by passing it as argument in the template, but later noticed that the book uses a different approach and I'm wondering which one is better and why? I don't like it that my solution doesn't use the request parameter, but it looks cleaner to me. My solution: URL path: path('goto/<int:page_id>', views.goto_page, name='goto'), Anchor: <a href="{% url 'rango:goto' page.id %}">{{ page.title }}</a> View: def goto_page(request, page_id): try: requested_page = Page.objects.get(id=page_id) requested_page.views += F('views') + 1 requested_page.save(update_fields=['views']) except Page.DoesNotExists: return redirect(reverse('rango:index')) return redirect(requested_page.url) Book's solution: URL path: path('goto/', views.goto_page, name='goto'), Anchor: <a href="{% url 'rango:goto' %}?page_id={{ page.id }}">{{ page.title }}</a> View: def goto_page(request): if request.method == 'GET': page_id = int(request.GET['page_id']) try: requested_page = Page.objects.get(id=page_id) requested_page.views += F('views') + 1 requested_page.save(update_fields=['views']) except Page.DoesNotExists: return redirect(reverse('rango:index')) else: return redirect(reverse('range:index')) return redirect(requested_page.url) -
How to get user's phone number from python social auth(google-oauth2)
I use python social auth and django rest framework. I want to fetch the user phone number. Settings SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = config('GOOGLE_ID') SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = config('GOOGLE_SECRET') SOCIAL_AUTH_RAISE_EXCEPTIONS = False SOCIAL_AUTH_USER_MODEL = 'users.TransUser' SOCIAL_AUTH_GOOGLE_OAUTH2_USER_FIELDS = ['email', 'firstname', 'lastname', 'phone_number'] SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = [ 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/user.phonenumbers.read', 'profile', 'email', ] Ouput {'access_token': 'xxxxxxxx', 'email': 'xxxxxxxx, 'email_verified': True, 'expires_in': 3582, 'family_name': 'xxxxxxx', 'given_name': 'xxxxx', 'id_token': 'xxxxxx', 'locale': 'es', 'name': 'xxxxxxx', 'picture': 'xxxxx', 'scope': 'https://www.googleapis.com/auth/userinfo.email ' 'https://www.googleapis.com/auth/user.phonenumbers.read ' 'https://www.googleapis.com/auth/userinfo.profile openid', 'sub': 'xxxxxx', 'token_type': 'Bearer'} but never phone number. I use user's phone number to registration it. I activated people APi in google console. Thx you -
django with postfix doesn't send email and doesn't raise an error
i have configured postfix as a null client on my machine and the configuration also seems to be working, as $ echo "test" | mail -s "test" -r "sender@domain.com" recipient@domain.com successfully delivers the email. however if i try to use it with django with the following settings: EMAIL_HOST = "localhost" EMAIL_PORT = 25 EMAIL_HOST_USER = "" EMAIL_HOST_PASSWORD = "" DEFAULT_FROM_EMAIL = "sender@domain.com" SERVER_EMAIL = "sender@domain.com" the process get's stuck without an error being raised: from django.core.mail import send_mail from django.conf import settings send_mail(subject="test", message="test", from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=["recipient@domain.com"]) i can't figure out why this function get's stuck, the /var/log/mail.log file is also empty. Edit: Note, that sender@domain.com and recipient@domain.com are both valid adresses but i replaced them in this question. -
How to test if user can register and is redirected to home page?
I am writing tests in order to see if a user can register and if successful, is redirected to home page. I have created a class RegisterPageViewtest(TestCase): def setUp(self): self.register_url=reverse('register') self.user={ 'username':'username', 'password':'password', 'password2':'password', 'first_name':'first_name', 'last_name':'last_name', 'email':'email@gmail.com' } with a function: def test_user_can_register(self): response = self.client.post(self.register_url,self.user,format='text/html') self.assertEqual(response.status_code,302) However, when I run tests I get a response in a console: AssertionError: 200 != 302 How can I fix it? -
How To Make Every Fifth Post An Ad Post In Django
I am trying to allow users to sponsor a post to bring more clicks to there posts. I want to make every fifth post a post that is a sponsored post but if i try to just use divisible by in the templates and loop through ads then it will post all of the ads after the fifth post here is some code i have tried models: class Ad(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True) views: def home(request, pk): context = { 'products': Post.objects.all(), 'ads': Ads.objects.all(), } return render(request, 'new.html', context) templates i have tried but don't work: {% for item in products %} //prints products {% if forloop.counter|divisibleby:4 %} {% for i in ads %} {% with it = forloop.parent.loop.counter|div:4 %}//this will give error //prints ad post {% endwith %} {% endfor %} {% endif %} {% endfor %} -
I have a Validation error in my Django models.py file
I am making a table in Django with the models.py file and when I run the code it gives a validation error which goes like this: django.core.exceptions.ValidationError: ['“null” value must be either True or False.'] this is my models.py file from django.db import models class Users: id = models.IntegerField(primary_key=True) first_name = models.CharField(max_length=250) last_name = models.CharField(max_length=250) username = models.CharField(max_length=50) password = models.CharField(max_length=300) birthday = models.DateField(auto_now_add=False) date_created = models.DateTimeField(auto_now_add=True) terms_confirmed = models.BooleanField(default=False) I have tried commenting out the fields with boolean values along with singling out each line to see if it produces the error -
How to open bash_profile in windows 10
Can anyone please help me with this error bash: /c/Users/ADMIN/.bash_profile: No such file or directory I am doing this for the first time so need help to resolve this error. -
Django how to customize upload_to function
I created a system with Django. In this system a user has more than one customers. There is a customer list. A user can upload files to a customer's page. What I want to is the file should save in a file and path of this file should be customer_customername (For example: customer_Emily). But in my code created a file that name as customer_None. How can i fix it? file upload model and customer model are 2 different models that connecetd with a foreign key owner Pdf/models.py def customer_directory_path(instance, filename): return 'customer_{0}/{1}'.format(instance.id, filename) class Pdf(models.Model): CHOICES = [ ... ] STAT = [ ... ] id = models.AutoField(primary_key=True) title = models.CharField(max_length=200) pdf = models.FileField(upload_to=customer_directory_path) owner = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True) customer/models.py class Customer(models.Model): customer_name = models.CharField(max_length=20) ... id = models.AutoField(primary_key=True) -
Set Selected Value In Html Dropdown List Option With Django Jinja Or Python
I want to set the default selected value from for loop in for loop using python or a jinja code with the if-else statement. {% for product in product %} <label>Supplier Name<span class="text-danger">*</span></label> <select class="form-control" name="fk_supplier"> <option>-- Select Supplier Name --</option> {% for supplier in supplier %} {% if supplier.supplier_name == product.fk_supplier %} <option value="{{supplier.pk}}" selected>{{supplier.supplier_name}}</option> {% else %} <option value="{{supplier.pk}}">{{supplier.supplier_name}} {{product.fk_supplier}} </option> {% endif %} {% endfor %} </select> {% endfor %} -
avoid html button being clicked again before it disapears (django)
I'm working in a Django project which has events that can be joined by users (adding the user_id and event_id to a model attend), In my event I have a join button form that when clicked adds the attend, after clicking the button disappears and appears a new button called leave event and the opposite. All this works, when the user joins or leaves the event page reloads. The problem I'm having is that I'm able to click the button 2 times in a row before the button disappears getting an error because it is trying to add an attend object that already exists or delete an object that does not exist. So my question is if there is a way to avoid the user clicking two times the button so it is not sending a POST request 2 times, or at least if he clicks it again before it disappears not sending a request. Here the javascript to show the join or leave button which is executed when the page is loaded or either button is clicked (I first looked in the list of attendants if the logged user is attending, because I didn't find a way to query … -
Comments are not saving from frontend in django
Hi everyone the comments are not working with CBV my form not even saving the comment. here is my code i will love if anyone help me with this.my models.py is class Product(models.Model): title = models.CharField(max_length=110) slug = models.SlugField(blank=True, unique=True) price = models.DecimalField(decimal_places=2, max_digits=6) discount_price=models.FloatField(blank=True, null=True) size = models.CharField(choices=SIZE_CHOICES, max_length=20) color = models.CharField(max_length=20, blank=True, null=True) image = models.ImageField(upload_to=upload_image_path) description = models.CharField(max_length=1000) featured = models.BooleanField(default=False) author = models.ForeignKey(User, on_delete=models.CASCADE) time_stamp = models.DateTimeField(auto_now_add=True) objects=ProductManager() def get_absolute_url(self):#i use this in product_list.html to go to detail page #return "/product/{slug}".format(slug=self.slug) return reverse("products:detail", kwargs={"slug" : self.slug}) def __str__(self): return str(self.title) @property def name(self): #sometime in html i say name istead of title so to make it work i wrote this return self.title def product_pre_save_reciever(sender, instance, *args, **kwargs):#i inherit unique slug generator from utils to here so when i create aa new instance it slug automatically generate. and i i create two t shirts it give a random straing to tshirt 2nd slug if not instance.slug: instance.slug=unique_slug_generator(instance) pre_save.connect(product_pre_save_reciever, sender=Product) class Comment(models.Model): product=models.ForeignKey(Product , related_name="comments", on_delete=models.CASCADE) name = models.CharField(max_length=255) body=models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s'%(self.product.title, self.name) my forms.py is: from django import forms from .models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment … -
Django button in admin
On user form view, add button "Login As", that button will execute functionality that we login as that user. Only admins can see/execute this functionality. This is my question, how this to make? -
How to create breadcrumb in my view function BY mptt
How to create breadcrumb in my view function? class Category(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') slug = models.SlugField( null=True, blank=True) description = models.TextField(null=True, blank=True) image = models.ImageField( upload_to=user_directory_path, default='posts/default.jpg') def get_absolute_url(self): return reverse('Category:post_single', args=[self.slug]) class Meta: ordering = ('-name',) def __str__(self): return self.name class Post(models.Model): class NewManager(models.Manager): def get_queryset(self): return super().get_queryset() .filter(status='published') options = ( ('draft', 'Draft'), ('published', 'Published'), ) category = TreeForeignKey('Category', on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=250) excerpt = models.TextField(null=True) image = models.ImageField( upload_to='uploads/', default='posts/default.jpg') image_caption = models.CharField(max_length=100, default='Photo by Blog') slug = models.SlugField(max_length=250, unique_for_date='publish') publish = models.DateTimeField(default=timezone.now) author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='blog_posts') content = models.TextField() status = models.CharField( max_length=10, choices=options, default='published') favourites = models.ManyToManyField( User, related_name='favourite', default=None, blank=True) likes = models.ManyToManyField( User, related_name='like', default=None, blank=True) like_count = models.BigIntegerField(default='0') views = models.PositiveIntegerField(default=0) thumbsup = models.IntegerField(default='0') thumbsdown = models.IntegerField(default='0') thumbs = models.ManyToManyField(User, related_name='thumbs', default=None, blank=True) objects = models.Manager() # default manager newmanager = NewManager() # custom manager def get_absolute_url(self): return reverse('blog:post_single', args=[self.slug]) class Meta: ordering = ('-publish',) def __str__(self): return self.title #views def post_single(request, post): post = get_object_or_404(Post, slug=post, status='published') postcat = Post.objects.filter(category=post.category) fav = bool if post.favourites.filter(id=request.user.id).exists(): fav = True allcomments = post.comments.filter(status=True) page = request.GET.get('page', 1) paginator = Paginator(allcomments, 10) … -
Django SearchVector postgres searchvector not saving correct strings
The postgres SearchVector in Django seems to be shortening my strings, I dont understand why. Ive shortened the code below to show what is happening. I am querying a person object with a lastname that is added to the SearchVector. from django.contrib.postgres.search import SearchVector self.model.objects.annotate( search=SearchVector( "last_name" ) ).filter(search__icontains="hjer").first().search reults in: "'hjerp':1" But the last_name is actually: self.model.objects.annotate( search=SearchVector( "last_name" ) ).filter(search__icontains="hjer").first().last_name 'Hjerpe' Why is the e not present in the search string? I would expect search above to show: "'hjerpe:1'" -
How to correctly migrate a Django application from SQL Lite to MySql database?
I am very new in Python and Django (I came from Java and Angular) and I am starting working on a Django project made by someone else. I studied Python and Django byt I have the following doubt about what could be a good approach to solve the following problem. This Django application it is using SQL Lite as database. First thing that I have to do is to change RDBMS in order to use MySql instead SQL Lite. I know that, after the MySql installation, I have to change these lines form the settings.py file in order to point to my MySql installation: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } And now my doubt. At the moment my SQL Lite database contains some tables that came from the classes defined into my models.py file. I know that in theory these tables can be automatically generated on the new MySQL database using the migrations (the data are not important because these tables derived from the models at the moment are empty). But my SQL Lite database contains also some Django tables related to users, groups and permissions and some other tables automatically generated by Django. … -
How to Create custom permission classes?
models: class DoctorProfile(AbstractBaseUser, PermissionsMixin): id=models.AutoField(primary_key=True) name = models.CharField(_('name'), max_length=50, blank=True) mobile = models.CharField(_('mobile'), unique=True, max_length=10, blank=False) # mobile= models.CharField(primary_key=True , max_length=10, validators=[RegexValidator(r'^\d{1,10}$')]) # mobile= models.IntegerField(validators=[MinValueValidator(10),MaxValueValidator(10)]) email = models.EmailField(_('email address'), blank=True) password = models.CharField(_('password'),max_length=25,blank=False) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) is_verified=models.BooleanField(default=False) is_active = models.BooleanField(_('active'), default=False) is_doctor = models.BooleanField(_('active'), default=False) otp = models.IntegerField(null=True, blank=True) dob=models.DateField() GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) How to Create custom permission for creating tasks ? eg: class ClinicRegistrationView(generics.ListCreateAPIView): serializer_class = ClinicSerializer queryset = Doctor_clinic.objects.all() permission_classes = (permissions.IsAuthenticated,)#token user can create How to give is_doctor permission ,only create task ??