Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Populating ManyToManyField getting value from another field of same model
Very easy problem for Expert!! For last 7 days, i am trying to solve this problem and posted 5 times on Stackoverflow with the same problem and no one can help me in this case! Stackoverflow banned my an account too! Going through a horrible frustration now! this is my last post! This is My Models... from django.db import models class Person(models.Model): name = models.CharField(max_length=20) class Group(models.Model): admin = models.ForeignKey( Person, on_delete=models.CASCADE, related_name='group_admin' ) members = models.ManyToManyField( Person, related_name='group_members', blank=True ) def save(self, *args, **kwargs): self.members.add(self.admin) super(Group, self).save(*args, **kwargs) I want An admin of a group also will be a memebrs of the group! I will fill only admin field!! and the members field will be filled automatically and its value will be the admin of the groups! I mean, an Admin of a group also will be a memebers of the same group.. Simple requirement, is not it? But this simple problem can't solve anyone on stackoverflow, so much frustration it creates! When i try to create new group, it throws me this error: "<Group: Group object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used. but if i keep this method … -
How to populate dropdowns with ForeignKey in Django
I would like to populate the question and category selects according to the foreign key of the previous selects, but I am not getting either with AJAX or creating a form. What could you do? index.html <div class="row"> <div class="col-md-4"> <div class="form-group "> <select id="prova" class="form-control" name="prova"> <option value='' selected>Prova</option> {% for prova in provas %} <option value="{{ prova.idProva }}">{{ prova.tipoProva }} {{prova.anoProva}}</option> {% endfor %} </select> </div> </div> <div class="col-md-4"> <div class="form-group "> <select id="questao" class="form-control" name="questao"> <option value='' selected>Questão</option> {% for questao in questoes %} <option value="{{ questao.idQuestao }}">{{ questao.idQuestao }}</option> {% endfor %} </select> </div> </div> <div class="col-md-4"> <div class="form-group "> <select id="categoria" class="form-control" name="categoria"> <option value='' selected>Categoria</option> {% for categoria in categorias %} <option value="{{ categoria.idCategoria }}">{{ categoria.nomeCategoria }}</option> {% endfor %} </select> </div> </div> </div> views.py def index(request): prova = request.POST.get('prova') form = QuestaoProvaForm() provas = Prova.objects.all().order_by('idProva') questoes = Questao.objects.filter(idProva=prova).order_by('idProva') categorias = Categoria.objects.all().order_by('nomeCategoria') return render(request, 'polls/index.html',{'form':form,'prova':prova,'categorias':categorias,'questoes':questoes,'provas':provas}) -
Django form not saving despite POSTing ok
I have what should be a very simple django form and model. Far as I can tell everything is working as it should. In my web server logs I get a 200 POST OK message, however...the form never redirects as it should, and nothing is saved to the database. I'm unsure how to troubleshoot this as there doesn't seem to be anay clear error. Relevant section from my forms.py: class StoreItemForm(forms.ModelForm): class Meta: model = StoreItem fields = ('item_name', 'description', 'manufacturer', 'product_category', 'price', 'item_pic', 'height', 'width', 'length', 'items_in_stock') widgets = { 'item_name' : forms.TextInput(attrs = {'class': 'sizefull s-text7 p-l-22 p-r-22', 'placeholder': 'Item Name'}), 'description' : forms.TextInput(attrs = {'class': 'sizefull s-text7 p-l-22 p-r-22', 'placeholder': 'Description'}), 'manufacturer' : forms.TextInput(attrs = {'class': 'sizefull s-text7 p-l-22 p-r-22', 'placeholder': 'Manufacturer'}), 'price' : forms.TextInput(attrs = {'class': 'sizefull s-text7 p-l-22 p-r-22', 'placeholder': 'Price'}), 'height' : forms.TextInput(attrs = {'class': 'sizefull s-text7 p-l-22 p-r-22', 'placeholder': 'Height'}), 'width' : forms.TextInput(attrs = {'class': 'sizefull s-text7 p-l-22 p-r-22', 'placeholder': 'Width'}), 'length' : forms.Textarea(attrs={'class': 'sizefull s-text7 p-l-22 p-r-22', 'placeholder': 'Length'}), 'items_in_stock' : forms.TextInput(attrs = {'class': 'sizefull s-text7 p-l-22 p-r-22', 'placeholder': 'Quantity'}), } views.py: def additems(request): item_name = request.POST.get('item_name', False) description = request.POST.get('description', False) manufacturer = request.POST.get('manufacturer', False) product_category = request.POST.get('product_category', False) price = … -
how to select values from joined table?
I have two models, class model_1(models.Model): id = models.IntegerField(primary_key=True) tableName = models.CharField(max_length=20, default=None) class Meta: db_table = "table1" class model_2(models.Model): id = models.IntegerField(primary_key=True) tableId = models.ForeignKey(model_1, on_delete=models.CASCADE, db_column='tableId') class Meta: db_table = "table2" i am performing, queryset = model_2.objects.select_related('tableId').values('tableName').annotate(tcount=Count('tableId')) i want the following query select table1.tableName, count(table2.tableId) from table2 INNER JOIN `table1` ON (`table1`.`id` = `table2`.`tableId`) group by table2.tableId; but its giving me, django.core.exceptions.FieldError: Cannot resolve keyword 'tableName' into field. Choices are: tableId, id Thank you for your suggestions -
solr server stops indexing after some records
I have solr installed on AWS cloud, which is not able to complete my indexing. I have similar DB and solr on my local system where indexing runs fine and I can search all data. I have monitored memory consumption , heap size on AWS while indexing is running. Nothing seems unusual. python manage.py rebuild_index --noinput -b 1000 --workers 4 This command shows that 168252 records will be indexed while indexing stops at 164252 and it never completes. On local it completes all records indexing. What is the reason for this unusual behaviour ? -
Inline action with no object instance in Django Admin
I am having troubles with working with GenericTabularInline in my django app. The case is: I have some object called Status which has relation to some Property (ForeignKey). I would like to have an additional actions on that Status object in Property change form. I am using inline_actions library to create custom actions for Status object. The struggle is when I try to render that Inline instance if there is no Status object attached to my Property. Is there any way I can override my custom actions to render even if there is no Status object attached to my Property? Here is my Inline code: class AbstractPropertyCheckInline(InlineActionsMixin, GenericTabularInline): model = Status readonly_fields = ('status_type', 'last_check', 'additional_message') extra = 0 inline_actions = ['revalidate'] def revalidate(self, request, obj, parent_obj=None): # My revalidation code What revalidate does is that it creates a Status object and attaches it to the Property if such doesn't exist. I would like to trigger such behavior from within admin page -
How to display data in the instance to which I want to edit?
I want to edit the information in an instance of a crud, but at the time of doing so, it does not show me the information, which I had previously put in the create view and I do not understand how to show it, I have tried with the arguments 'form': form.cleane_data , 'form': form, but still does not show me the data that is in the fields, but that can be previously seen in a list view, which I have in the home of the application. this is my funtion in views.py def update_permisos(request, pk): if request.method == 'POST' and request.is_ajax(): form = permiForm(request.POST, instance=request.user) if form.is_valid(): permiso = form.save(commit=False) permiso.usuario = request.user permiso.save() permiso.usuario.status = request.POST['status':'Aceptado'] permiso.usuario.d_pendientes = request.POST['d_pendientes']#valores, que van al campo permiso.usuario.h_pendientes = request.POST['h_pendientes']#valores, que van al campo permiso.usuario.save() return JsonResponse({'status':'true', 'msg':'Datos procesados correctamente'})#retornando JSon en jsConsole else: return JsonResponse({'status':'false', 'msg':'Datos procesados incorrectamente'})#retornando respuesta en jsConsole else: form = permiForm(instance=request.user) args = {'form':form.data} return render(request, 'plantillas/permisos.html', args) this is my forms.py forms.py class permiForm(forms.ModelForm): class Meta: model = permiso fields = [ 'disponer', 'razon', 'periodo_i', 'periodo_f', 'dias_disponer', 'horas_disponer', ] if somebody, want see some other part of me code, tell me and i post it -
Filter permission list and show what is necessary
As you know, Django gives you a list of default permissions. by default those authentication permissions have 'auth', 'conttentypes', 'sessions' and I don't want those permissions in my opinion. where I customize the code so that this doesn't happen ... If someone helped me, it would be useful. The image shows these permissions that I do not want to be displayed. -
Django elasticsearch not displaying data
I have created the following document using django-elasticsearch-dsl @skill.doc_type class SkillDocument(DocType): class Meta: model = data_Skills fields = { 'SKILL_ID', 'SKILL_NAME', 'DESCRIPTION', } This is my Consultant and consultant skill model class data_Consultant(models.Model): CONSULTANT_ID=models.AutoField(primary_key=True) FIRST_NAME=models.CharField(max_length=50) LAST_NAME=models.CharField(max_length=50) EMAIL=models.CharField(max_length=255) CONSULTANT_GRADE=models.CharField(max_length=50) class data_ConsultantSkills(models.Model): SKILL_LEVEL_SCORE=models.IntegerField() SKILL_ID=models.ForeignKey(data_Skills, on_delete=models.CASCADE,to_field='SKILL_ID') CONSULTANT_ID=models.ForeignKey(data_Consultant, on_delete=models.CASCADE, to_field='CONSULTANT_ID') And have the following views. I am currently trying to match the skill name, and in that results, filter out consultants that have that particular skill if choice == "Skillset": //form selection skill= SkillDocument.search().query("match", SKILL_NAME=q) for item_s in skill: s_id = data_ConsultantSkills.objects.filter(SKILL_ID=item_s.SKILL_ID) if s_id.exists(): for item_c in s_id: cons_id = item_c.CONSULTANT_ID consultant_name= data_Consultant.objects.filter(CONSULTANT_ID=cons_id.CONSULTANT_ID) return render(request, 'search/Results.html', {'consultant_name':consultant_name}) else: return render(request,'search/Results.html') And the following is my html {% for item in consultant_name %} <tr><th> {{item.FIRST_NAME}} {{item.LAST_NAME}} {{item.LAST_CLIENT}} </th></tr> <br> {% endfor %} My current problem is that it is only displaying one data (the earliest data added) instead of displaying multiple data. What do I need to do to change that? Thanks in advance! -
Python Django website not recognizing css changes
I am making a django website and I am loading in my css in the html as static. I am using to css files the first is for the bootstrap that i am using and the second on is my own css but the bootstrap variables are showing but not my own variables I have tried remaking the css document and changing from "class" to "id" html code: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Wedding planner - Dashboard</title> <link href="{% static 'css/main.css' %}" rel="stylesheet" /> <!-- Bootstrap --> <link href="{% static 'css/bootstrap-4.3.1.css' %}" rel="stylesheet" /> </head> <body> {% block content %} <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="{% url 'Home' %}">Wedding Planer</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" > <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#" >Home <span class="sr-only">(current)</span></a > </li> <li class="nav-item"> <a class="nav-link" href="#">About</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Plans</a> </li> </ul> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" > User </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> {% if user.is_authenticated%} <a class="dropdown-item" href="{% url 'logout' %}">Logout</a> {% else %} <a … -
ValueError: Unable to configure handler 'rotated_logs': in python 3.6?
$ python3 ./manage.py makemigrations Traceback (most recent call last): File "c:\python36\Lib\logging\config.py", line 558, in configure handler = self.configure_handler(handlers[name]) File "c:\python36\Lib\logging\config.py", line 731, in configure_handler result = factory(**kwargs) File "c:\python36\Lib\logging\handlers.py", line 150, in init BaseRotatingHandler.init(self, filename, mode, encoding, delay) File "c:\python36\Lib\logging\handlers.py", line 57, in init logging.FileHandler.init(self, filename, mode, encoding, delay) File "c:\python36\Lib\logging__init__.py", line 1025, in init StreamHandler.init(self, self._open()) File "c:\python36\Lib\logging__init__.py", line 1054, in _open return open(self.baseFilename, self.mode, encoding=self.encoding) FileNotFoundError: [Errno 2] No such file or directory: 'F:\tmp\fb_debug.log' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "./manage.py", line 22, in execute_from_command_line(sys.argv) File "F:\python\venv\lib\site-packages\django\core\management__init__.py", line 381, in execute_from_command_line utility.execute() File "F:\python\venv\lib\site-packages\django\core\management__init__.py", line 357, in execute django.setup() File "F:\python\venv\lib\site-packages\django__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "F:\python\venv\lib\site-packages\django\utils\log.py", line 76, in configure_logging logging_config_func(logging_settings) File "c:\python36\Lib\logging\config.py", line 795, in dictConfig dictConfigClass(config).configure() File "c:\python36\Lib\logging\config.py", line 566, in configure '%r: %s' % (name, e)) ValueError: Unable to configure handler 'rotated_logs': [Errno 2] No such file or directory: 'F:\tmp\fb_debug.log' -
Django countries full name value
Is there a way to get the full name of country in the database using Django-countries. My dropdown list shows the full country names but when submitted the country abbreviations are the values that appear in my database. Is there an argument to put in my model? I can’t find an example that shows this. country = CountryField(blank_label='(select country)') -
Django: Applying database migration on server start
I would like Django to automatically apply migrations when server starts. How to do it? -
invalid literal for int() with base 10: 'first'
I want to filter post list on the basis of category using django mptt. Here is my code. models.py class Post(models.Model): title = models.CharField(max_length=120) category = TreeForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE) content = models.TextField('Content') slug = models.SlugField() def __str__(self): return self.title class Category(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True, on_delete=models.CASCADE) slug = models.SlugField() class MPTTMeta: order_insertion_by = ['name'] class Meta: unique_together = (('parent', 'slug',)) verbose_name_plural = 'categories' def __str__(self): return self.name views.py class CategoryView(ListView): model = Post template_name = 'apps/category_view.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) post_list = Post.objects.filter(category=self.kwargs.get('category')) context['category_list'] = post_list return context And urls.py urlpatterns = [ path('category/<str:category>/', CategoryView.as_view(), name='category_filter'), ] Here every things is imported correctly. When i entered urls some things like below. http://localhost:8000/category/first/ I'm getting error as below shown in image. Am I missing somethings, Any help will be appreciated. -
Django bootstrap-pagination work with inherited templates?
Does "bootstrap-pagination" in django work with inherited template files? I have a situation like the following. I have a template file like so: *{% extends "shared/table.html" %}* *... some html stuff ... ....end of file ...* Then I have the table.html like so: *{% extends "shared/tablepage.html" %} {% load bootstrap_pagination %} <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" type="text/css" media="screen" title="no title" charset="utf-8"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/font-awesome.css" type="text/css" media="screen" title="no title" charset="utf-8"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.js"></script>* *...some html table here...* *{% bootstrap_paginate pagination_query range=10 show_prev_next="false" show_first_last="true" %}* end of file. I am doing something wrong here. But what is that? I can see the list of page links in the page. But all pages contain all the records. The views file is absolutely "traditional". It contains the necessary code and that code works with template files that are not inherited (or use inheritance). Thanks in advance. I would appreciate a quick response, but I understand that might not be possible. -
Translating urls Django
I'm using gettext_lazy as _ for translating urls in Django. My question is how can I translate only particular single string, for example: path(_('<int:document_id>/preview/<uuid:uuid_link>/') here i want to get only /preview/ for translation in my django.po file not the whole string? -
how to add maxlength attribute to some input field dynamically?
i am trying to add maxlength attribute to my html form dynamically but i cannot able to add. Initially i adden input field type dynamically and it runs but maxlength is not adding dynamically. can some one help me in this? this is my html input field code- <label for="field_type">Field Type</label> <select name="field_type" id="field_type"> <option value="text" >Char Field</option> <option value="email">Email Field</option> <option value="url">Url Field</option> <option value="number">Integer Field</option> <option value="checkbox">Boolean Field</option> </select> </div> field_type is my object of my model in which my value stores. class Field(models.Model): field_name = models.CharField(max_length=100, unique=True) field_type = models.CharField(max_length=50) max_length = models.IntegerField(default=None) is_required = models.BooleanField() def __str__(self): return self.field_name i tried this for maxlength attribute - <div class="col-lg-8 mb-20"> <br><br> <label for="maxlength">Field Length</label> <input name="max_length" id="maxlength"> </div> -
How to access .env file in jquery?
So I have django project with jquery for interactivity in frontend. I already have .env file to store database configuration to be used by django settings.py, but I need jquery to be able to access the .env file too. From what I read in dotenv documentation, I need to install the dotenv using npm or yarn. But I think jquery don't have/use npm? I am a newbie in javascript -
Case insensitive sort in django rest framework with mongoengine
Django already has a way to achieve this for RDBMS: MyModel.objects.order_by(Lower('myfield')) I'm using DRF with mongoengine but the above throws error: TypeError: 'Lower' object is not subscriptable I'm guessing this is a bug in the way order_by has been implemented in mongoengine. -
Populate table with database records
I am trying to populate html table from database, but I can't find a good solution for doing that. I hope this is not too broad question. I am scraping data about hotel bookings and it's prices and I want to display it nicely on the table. I am working on it for quite a while but I am still struggling, hopefully someone will be able to help me. The table result I am trying to get: The first column represents what time scraping was executed, and top shows for what dates booking is made(checkin date). And the rest would be prices. +--------+-------+-------+-------+-------+ | | 1Apr | 2Apr | 3Apr | 4Apr | +--------+-------+-------+-------+-------+ | 11am | 40(A) | 40(A) | 40(A) | 40(A) | | 1110am | 40(X) | 40(X) | 42(A) | 42(A) | | 1120am | | | | | +--------+-------+-------+-------+-------+ Main model is PriceDatum, where all the prices are stored and another important model for this table is RoomScans which stores the time when scan was made. models.py: class PriceDatum(models.Model): room_scan = models.ForeignKey(RoomScan,default=1, on_delete=models.CASCADE) room = models.ForeignKey(Room, on_delete=models.CASCADE) checkin = models.DateField(db_index=True, help_text="Check in date", null=True) checkout = models.DateField(db_index=True, help_text="checkout date", null=True) price = models.PositiveSmallIntegerField(help_text="Price in the … -
Is is possible to pass two kwargs in DRF viewsets?
I am trying to get pass two kwargs in urls pointing to a viewset which lists and retrieves accordingly. i have tried getting self.kwargs as in generic views so i followed up same process for viewset but couldnot succeed. router = routers.DefaultRouter() router.register('v1/outlet/<outlet_id>/stock/<stock_id>', StockViewSet, basename='stock') urlpatterns = \ [ path('api/', include(router.urls)) ] viewset class StockViewSet(viewsets.ViewSet): def list(self, request, pk=None ,*args, **kwargs): # outlet_id = self.kwargs['outlet_id'] outlet_stock = OutletStock.objects.filter(outlet=outlet_id) def retrieve(self,request,pk=None,id=None,*args, **kwargs): # outlet_id = self.kwargs['outlet_id'] # stock_id = self.kwargs['stock_id'] -
what are the issues if I change django app name?
I know there are questions regarding how to change django app name but none of them talk about what are the downstream effects of changing the name of django app. Is it possible to keep the old table and migration names ? -
How to apply join and group by together on tables in django ORM?
I have two models, class model_1(models.Model): id = models.IntegerField(primary_key=True) tableName = models.CharField(max_length=20, default=None) class Meta: db_table = "table1" class model_2(models.Model): id = models.IntegerField(primary_key=True) tableId = models.ForeignKey(model_1, on_delete=models.CASCADE, db_column='tableId') class Meta: db_table = "table2" i am performing, queryset = Leads.objects.select_related('tableId').annotate(tcount=Count('tableId')) which is giving me the result, SELECT `table2`.`id`, `table2`.`tableId`, COUNT(`table2`.`tableId`) AS `tcount`, `table1`.`id`, `table1`.`tableName` FROM `table2` INNER JOIN `table1` ON (`table2`.`tableId` = `table1`.`id`) GROUP BY `table2`.`id` ORDER BY NULL; this is applying group by on table2.id , but i have specified annotate on tableId, in my ORM query hence it should apply group by on table2.tableId what am i doing wrong here ? Thank you for your suggestions -
How to group by over related model count in Django ORM
Let's say I have the following models: class Conversation(Model): ... class Message(Model): conversation = models.ForeignKey(Conversation) The following code counts the number of messages for each conversation: Conversation.objects \ .filter(...) \ .annotate(size=Count("message")) \ .values("size") and returns a query set of {'size': 0}, {'size': 1}, {'size': 0}, {'size': 0} etc. But how do I aggregate over the conversation sizes? That is, obtaining a result something like this: (0, 3), (1, 1), where the first element in each pair is the conversation size and the second element is the number of conversations of this size? -
how to serializers django 3 related model and create instance
My Modes.py look like below they have 3 related models all three model connect with one to one field so I am trying to make one serializers for all 3 model, and I want to create instance of 3 model at a time because of they are connected with each other with one to one field I am able to do with 2 models can anyone help me thanks in advance. class UserProfile(models.Model): # some field telephone = models.CharField(max_length=12) class User(AbstractUser): username = None email = models.EmailField(_('email'), unique=True) first_name = models.CharField( _('first name'), max_length=250) last_name = models.CharField(_('last name'), max_length=250) profile = models.OneToOneField(UserProfile, on_delete=models.CASCADE, null=True) class Genre(MPTTModel): user = models.OneToOneField(User, on_delete=models.CASCADE) parent = TreeForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True, related_name='reporting_manager') serializers.py class UserProfileModifySerializer(ModelSerializer): class Meta: model = UserProfile fields = ['telephone'] class EmployeeCreateSerializer(ModelSerializer): profile = UserProfileModifySerializer() id = PrimaryKeyRelatedField(read_only=True) class Meta: model = User fields = [ 'id', 'email', 'first_name', 'last_name', 'profile', ] # def create(self, validated_data): # profile_data = validated_data.pop('profile') # instance_profile = UserProfile.objects.create(**profile_data) # instance_user = User(profile=instance_profile, **validated_data) # password = randomStringDigits() # instance_user.set_password(password) # instance_user.save() # return instance_user class GenreModifySerializer(ModelSerializer): user = EmployeeCreateSerializer() class Meta: model = Genre fields = ['user', 'parent'] def create(self, validated_data): user_data = validated_data.pop('user') instance_user = …