Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF ListAPIView return manytomany value names instead of pk
I have a Post Model contains tags field that have ManyToManyField to categories Model, when i call REST ListAPIView all post tags returns in pk I have tried to override list function in ListAPIView and map all tags_names for every post but this takes a huge time and destroys the performance I hope/Believe there something built in for this case models.py class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=256) content = RichTextField() tags = models.ManyToManyField(Categories) def __str__(self): return self.title class Categories(models.Model): tag_name = models.CharField(max_length=256, unique=True) def __str__(self): return self.tag_name class Meta: ordering = ('tag_name',) unique_together = ('tag_name',) views.py from .models import Post from .serializers import NewPostSerializer, PostSerializer class NewPost(CreateAPIView): serializer_class = NewPostSerializer permission_classes = [IsAuthenticated, IsAdminUser] class PostList(ListAPIView): queryset = Post.objects.all() serializer_class = PostSerializer serializers.py class NewPostSerializer(ModelSerializer): class Meta: model = Post fields = ['title', 'content', 'tags'] read_only_fields = ['tags', 'author_id'] when i visit ListApiView link returned results would be like this: [ { "id": 30, "title": "post title test", "content": "lorem text", "author": 3, "tags": [ 8, # should be games 3 # should be action ] } ] -
How to get a value from html using checkbox into views.py?-Django
I am not sure how to receive dynamic values from checkbox I want to take the id of Service model which I already have in my django project. I have a form which will take the values from checkbox to views.py. I want to know what is the right way to use the checkbox. Is this the correct way? <td><input type='checkbox' name='services' value={{ service.id }} class='btn btn-primary' /></td> -
django admin have choice option in field depend on values in other field
I'm just starting out in Django, and am having trouble setting up a model on the admin side. Here is the situation. I have 12 centers, each with over 20 laboratories. I have a model class for publications. On the admin side, I want to be able to assign centers and laboratories to each publication. More than one center can be assigned to each publication, and within each center more that one laboratory could be assigned. But, I do not want the laboratory field to list all the possible laboratories because there are too many. I would like the list seen in the laboratory field to only display laboratories in the centers that are chosen in the center field (and ideally, if more than one center is chosen, there will be separate lists to choose from for each) Here are the models I have: class Publications(models.Model): center = models.ManyToManyField('Center') laboratory = models.ManyToManyField('Laboratory') class Center(models.Model): name = models.CharField(max_length=255) class Laboratory(models.Model): name = models.CharField(max_length=255) So, after making Admin classes (PublicationsAdmin(admin.ModelAdmin), CenterAdmin(admin.ModelAdmin), LaboratoryAdmin(admin.ModelAdmin)) and registering them in admin.py, I can go to the admin page and add the centers and the laboratories and then when adding publications, I can choose the center(s) and … -
Can't get user id from request in django rest framework?
I wrote an api using django rest framework(DRF) which uses SessionAuthentication for validating users. This is my whole code # project/settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'app', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ) } # app/models.py from django.db import models # Create your models here. class Item(models.Model): name = models.CharField(max_length=50) amount = models.FloatField() # app/serializers.py from rest_framework import serializers from .models import Item class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ('id','name', 'amount') # app/urls.py from django.urls import path from main import views urlpatterns = [ path('',views.ItemView.as_view(),name='view_list'), ] # app/views.py from .models import Item from .serializers import ItemSerializer from rest_framework.response import Response from rest_framework.views import APIView class ItemView(APIView): def get(self, request): items = Item.objects.all() items_serializer = ItemSerializer(items, many=True) return Response(items_serializer.data) def post(self,request): print(request.data) item_serializer = ItemSerializer(data=request.data) if item_serializer.is_valid(): return Response({'userid':request.user.id}) return Response({'error':'error'}) I then logged in to http://127.0.0.1:8000/admin with my username and password and I expected my post request of {name:"Steve",amount:10000} return a result similar to this { "userid": 3 } but its returning { "userid": null } How do we get user id from DRF request? -
Is there a way to know if an user owns a domain?
I'm developing a webapp(Django) that let users have an eshop just with a few clicks. I serve the shops under https://shopname.mydomain.es but then I give them the option to use a domain if they want. For example one of my users (user1) buys "happyuser.com" in a domain provider of his choice. Then I tell them to modify their DNS to point to my server. So far so good, everything works perfectly, I use Nginx to allow access from the connected domains and everything works correctly. Here comes my doubt. I use a middleware to detect the host, in this case "happyuser.com", I check a table in wich I have the relation between user and domain name. class UserDomain(models.Model): user = ForeingKey(...) domain = UrlField(...) Then I tell django to serve the correct shop. But what happens if another user (user2) also saves the domain "happyuser.com", how can I know wich user shop should I load?. I know is unlikely that this happens, but is there a way to prevent this problem? -
How to loop through a form object in django?
I want to loop through a form object in order to style the form as I wish. I'm not sure what I make wrong. I want the form to look exactly the same as before, after I integrate the form tags but it's not. this is the from class: class CreateUserForm(UserCreationForm): email = forms.EmailField(widget=forms.TextInput( attrs={'class': 'form-control form-control-user', 'id': 'exampleInputEmail', 'placeholder': 'Email Address'}), label='') username = forms.CharField(widget=forms.TextInput( attrs={'class': 'form-control form-control-user', 'id': 'exampleInputEmail', 'placeholder': 'Username'}), label='') password1 = forms.CharField(widget=forms.PasswordInput( attrs={'class': 'form-control form-control-user', 'id': 'exampleInputPassword', 'placeholder': 'Password'}), label='') password2 = forms.CharField(widget=forms.PasswordInput( attrs={'class': 'form-control form-control-user', 'id': 'exampleRepeatPassword', 'placeholder': 'Repeat Password'}), label='') class Meta: model = User fields = ['email', 'username', 'password1', 'password2'] html form before adding the forms tags: <form class="user" method="POST"> {% csrf_token %} <div class="form-group"> <input type="email" class="form-control form-control-user" id="exampleInputEmail" placeholder="Email Address"> </div> <div class="form-group"> <input type="email" class="form-control form-control-user" id="exampleInputEmail" placeholder="Username"> </div> <div class="form-group row"> <div class="col-sm-6 mb-3 mb-sm-0"> <input type="password" class="form-control form-control-user" id="exampleInputPassword" placeholder="Password"> </div> <div class="col-sm-6"> <input type="password" class="form-control form-control-user" id="exampleRepeatPassword" placeholder="Repeat Password"> </div> </div> <input type="submit" name="Register" class="btn btn-primary btn-user btn-block" value="Register Account"> <hr> <a href="#" class="btn btn-google btn-user btn-block"> <i class="fab fa-google fa-fw"></i> Register with Google </a> <a href="#" class="btn btn-facebook btn-user btn-block"> <i class="fab fa-facebook-f fa-fw"></i> Register … -
How to add an extra field for an existing model in case of many to many relationships in django
So I have a product Model which say looks like this : class ProductModel(models.Model): name = models.CharField(max_length=200) price = models.DecimalField(max_digits=6, decimal_places=2, null=True) and I also have a cart model which looks like this : class CartModel(models.Model): customer = models.ForeignKey(User, on_delete= models.CASCADE, related_name="cart") products = models.ManyToManyField(ProductModel) the thing is I want to add a quantity field to the product so the user can add multiple products from the same product in the cart But I only want it when the product is in a cart (I don't want to add it in the ProductModel) Instead I want to add it to the product fields in the many to many relationship. I've done a bit of research and most of the answers aren't clear enough on how I should be doing this. -
can any one tell me how i can get user after login
I am trying to create logs of users but I can't seem to get an error around request.user.is_authenticated. please ignore my bad knowlede as this is my first post here's my code for log view User = settings.AUTH_USER_MODEL class ObjectViewed(models.Model): user = models.ForeignKey( User, blank=True, null=True, on_delete=models.CASCADE) # content_type = models.ForeignKey( # ContentType, on_delete=models.SET_NULL, null=True) InputAndOutput = models.CharField( max_length=10000, blank=True, null=True) ip_address = models.CharField(max_length=120, blank=True, null=True) # content_object = GenericForeignKey('content_type', 'object_id') timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.InputAndOutput class Meta: db_table='analytics_objectviewed' ordering = ['-timestamp'] verbose_name = 'Object Viewed' verbose_name_plural = 'Objects Viewed' def object_viewed_receiver(sender, instance, request, *args, **kwargs): # c_type = ContentType.objects.get_for_model(sender) ip_address = None try: ip_address = get_client_ip(request) except: pass if request.user.is_authenticated: user = request.user new_view_instance = ObjectViewed.objects.create( user=request.user, # content_type=c_type, InputAndOutput=instance, ip_address=get_client_ip(request) ) -
Django CategoryView with multiple status
def CategoryView(request, cats): category_posts = Post.objects.filter(category__iexact=cats.replace('-',' '), status='1') return render(request, 'categories.html', {'cats':cats.title().replace('-',' '), 'category_posts':category_posts}) I have a function that let me view status 1, but now I need one that let me view 1 and 2 at the same time, tried some things but didn't work as expected. -
Run subprocess from inside Django app as root
I need to execute linux command from inside django app. The problem is that django app user is www-data and linux command creates files, so I get permission denied error. How to run subprocess.check_output(['some', 'command']) as root? -
how can I encrypt my Django rest framework response? [closed]
I have Django rest framework as Backend for multi-platform project (web, Ios, android), the connection is encrypted with HTTPS, my question is how can I encrypt the body of the response before sending it to the frontend? is there any library to use? any advices I would be grateful. -
Django password shows in Form Data (Post/Request)
Good evening, I would like to know if when you submit a POST request to Django with your credentials (username/email and password) is normal/save to have that info open in Form Data (dev tools google -> network -> url). Like that: It's possible to hide that info or at least encrypt? Many thanks in advance! -
Erro when duplicate an instance in django
I want to duplicate an instance of my django class. I saw in the documentation https://docs.djangoproject.com/en/3.1/topics/db/queries/#copying-model-instances that I have to set pk to None and save. But this is the result when I try to clone the instance s1 of Scenario: What should I do? -
Send email with Chart.js and Django
I generate data and create charts using Chart.js and Django. Everything works fine, but now I want to send these charts by email. So I have data like below. labels = ['City1', 'City2', 'City3'] data = [[3,5,8], [12,23,3], [9,1,14]] I created a Mail class which allows me to send an email with message and attachments, but I don't know how can I add chart from Chart.js. So, summarizing, I want to do something like below. def send_mail_witch_chart(): labels = ['City1', 'City2', 'City3'] data = [[3,5,8], [12,23,3], [9,1,14]] mail_body = "create chart from above data" mail = Mail() mail_with_chart = mail.prepare_mail('mail_title', mail_body) mail.send(mail_with_charts) So, could somebody help, how can I create mail_body to pass it to prepare_mail() function -
csrf_token error even when the token is included within the html file and settings.py also has csrf middleware included
Thanks for looking into this! I have this error popping up even if my User registration html file has the token in it. Also settings.py file does have django.middleware.csrf.CsrfViewMiddleware included within it. Error Message : "POST /register/ HTTP/1.1" 403 2513 Forbidden (CSRF token missing or incorrect.): /register/ My views.py file : from django.shortcuts import render from django.contrib.auth import login,authenticate # from django.contrib.auth import UserCreationForm #Gives error from django.contrib.auth.forms import UserCreationForm def register(response): if response.method=='POST': form = UserCreationForm(response.POST) if form.is_valid(): form.save() else: form = UserCreationForm() return render(response,'register/register.html',{'form':form}) register.html file : {% extends 'main/base.html' %} {% block title %} Create an account {% endblock %} {% block content %} <form class="form-group" method="POST"> {% csrf_token %} {{ form }} <button type="submit" class="btn btn-success">Register</button> </form> {% endblock %} -
Why do I get CSRF authentication error in Django in certain condition?
Okay, so this is a very weird issue I'm having. I have my Django project, and I tried to log in to admin page with my superuser account. I type in the username and password, and this is where the weird error occurs. After typing in the username, when I type password real quick and HIT ENTER right away, the page stays in the loading process. It keeps on loading in the same page for a while, and I hit the submit button again or hit refresh, I get the CSRF authentication error. And when I click on 'back' on my browser, I get the admin page safely logged in. I know it sounds weird. But when I type in the username and password and then CLICK the submit button instead of hitting enter right away, I get logged in without any issue. In short, it's like this: When I try to log in to the admin page, if I type password real quick and hit enter right away, the page does nothing but keep on loading. It loads like forever so if I hit refresh or click submit button again, I get the CSRF authentication error. But if I … -
Django: how to annotate a list of ids (as slug or string)
I have a many-to-many relationship such as: class SeriesCompletion(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL, related_name='completions',) series = models.ForeignKey( Series, blank=True, null=True, on_delete=models.SET_NULL, related_name='completions', ) which contain one record each time a user completes a series I'm trying to build a custom queryset (within a manager) which will annotate for the series model either a slug ("1-12-52-34") or a string ("1,12,52,34") which contain the ids of all the users which completed the series Basically, I want to do the same as following, but through the manager: user_who_completed_id_list = list(SeriesCompletion.objects.filter( series=obj).values_list('user__id', flat=True)) user_who_completed_ids = ','.join(map(str, user_who_completed_id_list)) user_who_completed_ids_slug = '-'.join(map(str, user_who_completed_id_list)) I been doing tons and tons of tests and of research on the web without any success. Could someone help me out? -
Is there a way to display all current entries to a model in order to save a many to many relationship in Django?
I have two tables called Product and Ticket, with a TicketProduct table between as a many-to-many relationship. When I load the page to create a new Ticket, I need to see every current entry in the Product table, along with an entry for a count value on each product, that will save into the TicketProduct table when I save the new Ticket. I am currently able to display the full information about the ticket using a ticket form, I am able to pass in product information, however, I have not been able to display a listing of all products with a text box that will allow me to enter the count, and save at one time. Right now, my form overwrites the text boxes in my for loop and returns only the last product. What do I need to change in order to display and save this data? Views.py def newTicket(request): if request.method == 'POST': ticketForm = TicketForm(request.POST) if ticketForm.is_valid(): ticket = ticketForm.save(commit=False) ticketForm.user_id = request.user.id ticket = ticketForm.save() invoice_number = ticket.pk return redirect(str(invoice_number) + '/newTicketProduct') else: print(ticketForm.errors) else: ticketForm = TicketForm(initial={'tran_type': 'CH', 'user_id': request.user.id}) ticketForm.user_id = request.user.id model = Ticket return render(request, 'tickets/newTicket.html', {'ticketForm': ticketForm}) forms.py class TicketForm(forms.ModelForm): class … -
Use email created on cpanel - django
i try use email from cpanel in django but it show this error : App 634174 output: smtplib.SMTPSenderRefused: (501, b'<=?utf-8?q?Creative?=>: sender address must contain a domain', '=?utf-8?q?Creative?=') and this is my settings.py email setting : #MY EMAIL SETTING EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = False EMAIL_HOST = "mail.techpediaa.com" EMAIL_HOST_USER = "contact@techpediaa.com" EMAIL_HOST_PASSWORD = "mypass" EMAIL_PORT = 26 i'am using namecheap -
'PosixPath' object is not subscriptable
Using ogrinfo -so I've found the structure of the shapefile and based on this structure I've created a model: from django.contrib.gis.db import models class Villages(models.Model): . . . After that I've created the load.py as mentioned here inside the same directory of models.py: from pathlib import Path from django.contrib.gis.utils import LayerMapping from .models import Villages villages_mapping = { . . . } villages = Path(__file__).resolve().parent / 'gis' / 'villages.shp' def run(verbose=True): lm = LayerMapping(Villages, villages, villages_mapping, transform=False) lm.save(strict=True, verbose=verbose) Then, I try to use load.py: python3 manage.py shell > from geodata import load > load.run() But I see this strange error: Traceback (most recent call last): File "", line 1, in File "/home/maxdragonheart/DEV_FOLDER/Django/Enographiae/enographiae_dev/enographiae/geodata/load.py", line 32, in run lm = LayerMapping(Villages, villages, villages_mapping, transform=False) File "/home/maxdragonheart/DEV_FOLDER/Django/Enographiae/enographiae_dev/devenv/lib/python3.7/site-packages/django/contrib/gis/utils/layermapping.py", line 99, in init self.layer = self.ds[layer] TypeError: 'PosixPath' object is not subscriptable -
Need help in finding the count of an unique group of entries in django models
I have 3 models Customer, Services and Uses. The Uses model contains the customer_id and service_id(service) used by the customer. Now what I want is a list of count on the number of times each different service being used by the customer. For example if services say pool and buffet is being used once and twice i want the answer to be [1,2]. I don't want the count on distinct services used rather i want the count on each particular service. Here are my models class Customer(models.Model): firstname = models.CharField(max_length=15) lastname = models.CharField(max_length=15) #other attributes class Services(models.Model): service_name = models.CharField(max_length=15) price = models.IntegerField() class Uses(models.Model): customer = models.ForeignKey(Customer,on_delete=CASCADE) service_id = models.ForeignKey(Services,on_delete=CASCADE) time_used = models.TimeField(default=timezone.localtime()) This is what I have got which returns the distinct services used. count=Uses.objects.filter(customer_id=customer).values('customer_id','service_id').distinct().count() Need some help please to modify it. -
Page Transition using CSS JS (Vanilla) and Django does not work perfectly
I want to make my own transition animation using Vanilla JS in django Framework But I got some issue the URL page is 127.0.0.1:8080/foo/bar/undefined My CSS .my-transition{ position: fixed; width: 0; left: 50%; top: 0; bottom: 0; right: 0; z-index: 123; background-color: #2C4C3B; transition: 0.5s ease-out; } .my-transition.is-active{ width: 100%; left: 0; } in my JS window.onload = () => { const myTransition = document.querySelector('.transition'); const link = document.querySelectorAll('.anchor-load') setTimeout(() => { myTransition.classList.remove('is-active'); }, 500); for(let i = 0; i < link.length; i++){ const anchor = link[i]; anchor.addEventListener('click', e => { myTransition.classList.add('is-active'); let target = e.target.href; setTimeout(()=>{ window.location.href = target; }, 500); e.preventDefault(); }); } } My HTML template <div class="transition my-transition is-active"></div> ... <ul> <li> <a href="{% url 'home' %}" class="anchor-load">Go to Home</a> </li> <li> <a href="{% url 'about' %}" class="anchor-load">Go to About</a> </li> <li> <a href="{% url 'contact' %}" class="anchor-load">Go to Hell</a> </li> </ul> when I use this code the page is work perfectly But I want to make UX UI more attractive by adding some tag like img or span or div inside the anchor tag for ex. <ul> <li> <a href="{% url 'home' %}" class="anchor-load"> <span> Go to Home </span> </a> </li> <li> <a href="{% url … -
Django new field "JSONField" error - Column does not exist
I created a dummy project just to test the new field JSONField of Django but the column doesn't not appear to be created (I am using Postgresql). class Author(models.Model): name = models.CharField(max_length=50) description = models.TextField() slug = models.SlugField() details = models.JSONField() class Meta: verbose_name = "Author" def __str__(self): return self.name If i go to the database, the column is not created -- screenshot When i go to the admin view page of the table Author i get the following error -- screenshot The error in the admin panel is understandable: you cannot view a column that does not exist. Do you guys have the same error? I can't find this error with JSONField anywhere. Thanks Note: This is my first post. -
DateField filter date range in Django_Filter
Does anybody knows how to apply filter date range using django_filter? I want to filter date range using django filter it is possible? filters.py from django.contrib.auth.models import User from .models import Person import django_filters class UserFilter(django_filters.FilterSet): class Meta: model = Person fields = ['province', 'municipality','barangay','classification','classification','category', 'type_payout','payroll_batch', 'batch_it','paid','paid_by' ] #I havent add date yet views.py def sample(request): datefrom = request.POST.get('datefrom', False) #value name from datefrom dateto request.POST.get('dateto', False) #value name from dateto user_list = Person.objects.all() sample_data = UserFilter(request.POST, queryset=user_list) format = {'benefeciaries':sample_data} return render(request, 'payroll.html', format) models.py class Person(models.Model): date_receive = models.DateField(null=True, blank=True) some other value ...... -
app.autodiscover_tasks() TypeError: autodiscover_tasks() missing 1 required positional argument: 'packages'
I am trying to use celery in my django app. But, I was getting an error, so I copied the code from the book I was following(Django 3 by example). Now, when I run the python manage.py makemigrations command, I get this error: app.autodiscover_tasks() TypeError: autodiscover_tasks() missing 1 required positional argument: 'packages' Here is my celery.py, where the error is: import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myshop.settings') app = Celery('myshop') app.config_from_object('django.conf:settings') app.autodiscover_tasks() What is the problem?