Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Troubles with saving UserCreationForm in Django
I have my registration view, that uses UserCreationForm. Here it is: def registration(request): if request.method == 'POST': form = UserCreationForm() if form.is_valid: user = form.save() login(request, user) return redirect('home') else: if request.user.is_authenticated: logout(request) form = UserCreationForm() context = {'form':form,} return render(request, "register.html",context) But somehow when I try to create new user, I get AttributeError, that says " 'UserCreationForm' object has no attribute 'cleaned_data'" even though I don't have any calls of cleaned_data whatsoever. I tried to create my custom registration form which used cleaned_data, but I threw this away and wiped my custom form from the project completely. Why could this happen? P.S. The line that causes problems according to my Django debug return is user = form.save() -
Django POST returns empty - DRF + recaptcha
I'm trying to make a POST request to Django and it arrives empty to the view. views.py from django.http import HttpResponse from rest_framework import generics, views class TESTViewSet(views.APIView): def post(self, request): st = f'test: {request.POST} - {request.data} ' s_obj = serializers.RecaptchaSerializer( data=request.data, context={"request": request} ) return HttpResponse(st) The purpose is to test recaptcha with django rest framework, but I haven't even got there yet. The issue is the request always arriving at the view empty of any info. The page renders renders "test: - " The template rendered in the page: <div class=""> test <form method="post" action="/api/test_recaptcha/"> {% csrf_token %} <label for="ntest">Select:</label> <select name="ntest" id="ntest"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <label for="stest">Text:</label><br> <input type="text" id="stest" name="stest" value=""><br> <script src='https://www.google.com/recaptcha/api.js'></script> <div class="g-recaptcha" data-sitekey="{MY CAPTCHA PUBLIC KEY}"></div> <button type="submit" class="btn btn-primary">Post</button> </form> </div> It renders what is in the view, so the route is ok. I inspected the browser request, and all the fields of the post request are filled, including the g-captcha. However when it arrives at the view it's empty. What am I missing? -
Django Query to Combine Multiple ArrayFields to one text string
I have an object model where Documents are long text files that can have Attachments and both sets of objects can also have spreadsheet-like Tables. Each table has a rectangular array with text. I want users to be able to search for a keyword across the table contents, but the results will be displayed by the main document (so instead of seeing each table that matches, you'll just see the document that has the most tables that match your query). Below you can see a test query I'm trying to run that in an ideal world would convert all of the table contents (across all attachments) to one long string, that I can then pass to a SearchHighlight to make the headline. For some reason, the test query returns the tables as different objects, rather than concatenated to one long string. I'm using a custom function that mimics the Postgres 13 StringAgg as I'm using Postgres 10. Thanks in advance for your help, let me know if I need to provide more information to replicate this. my models.py: class Document(AbstractDocument): tables = GenericRelation(Table) class Attachment(AbstractDocument): tables_new = GenericRelation(Table) main_document = ForeignKey(Document, on_delete=CASCADE, related_name="attachments") class Table(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id … -
What does *args and **kwargs do in Django?
I was following a Django tutorial when I came upon the following code: def index(*args, **kwargs): return HttpResponse("<h1>Hello World</h1>") The instructor did not really explain what *args and **kwargs were, and it confused me. Can someone please explain what this does in the simplest terms? I'm pretty good with Python but I've never heard of this before. -
How to get Object value Django
I want get member object value 1.models.py from django.db import models class Member(models.Model): pID = models.CharField(max_length=6, primary_key=True, null=False) pChName = models.CharField(max_length=20,null=False) pBirth = models.CharField(max_length=10,null=False) pMobile = models.CharField(max_length=10,null=False) pLineID = models.CharField(max_length=20,null=True) pTeam = models.CharField(max_length=20,null=True) pAccount = models.CharField(max_length=20,null=False) pPassword = models.CharField(max_length=20,null=False) class Meta: db_table = 'members' fields = '__all__' 2.views.py def register(request): try: if request.method == "POST": member = Member(request.body.decode('utf-8')) print(member) except Exception as e: print(e) return redirect('/') return render(request, 'register.html') 3.Log Member object (csrfmiddlewaretoken=xLnhz9mX3aYVCRgakvcbPokrnbNjhiYG6NW9Ocf0GkfzfGZWBUdA2Bn6rNTOzKBP&pChName=1&pBitrh=2&pMobile=3&pLineID=4&pAccount=5&pPassword=6&pTeam=A) I want get member object value -
Use django permission system without Django Users
I want to build an application similar to jitsi. So people can join rooms (django channels) without registration or log in. Although this should be optionally supported. In a room I need "Users". These have a name and permissions. For instance the first joined should be in an "admin group" and be allowed to kick others users. So my idea was to create a User for each "websocket connection" and assoziate that with the room. I therefore made my own Django User. class RoomUser(AbstractBaseUser, PermissionsMixin): """ A custom user model for rooms to allow using built in permission handling """ channelName = models.CharField( max_length=255, help_text="Reply channel for connection that is present" ) userName = models.CharField( max_length=255, help_text="Free choosen user name" ) USERNAME_FIELD = 'channelName' REQUIRED_FIELDS = ['userName'] objects = RoomUserManager() def __str__(self): return self.channelName The thing is that I get these error messages auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'UserManage.groups'. Basically, this is also what the docs say, I should set AUTH_USER_MODEL, so it replaced the django user with my custom user. But this is not what I want. I don't want to replace the default user model (I might wanna add real login to … -
Views Count wont increase by 1
Model: @python_2_unicode_compatible class Post(models.Model): description = models.CharField(max_length=255, blank=True) pic = models.ImageField(upload_to='path/to/img') date_posted = models.DateTimeField(default=timezone.now) user_name = models.ForeignKey(User, on_delete=models.CASCADE) tags = models.CharField(max_length=100, blank=True) hit_count_generic = GenericRelation(HitCount, object_id_field='object_pk', related_query_name='hit_count_generic_relation') def __str__(self): return self.description def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) return super(Post, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) views.py: class UserPostListView(LoginRequiredMixin, ListView): model = Post template_name = 'feed/user_posts.html' context_object_name = 'posts' paginate_by = 10 def get_context_data(self, **kwargs): context = super(UserPostListView, self).get_context_data(**kwargs) user = get_object_or_404(User, username=self.kwargs.get('username')) liked = [i for i in Post.objects.filter(user_name=user) if Like.objects.filter(user = self.request.user, post=i)] context['liked_post'] = liked context.update({ 'popular_posts': Post.objects.order_by('-hit_count_generic__hits')[:3], }) return context def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.all().order_by('-date_posted') urls.py: path('post/<int:pk>/', views.post_detail, name='post-detail'), In my django template view: <p class="text-muted">Views: {% get_hit_count for post %}</p> I am getting Views:0 Where is the problem? -
Couldn't integrate a CSS file into my project
I would like to connect my layout.html file with a CSS file so that every other page extending my layout.html has access to this CSS file. That is the code: layout.html <!DOCTYPE html> <html lang="de"> <head> <title>Aufgabenzettel</title> <link rel="stylesheet" href="/aufgabenzettel/static/css/main.css"> </head> <body> {% block body %} {% endblock %} </body> </html> index.html {% extends "aufgabenzettel/layout.html" %} {% block body %} <h1>Meine Aufgaben</h1> {% endblock %} main.css h1 { color: aqua; } The href in layout.html is probably correct bacause I can be redirected to it in VS via ctrl + click. However, the h1 in index.html still appears in black instead of aqua... What am I doing wrong? I appreciate every kind of help! -
How to debug database connections pool in django
I'm using Django 3.1.5 with multi-threading and the default database is a PostgreSQL database and the problem is that for some reason when I keep the Django server running for minutes, the database server starts showing errors that no remaining connections available. In order to debug this problem and find out what's creating new database connections without closing old ones, I need a way to list all database connections, active and IDLE along with any possible details. So, how do I access such information in runtime? -
Django filter objects id and search for the full name in User model
I have a problem of solving this for the whole day and can't get it right. Please someone help me... book_obj = Book.objects.filter(status_sold=True).order_by('-date_sold') result will be something like this: id = 2 title = 'bla bla bla bla...' author = 3 ---> id from the User model (not a foreign key) status_sold = True date_sold = '2021-05-10' I want to view that data in the template, but the author I want to display the name instead of number 3 as an id of the author. How to solve this ? author_name = User.objects.get(id= ???????? ) so I can use {{ author_name.get_full_name }} later in the template Thx in advanced.... -
How to use model field in it's serializer
I would like to have my own error messages, which I've implemented in serializer like this: class TransactionsValuesSerializer(serializers.ModelSerializer): class Meta: model = Translations fields = ('id', 'value') extra_kwargs = {"value": {"error_messages": {"blank": f"Error"}}} It's model class Translations(models.Model): class Meta: db_table = 'merchants__translations' value = models.TextField() key = models.ForeignKey( TranslationsKeys, on_delete=models.CASCADE, related_name='translations' ) translation_language = models.ForeignKey( TranslationLanguages, on_delete=models.CASCADE, related_name='translations' ) Now, if user do not enter some of the fields for translations, it will show error message 'Error'. Image Is there a way to output error message like 'Error in {key}'? -
Filter database models based on input in form
I have the following models and a form in my Django app. These are the relevant snippets of my code. models.py C = 'C' I = 'I' A = 'A' CIA_CATEGORIES = ( (C, 'Confidentiality'), (I, 'Integrity'), (A, 'Availability') ) class security_incident(models.Model): asset = models.CharField(max_length=200) actor = models.CharField(max_length=200) action = models.CharField(max_length=200, primary_key=True) cia = models.CharField(max_length=9, choices=CIA_CATEGORIES, default=C) def __str__(self): return self.asset class defense_mechanism(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class attack(models.Model): attack_description = models.CharField(max_length=100) defense_mechanism = models.ManyToManyField(defense_mechanism) action = models.ForeignKey(security_incident, on_delete=models.CASCADE) def __str__(self): return self.attack_description form.py #Form to enter goal of attack-defense-tree class GoalForm(forms.Form): goal = forms.CharField(label='Goal of attack-defense-tree', max_length=100) categories = forms.MultipleChoiceField(choices='CIA_CATEGORIES', widget=CheckboxInput) Based on the input of the form (Goal and chosen categories) the database models should be filtered. If GOAL input(assuming goal form input = Database) matches an asset in security_incident model (security incident asset =Database) and category(or categories) have been chosen, the filter view should list all security incidents with related attacks and defense mechanisms for the goal/asset. The output should be something like this: generate.html <form method="POST" class="post-form">{% csrf_token %} {{ form.as_p }} <button type="submit" class="search btn btn-default">Search</button> </form> <div> {% for security_incident in filter.qs %} <h2>Form input: Goal</h2> <ul> <li>cia_category1</li> <ul> <li> {{ … -
Django Crispy Forms two columns in view.py
I have a form in my views.py with fields I have created in models.py. I would like to put 2 fields, 'subject' and 'rn_number' next to each other, like two columns in 1 row. How can I do that? It would be great if I could do it in my 'class PostCreateView'. I use crispy_forms. class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title', 'content_don', 'subject', 'rn_number'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) -
Django ORM, filter data from 3 different table
there are 3 models, how to form a request to retrieve all LocationCompany with a specific city or sector, + DomainService domain + Service service_type, name name = models.CharField(max_length=20, blank=True, null=True) service_type = models.ForeignKey(Service_type, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=0) slug = models.SlugField(max_length=30) class DomainService(models.Model): domain = models.CharField(max_length=30) sercices = models.ManyToManyField(Service, blank=True) title = models.CharField(max_length=200, blank=True) short_description = models.CharField(max_length=500, blank=True) long_description = models.CharField(max_length=1000, blank=True) specialization = models.ForeignKey(SpecializationService, on_delete=models.SET_NULL, blank=True, null=True) slug = models.SlugField(max_length=30) class LocationCompany(models.Model): company = models.ForeignKey(MyUser, on_delete=models.CASCADE, blank=True, null=True) doctors = models.ManyToManyField(MyUser, blank=True, related_name='company_doctors') domain = models.ManyToManyField(DomainService, blank=True) city = models.CharField(max_length=30) sector = models.CharField(max_length=30, blank=True, null=True) street = models.CharField(max_length=30, blank=True, null=True) google_maps_link = models.CharField(max_length=500, blank=True, null=True) slug = models.SlugField(max_length=30) slug_sector = models.SlugField(max_length=30)``` -
How do i update an array of objects inside an array
res[question.question_id]["question_parts"].append( { "part_desc": question.part_desc, "part_guided_answer": [ { "part_answer_id": question.part_answer_id, "part_model_ans": question.part_model_ans, "part_answer_mark": question.part_answer_mark, } ], "part_total_marks": question.part_total_marks, } ) @require_http_methods(["POST"]) @login_required def create_part_question(request): req = json.loads(request.body) description = req["description"] question_parts = req["question_parts"] part_guided_answers=req["part_guided_answer"] question, created = models.Questions.objects.get_or_create( description=description, ) for question_part in question_parts: part , created = models.QuestionsPart.objects.get_or_create( question_id=question, part_desc=question_part["part_desc"], part_total_marks=question_part["part_total_marks"], ) for question_part in question_parts: for part_guided_answer in part_guided_answers: models.PartModelAnswer.objects.create( question_id=question, part_id = part, answer_mark= question_part[part_guided_answer["answer_mark"]], model_ans= question_part[part_guided_answer["answer_mark"]], ) return success({"res": True}) how do i add an array of objects inside the array of objects so what i am trying to show here is that in one question part there can be multiple guided answers so what im trying to do is to add add mulitple guided answers into one question part however so far only the part_desc and the part_total_marks has been added as well as the description, the part_guided_answer has not been added, is there a solution or a better way to do this -
DRF Parse array of objects in form data with images
What is the best possible way to parse nested array objects along with images in drf? I am passing data from React js application -
django-modeltranslation seems to be breaking admin search_fields
I am using django-modeltranslation for a few attributes on some of my models & it seems to be breaking the Django admin search (and therefore also breaking autocomplete_fields on other objects). For example, if I have translated attributes in search_fields: search_fields = ("display_id", "name",) I get the error: "Related Field got invalid lookup: icontains" But if I remove the translated field to just: search_fields = ("display_id",) It works fine. This is using TranslationAdmin from modeltranslation.admin which per the docs "does some funky patching on all your models registered for translation" so I don't know what I am forgetting. -
How do i start the server in django?
When I type manage.py runserver in the shell, there only opens PyCharm, but I need to start the server of course. Why is this happening? -
Django mysql database display data from more than one table in a for loop in template problem
I have a old league web site php script with mysql database from 2006. This script not running depends to old php and mysql versions. Thats why I tried to get data from mysql database using django but I have a problem with match listing page. At database there is a table for league matches. I can fetch data and listing from using django template system like this : models.py class LeagueMatch(models.Model): objects = None idm = models.AutoField(primary_key=True) league = models.IntegerField() ids = models.PositiveIntegerField() judge = models.PositiveIntegerField() date = models.IntegerField() idg = models.PositiveIntegerField(blank=True, null=True) pos = models.IntegerField(blank=True, null=True) rnd = models.PositiveIntegerField(blank=True, null=True) idc1 = models.IntegerField() idc2 = models.IntegerField() type = models.CharField(max_length=20, blank=True, null=True) idpt = models.PositiveSmallIntegerField() points1 = models.IntegerField() points2 = models.IntegerField() frags1 = models.SmallIntegerField() frags2 = models.SmallIntegerField() win1 = models.PositiveIntegerField() draw = models.PositiveIntegerField() win2 = models.PositiveIntegerField() maps = models.CharField(max_length=70) scores = models.CharField(max_length=70) descr = models.TextField() server = models.CharField(max_length=30) views.py def all_matches(request): match_list = LeagueMatch.objects.all() return render(request, 'home_match.html', {'match_list': match_list}) {% for match in match_list reversed %} {% if match.league == 1 %} <div class="card" > <div class="card-body"> <h5 class="card-title"><a href="{% url 'match-detail' match.pk %}"> Match No {{ match.idm }} - Team A ({{ match.idc1 }}) vs Team B ({{ … -
Django: Toggle active users
here in this project, i want to show the active bar when admin is logged in and show blue color and when any other user is logged in, i want to show the active bar on it and others on red color when the users are not active. This is my html <div class="card-body table-responsive p-0"> <table class="table table-hover text-nowrap" id="rooms"> <thead> <tr> <th>SN</th> <th>Users</th> <th>Email</th> <th>Status</th> <th>Action</th> </tr> </thead> <tbody> {% for user in object_list %} <tr> <td>{{forloop.counter}}</td> <td>{{user.username }}</td> <td>{{user.email}}</td> <td> <label class="switch"> <input type="checkbox"> <span class="slider round"></span> </label> </td> <td> <span ><a class="btn btn-info mr-2" href="{% url 'dashboard:passwordreset' %}" ><i class="fa fa-edit m-1" aria-hidden="true" ></i>Reset Password</a ></span> </td> </tr> {% endfor %} </tbody> </table> </div> </div> Here I want to show green when admin is logged in and other active when other user is logged in -
DRF - filtering / customizing options in PUT request
I already tried to find some answers (#1) - with very little success. I want to filter the items the DRF api page returns in the PUT options: lets assume a simple model: class Product(models.Model): name = models.CharField(max_length = 10, default = '') user = models.ForeignKey(User, on_delete = models.CASCADE) class Price(models.Model): amt = models.PositiveIntegerField(default = 0) product = models.ForeignKey(Product, on_delete = models.CASCADE) so every product is linked to a user in the following way: Product | User ---------------- four | user2 three | user1 two | admin one | admin If I now define a ViewSet: class PriceViewSet(viewsets.ViewSet): serializer_class = PriceSerializer http_method_names = ['get', 'put', 'head'] def get_queryset(self): prods = Product.objects.filter(user = self.request.user) return Price.objects.filter(product__in = prods) def list(self, request): results = PriceSerializer(data = self.get_queryset(), many = True) results.is_valid() return Response(data = results.data) def put(self, request): prod = Product.objects.get(id = request.data["product"]) price = Price.objects.get(product = prod) price.amt = request.data["amt"] price.save() return Response(data = "OK") I see the following result (logged in as admin): Why is the user able to even see product three & four (not owned by admin, not in the get_queryset)? How can I filter them for the PUT dropdown? PriceSerializer for completeness sake: class PriceSerializer(serializers.ModelSerializer): class Meta: … -
Django: How to get most recent object from different model?
I m trying to display following output in which Cylinder, Issue & Return are different model, the view I m expecting is cylinder table, where only recently created entries of issue and return is appearing , For example : cylinderId=100 having two entries in issue table and return table but in cylinder table only the recently created is appearing which is :- cyId | createdAt | issuedDate | username | ReturnDate 100 | 5may,13:00| 6may,14:00 | anyone | 7may,15:00 Here is the view i m expecting:- for this result what should i do? Help please :) -
Passing parameter to form action in django?
Template : <form action="/wiki/{{ title }}/" method="post"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> And,views : def TitlePage(request, title): if request.method == "POST": title = request.POST.get('q') return render(request, "encyclopedia/titlepage.html", { "title" : title, "getentry": util.get_entry(title) }) URL : path("<str:title>/", views.TitlePage, name='titlepage') But when we submit the form, {{ title }} is not translated and url directs to /wiki// Are parameters not allowed in form actions? If its allowed then why is it not working here? Thanks. -
Error while implementing django tutorial - QuerySet is empty
Can someone explain how to manually enter data in "Choice" table? I am following the django tutorial and my QuerySet is empty like yugal sinha has mentioned here: A solution without an explanation How can I fix this issue? Thank you in advance -
Django static css wont Load
using {%static '' %} wont' work enter image description here already use + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) load template settingenter image description here