Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - edit both sides of a many-to-many relation with generic UpdateView
I have a question whether or not it is possible to use the generic UpdateView class to edit "both sides" of a many-to-many relationship. I have the following classes defined in models.py: class SomeCategory(models.Model): code = models.CharField(max_length=5) name = models.CharField(max_length=40) class SomeClass(models.Model): code = models.CharField(max_length=3, unique=True) name = models.CharField(max_length=30, unique=False) age = models.IntegerField(null=False) allowed_categories = models.ManyToManyField(SomeCategory) These are both dictionary type tables that store sets of configuration data for my application. To allow editing the dictionaries I use simple UpdateViews: class SomeClassUpdate(UpdateView): model = SomeClass template_name = 'admin/edit_class.html' fields = ['code', 'name', 'age', 'allowed_categories'] ordering = ['code'] This works fine, I get a nice multi-select and everything is perfect. However, I would like to have the possibility to edit the relationship from the side of the SomeCategory table, so I can choose which SomeClass elements are linked to a certain SomeCategory: class SomeCategoryUpdate(UpdateView): model = SomeCategory template_name = 'admin/edit_category.html' fields = ['code', 'name', ??????? ] ordering = ['code'] I have tried adding the related_name attribute to the SomeCategory model, but that did not work. Any ideas if this can be done without using a custom ModelForm? Key library versions: Django==1.11.8 psycopg2==2.7.4 PS: this is my very first question asked on … -
How to load CSS files to HTML file in Django...?
I'm learning Django framework.I tried to link my css file into html file in django but it not working. I use {% load staticfiles %} keyword also... I'm using Pycharm community IDE....how to solve this?What is the problem in this...??? This is the html file: Music/template/music/index.html {% load staticfiles %} <link rel="stylesheet" type="text/css" href=" {% static 'music/style.css' %} "/> {% if all_album %} <ul> {% for album in all_album %} <li><a href="{%url 'music:detail' album.id %}">{{album.title}}</a> </li> {% endfor %} </ul> {% endif %} This is CSS file: Music/static/style.css body{ background: white; } -
How to protected my django app by unreadable human source code?
How can I protected Django apps from readable ? I'll protected code on my server and the source on the server can not be unreadable by users.How to Minify, obfuscate, and compress Django source code ? -
How to get all fields in django rest framework which is defined as related name in a diffent model with foreign key?
Here is my models.py from __future__ import unicode_literals from django.db import models class User(models.Model): name = models.CharField(max_length=200) company_name = models.ForeignKey('Company',on_delete=models.CASCADE,related_name='user') def __str__(self): return self.name class Company(models.Model): name = models.CharField(max_length=200) phone_number = models.IntegerField(null=True,blank=True) def __str__(self): return self.name class Catalog(models.Model): name = models.CharField(max_length=200) no_of_pcs = models.IntegerField(null=True,blank=True) per_piece_price = models.DecimalField(null=True,blank=True,max_digits=10,decimal_places=2) company_name = models.ForeignKey(Company,on_delete=models.CASCADE,related_name='catalog') def __str__(self): return self.name here is my serializers.py from rest_framework import serializers from .models import * from django.db.models import Sum,Count class CatalogSerializer(serializers.ModelSerializer): total_pieces = serializers.SerializerMethodField() total_price = serializers.SerializerMethodField() company_name = serializers.CharField() class Meta: model = Catalog fields = ('name','no_of_pcs','per_piece_price','company_name','total_pieces','total_price') def get_total_pieces(self, obj): totalpieces = Catalog.objects.aggregate(total_pieces=Count('no_of_pcs')) return totalpieces["total_pieces"] def get_total_price(self, obj): totalprice = Catalog.objects.aggregate(total_price=Sum('per_piece_price')) return totalprice["total_price"] class UserSerializer(serializers.ModelSerializer): company_name = serializers.CharField() class Meta: model = User fields = '__all__' class CatalogData(serializers.ModelSerializer): class Meta: model = Catalog fields = ('name', 'no_of_pcs', 'per_piece_price') class CompanySerializer(serializers.ModelSerializer): catalog = CatalogData(many=True) user = UserSerializer(many=True) class Meta: model = Company fields = ('name', 'phone_number', 'catalog','user') here is my views.py from __future__ import unicode_literals from django.http import HttpResponse from .models import * import json from django.http import JsonResponse, HttpResponse from .serializers import * from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework import viewsets class CatalogView(viewsets.ModelViewSet): queryset = Catalog.objects.select_related('company_name') serializer_class = CatalogSerializer class … -
Caching objects inbetween tests using pytest-django
I am trying to speed up my unit tests by caching objects inbetween tests. I know that tests ought to be isolated from one another. But the act of creating my objects is expensive and there is no need to keep creating the same objects over-and-over again. Originally, I thought I could call a fixture from setup_class but apparently that doesn't work. So I have just written a simple function to call at the start of each test. This nearly works. However, the related objects are empty. Here is some code: models.py: class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, related_name="books") tests.py: import factory import pytest from faker import Faker from django.db import models from models import Book, Author fake = Faker() class AuthorFactory(factory.django.DjangoModelFactory): class Meta: model = Author name = factory.Faker('name') class BookFactory(factory.django.DjangoModelFactory): class Meta: model = Book title = factory.Faker('sentence') author = factory.SubFactory(AuthorFactory) def make_an_author(**kwargs): n_books = kwargs.pop("n_books", 10) author = AuthorFactory.create(**kwargs) for i in range(n_books): BookFactory.create(author=author) return author @pytest.mark.django_db class TestAuthor: N_AUTHORS = 10 cached_authors = [] def cache_authors(self, n_authors): current_n_authors = len(self.cached_authors) if current_n_authors < n_authors: self.cached_authors.extend( [ make_an_author(n_books=2) for i in range(current_n_authors, n_authors) ] ) def test_one(self, cache_authors): self.cache_authors(10) author … -
Django ORM: pre-filtering related fields inside a queryset
Imagine I have two models, A and B, which are defined (loosely) as class A(models.Model): a_flag = models.BooleanField() b = models.ForeignKey('B', ...) class B(models.Model): b_flag = models.BooleanField() I want to have a queryset of A's which have a_flag=True, and for these, I want further queries to a.b.filter(...) be kind of 'pre-filtered' with b_flag=True. Is there a way of doing this without redefining the RelatedManager of B (still seems like a hacky solution)? -
Django: Counting in a many "many-to-many" table schema
I want to calculate some stats in my django app. With this schema, class Rank(models.Model): rank_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) class Taxon(models.Model): taxon_id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) rank = models.ForeignKey(Rank) class Passport(models.Model): id: taxa: models.ManyToMany(Taxon, through='TaxonPassport') class Accession(models.Model): id: passports= models.ManyToManyField(Passport, through='AccessionPassport') I want to to calculate how many accessions are for each taxon_name rank conbination. This is the django query expression that I would use: queryset = Taxon.objects.filter(passport__accession__institute=self).distinct('passport__accession').values('name', 'rank__name').annotate(counts=Count('name')) But it throws a nonImplemented error: NotImplementedError: annotate() + distinct(fields) is not implemented. In orther to solve this I have made a rawSql query with a "Select from Select": Select "taxon_id", "taxon_name", "name", COUNT(*) as counts from ( SELECT DISTINCT "vavilov2_integration_accession"."accession_id", "vavilov2_integration_taxon"."taxon_id" as "taxon_id", "vavilov2_integration_taxon"."name" as "taxon_name", "vavilov2_integration_rank"."name" FROM "vavilov2_integration_taxon" INNER JOIN "vavilov2_integration_taxonpassport" ON ("vavilov2_integration_taxon"."taxon_id" = "vavilov2_integration_taxonpassport"."taxon_id") INNER JOIN "vavilov2_integration_passport" ON ("vavilov2_integration_taxonpassport"."passport_id" = "vavilov2_integration_passport"."passport_id") INNER JOIN "vavilov2_integration_accessionpassport" ON ("vavilov2_integration_passport"."passport_id" = "vavilov2_integration_accessionpassport"."passport_id") INNER JOIN "vavilov2_integration_accession" ON ("vavilov2_integration_accessionpassport"."accession_id" = "vavilov2_integration_accession"."accession_id") INNER JOIN "vavilov2_integration_rank" ON ("vavilov2_integration_taxon"."rank_id" = "vavilov2_integration_rank"."rank_id") WHERE "vavilov2_integration_accession"."institute_id" = 2) as TMP group BY "taxon_name", "name", "taxon_id" ; I am trying to convert this to a Django ORM expression but I don't know how. Any suggestion? Thanks in advance. -
Delete specific Row in Django
im pretty new to django and html and want to create a Customerportal where customers can manage their documents. My problem is that every row got its own delete button but whatever button i click it always delete the top row and not the button on the row i clicked. I think you only need to see the template to see the mistake because it deletes the 'Akte' but just not the right one. template: <table class="center" id="myTable" style="border:solid;border-color:white;padding-bottom:1%;padding-left:1%;margin-top:3%;border-radius:6px;width:50%"> <tr style="margin-left:30%;margin-right:30%;border:solid;border-color:white;padding-bottom:1%;padding-left:1%;margin-top:3%;border-radius:6px;color:white"> <th class="cell" onclick="sortTable(0)">Aktenbarcode</th> <th class="cell" onclick="sortTable(1)">Ersteller</th> <th class="cell" onclick="sortTable(2)">Startdatum</th> <th class="cell" onclick="sortTable(3)">Kundennummer</th> <th class="cell" onclick="sortTable(4)">Aktionen</th> </tr> {%for Akte in akte_list%} <tr> <td id="{{Akte.Aktenbarcode}}"class="cell">{{Akte.Aktenbarcode}}</td> <td class="cell">{{Akte.user}}</td> <td class="cell">{{Akte.Startdatum}}</td> <td class="cell">{{Akte.kundennr}}</td> <td class="cell"> <form action="{% url 'aktedelete' %}" method="post"> {% csrf_token %} <input class="btn btn-primary" type="submit" value="Status anzeigen"/> <input type="hidden" name="aktenbarcode" value="{{Akte.Aktenbarcode}}" /> <input type="hidden" name="mitglied" value="{{container}}"/> <input type="hidden" name="benutzer" value="{{request.user.username}}"/> <input type="hidden" name="status" value="{{status}}" /> {% if status == "O" %} <button class="btn btn-primary" data-toggle="modal" data-target="#myModal" type="button"> Akte entfernen</button> <!-- Modal --> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle" style="color:black">Akte: {{Akte.Aktenbarcode}}</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body" style="color:black"> Wollen Sie diese Akte unwiderruflich … -
Execute python script with same name in different directory
I have the following file structure: A: |_ a.py |_ b.py B: |_ a.py |_ b.py I want to dynamically execute either A/b.py or B/b.py. I am using the following code: path = '/home/username/test/' + module + '/' if path not in sys.path: sys.path.append(path) script = import_module(sub, 'Script') myClass = getattr(script, 'Script') run = myClass() Doing this, if I run B/b.py and then A/b.py, it will execute B/b.py instead of A/b.py. The first script to be run will be executed in the next round. I need help in making sure the file in the directory I want is run only. -
Searching wagtail images
I'm implementing a image rich webapp with wagtail and elasticsearch. To search for images I want to use elasticsearch and the built-in capabilities of wagtail to index and search for images. The images in wagtail are tagged and I want to use those tags to find images. The indexing of images already worked out of the box and now I'm strugling with searching for them. The challenge is that I want to search for text in tags. Wagtail provides a search() function on the object manager which can be used for searching: images = Image.objects.search("sometag") To restrict the search on a specific field, it is possible to do the following: images = Image.objects.search("sometag", fields=['title']) Now to restrict on the tag which is a defined as a related field for search: search_fields = CollectionMember.search_fields + [ index.SearchField('title', partial_match=True, boost=10), index.AutocompleteField('title'), index.FilterField('title'), index.RelatedFields('tags', [ index.SearchField('name', partial_match=True, boost=10), index.AutocompleteField('name'), ]), index.FilterField('uploaded_by_user'), ] I'd expect the search() function to work with either the 'tag' or 'tag.name' parameter: images = Image.objects.search("sometag", fields=['tags.name']) images = Image.objects.search("sometag", fields=['tags']) But I only get the following error: wagtail.search.backends.base.SearchFieldError: Cannot search with field "tags.name". Please add index.SearchField('tags.name') to Image.search_fields. or wagtail.search.backends.base.SearchFieldError: Cannot search with field "tags". Please add index.SearchField('tags') to … -
django-rest-swagger urls not getting mapped with swagger
I am trying to implement django-rest-swageer for documentation i have added the following in my root urls from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title="Swagger Docs") urlpatterns = [ url(r'^docs/',schema_view), ] when i am going to localhost/docs only getting this as output Swagger Logo swagger Logout You are logged in as: admin@*** Powered by Django REST Swagger -
Populating field values in django forms
I want to know the best way to assign a generated value for model field in a django form. Here is the code for what I need to implement the logic. Model: class Booking: number = models.CharField(max_length=8) category = models.CharField(max_length=2) ref = models.CharField(max_length=10) What I need to do is, store the combination of number + category in ref field when model is saved. I know there are two methods called save() and clean() available for this. But I'm not sure which one is the best to use. Thanks. -
Run a single pytest in django with the settings variable (pycharm)
When I try to run a single test in django I get: Requested settings, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() I know you can set in the configurations the variable DJANGO_SETTINGS_MODULE, but I would like to do that for all configurations when I run individual tests (I cannot insert the variable for each method...) Is there a proper global solution? I have the pytest.ini file in project root: [pytest] DJANGO_SETTINGS_MODULE = report.settings But this seems to work only when I run all the tests.. -
Creating objects inheriting from User with existing User in Django
I have my user models like this from django.contrib.auth.models import User class AUser(User): # some model properties class BUser(User): # some model properties Here AUser has different web interface and BUser has different web interface. If a user signup in AUser interface, I will create a user for him like this. auser = AUser.objects.create(username='abc', first_name='abc', last_name='cdf', email='abc@gmail.com') auser.set_password('asdf12345') Same thing I will do for creating account in BUser interface. As AUser and BUser inherit User model, they have a field user_ptr which is actually User object. The problem is If a user has already an account in AUser interface, then if he tries to login with same credentials in BUser interface, I will automatically create BUser object for him but with same credentials. Which means I will not create User object but I will attach a BUser object with existing User object. But I cannot find a way to create object like this. I tried to do it like this user = User.objects.get(id=123) buser = BUser.objects.create(user_ptr=user) But it try to create new User object with default values. How can I create a new BUser object with existing User object in this case? PS: Though it is not good idea to … -
Sharing database relations across micro-services with Django rest framework
I have two django REST API projects which I have decoupled them into micro services architecture, one of the services is an (SSO) that handles authentication (I'm using JWT token based authentication) and manage Users info and the other is a payroll service. The problem is the user has a relation to some model in payroll service. To be specific I have an Employee class in payroll service which has a user_id field. This is where I will add a user UUID which I will get from querying the SSO service. How do I share database across micro-services taking into consideration each service has its own database. -
make shared element on pages django
Hello I want to know how to make element like in soundcloud or spotify when you play music there is that element that stay the same even when you change page -
Default value and DeferredAttribute problem
I would like to set the default value in one form from another form. How to do it correctly ??? class def_val(models.Model): bnumber = models.CharField(max_length=100, blank=True) def __str__(self): return self.bumber class Panel(models.Model): barcode = models.CharField('Kod kreskowy', max_length=100, blank=True) producer = models.ForeignKey(PanelProducer, verbose_name='Producent', on_delete=models.CASCADE) size = models.ForeignKey(PanelSize, verbose_name='Rozmiar', on_delete=models.CASCADE) box_number = models.CharField(('Numer palety'), max_length=10, blank=True, default=def_val.bnumber) tested_by = models.ForeignKey(User, verbose_name='Osoba pakująca', related_name="Created_by", on_delete=models.CASCADE) test_date = models.DateTimeField(('Data pakowania'),default=datetime.now, blank=True) -
Multiple Nested Serializer
I have SectionInfo model which is related to Projects with ForeignKey and a Section2 model which is related to SectionInfo with OneToOneField. How can i access Section2 data direclty in Projects Serializer. models.py class Projects(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) p_name = models.CharField(max_length=100) p_name_full = models.CharField(max_length=150) p_creation_date = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True) class SectionInfo(models.Model): p_id = models.ForeignKey(Projects, on_delete=models.CASCADE, related_name='sec_info', db_column='p_id') s_name = models.CharField(max_length=200) s_type = models.CharField(max_length=200, db_column='type') s_length = models.IntegerField(null=True, blank=True) class Section2(models.Model): info_id = models.OneToOneField('rsa.SectionInfo', on_delete=models.CASCADE, related_name='sec_2', db_column='info_id') s_cbRestrictionEnd_1 = models.IntegerField(null=True, blank=True) s_cbReflector_1 = models.IntegerField(null=True, blank=True) serializer.py class ProjectListSerializer(ModelSerializer): sec_2 = Section2Serializer(many=True) class Meta: depth = 2 model = Projects fields = [ 'p_name', 'p_name_full', 'p_creation_date', 'sec_2', ] class Section2Serializer(ModelSerializer): sec_info = SectionInfoSerializer(read_only=True) class Meta: depth = 2 model = Section2 fields = [ 'sec_info', 'sec_ques', 's_cbRestrictionEnd_1', 's_cbReflector_1', ] class SectionInfoSerializer(ModelSerializer): class Meta: model = SectionInfo fields = [ 's_name', 's_type', 's_length', ] This shows the following error:- The serializer field might be named incorrectly and not match any attribute or key on the Projects instance. -
Django 4 unique constraint IntegrityError
I am building a parking app, and my issue is that i used 4 different constraints. My issue: if on 25th of Oct i have a P1 location booked from 9-17, i want it to be free for booking from 18-24. My models: from django.db import models from django.conf import settings from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ from datetime import datetime, timedelta, time from django.core.exceptions import NON_FIELD_ERRORS today = datetime.now().date() tomorrow = today + timedelta(1) now = datetime.now() l = now.hour m=int(now.strftime("%H")) class ParcareManager(models.Manager): def active(self, *args, **kwargs): return super(ParcareManager, self).filter(draft=False).filter(parking_on__lte=datetime.now()) class Parcare(models.Model): PARKING_PLOT = (('P1', 'Parking #1'), ('P2', 'Parking #2'),('P3', 'Parking #3')) user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True,null=True, default=1, on_delete=True) email=models.EmailField(blank=True, null=True) parking_on = models.DateField(auto_now=False, auto_now_add=False,blank=True, null=True, help_text='Alege data cand doresti sa vii in office',) parking_off = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True, help_text='Alege Data Plecarii') numar_masina = models.CharField(max_length=8, default="IF77WXV",blank=True, null=True, help_text='Introdu Numarul Masinii') location = models.CharField(max_length=3, blank=True, default="P1",null=True, choices=PARKING_PLOT, help_text='Alege Locul de Parcare Dorit') updated = models.DateTimeField(auto_now=True, auto_now_add=False,blank=True, null=True) timestamp=models.DateTimeField(auto_now=False, auto_now_add=True,blank=True, null=True) venire = models.TimeField(default=time(9, 00), auto_now=False,auto_now_add=False, help_text='Alege Ora Venirii') plecare = models.TimeField(default=time(18, 00), auto_now=False, auto_now_add=False, help_text='Alege Ora Plecarii') objects = ParcareManager() def __str__(self): return self.location + " | " + str(self.parking_on) + " | " + str(self.parking_off) … -
How do I make a button on a website that generates ovpn config specific on the information filled
So here is the example... Name: [Generate ovpn config button] and then what happens when someone click on the button is config file will appear with that specified name.I am still newb and working on a django website.I dont mind incorporating other language into the web other than python even tho im working with django.But if its possible to be done with python please do tell me how.Just tell me the key things what I should be having to do this.Not expecting straight feeding the code since I am still learning but its fine too. Ill just study the code then. -
Cannot delete element from django arrayfield
I am trying to delete an element from an arrayfield in notes model obj=notes.objects.get(id=n_id,related_to__contains=[c_id]) obj.related_to.remove(c_id) obj.save() where related to is the arrayfield related_to=ArrayField(models.IntegerField()) n_id is the note's id and c_id is contact's id. When i try to do this i am getting the error ValueError: list.remove(x): x not in list . I've checked and the c_id is in the arrayfield. What is wrong? -
Detect all tabs are closed for a particular browser and implement logout
I have logout user function at my backend which logs out user after 10 minutes of inactivity. I want to implement logout if all the tabs for the particular website is closed. One more scenario ,I want to implement is,if multiple tabs are opened for that particular site and anyone of it is active, the user should not log out. Any suggestions on how to achieve this ? -
How to achieve Right Join or left join between three tables without direct relation using Django rest serializer?
I have three SQL tables User_Group, Group, Post User_Group has foreign key from Group. And, Post also has foreign key from Group. Now, I want to get the data from Post table using Group_ids from the User_Group table "Select User_Group.group_id, Post.post_title, Post.post_by, Group.group_title From User_Group Inner Join Group ON User_Group.group_id = Group.group_id Inner Join Post ON Group.group_id = Post.group_id Where User_Group.user_id=1" How can i get the same result of this SQL Query from DJango rest Framework? -
Django Custom widget rendering
The General Problem Suppose you have a certain model class MyModel(models.Model): Name = models.CharField(max_length=64) And an accompaniying form you use for creation class CreateMyModelForm(forms.ModelForm): class Meta: model = MyModel fields = ['name'] In a normal situation, when the form is rendered in a template I usually loop over the fields in the template {%for field in form%} {{field}} {%endfor%} When custom styling is needed, I usually have to resort to placing my <div>s and <span>s in that loop, and specify the base widget and its attrs in the Meta subclass. Looking through the Django Documentation on the topic, I understand that it seems like I have to play with the Media subclass to make all the manipulation happen in the widgets property in the Meta, but I just can't wrap my head around it. Specific Problem Suppose I have a template where TextInput forms need to render as: <div class="form-group input-group"> <span class="input-group-addon">Name</span> <input type="text" name="name" class="form-control" placeholder="MyModel Name"> </div> How do I go about creating a widget so that I can get the same result by using: class CreateMyModelForm(forms.ModelForm): class Meta: model = MyModel fields = ['name'] widgets={'name':MyWidget(addon="Name",placeholder="MyModel Name")} I understand that the placeholder is something I can put … -
Specify search fields for some cases DRF
Let's say I have these fields for search in my ViewSet: search_fields = ('username', 'name', 'surname') When I want to search a user, I append URL with something like ?search=usertest. And it will search on 3 provided fields. Is there a way to specify a fild where to search for some custom cases, so that input will be searched only, for example, on name field?