Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django "Reverse for 'question_update' with keyword arguments '{'pk': ''}' not found."error
NoReverseMatch at /answer_update/1/16 Reverse for 'question_update' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['question\/(?P[0-9]+)\/update\/$'] I am trying to make a comment update function. But it doesn't work. Someone please help me out. urls.py path('answer_update/<int:qpk>/<int:apk>',views.answer_update, name='answer_update'), views.py def answer_update(request, qpk, apk): answer = get_object_or_404(Answer, pk=apk) question = get_object_or_404(Question, pk=qpk) if request.method == "POST": form = AnswerForm(request.POST, instance=answer) if form.is_vaild(): form.save() return redirect('detail_question', pk=apk) else: form = AnswerForm(instance = answer) return render(request, 'detail_question.html',{'form':form}) detail_question.html <div> <h1>Answer_list</h1> <div> {% for answer in answers %} <div> {% if answer.image %} <img src="{{ answer.image.url}}" height=200> {% endif %} <p> {{ answer.content }} </p> <p> {{ answer.author }} </p> {% if user == answer.author %} <a href="{% url 'answer_update' question.pk answer.pk %}">update</a> {% endif %} {% if user == answer.author %} <a href="{% url 'answer_remove' question.pk answer.pk %}">delete</a> {% endif %} {% if user == question.author and question.selected == False %} <a href="{% url 'select_question' question.pk answer.pk %}">select</a> {% endif %} <hr> </div> {% endfor %} </div> -
How to solve the error of Unknown field(s) (Id_card_number) specified for User?
I am trying to add new input field in users page in django admin, but it is showing me just email, password, confirm password fields. I want it to show Id_card_number also. I have codes in different files but when I makemigrations, it is giving me django.core.exceptions.FieldError: Unknown field(s) (Id_number) specified for User. How to solve this problem? models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): Id_card_number = models.CharField(max_length=15) settings.py AUTH_USER_MODEL = 'users.User' admin.py from django.contrib.auth.admin import UserAdmin from .models import * admin.site.register(User, UserAdmin) views.py from django.contrib.auth import get_user_model User = get_user_model() -
Updating data in Database from Django form
I want to create a form that edits data already stored on my DB. This is what the template looks like: {% for row in mydb %} <form method="post" novalidate> {% csrf_token %} {% include 'main/includes/bs4_form.html' with form=form3 %} {{row.firstfield}} {{row.secondfield}} <button name="button3" type="submit" class="btn btn-danger style="background-color: red;">CANCEL</button></td> </form> {% endfor %} The for statements is to display each row of the data in my table in a single line. Near each line, there is a submit button. When this button is clicked, the field secondfield is updated with the value New Value, as you can see in my form. Thi is the part of the view involved: def myview(request, tvticker): row = mydb.objects if request.method == 'POST': ... if 'button3' in request.POST: form3 = form = UpdateForm(request.POST) if form3.is_valid(): profile = form.save(commit=False) profile.save() messages.success(request, f"Success") ... render(request, "main/mytemplate.html", context={'row': row,}) And here is the form: class UpdateForm(forms.ModelForm): SomeField = forms.CharField() class Meta: model = MyModel fields = ("SomeField",) def save(self, commit=True): send = super(UpdateForm, self).save(commit=False) send.secondfield = 'New Value' if commit: send.save() return send My actual code it's not working, is seems to send a POST request but the secondfield value is not updated. For example, if i click … -
Unable to query through elasticsearch
I am using Elasticsearch in my Django application. When i try to query my result using curl i get found = false. Can someone help me here !]1 I am following this tutorial and my code when i execute https://www.freecodecamp.org/news/elasticsearch-with-django-the-easy-way-909375bc16cb/ and my code fails when i execute curl -XGET 'localhost:9200/blogpost-index/blog_post_index/1?pretty' -
Django Prefetch not fetching the related fields
I have four models that reference a CustomUser table. class Profile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) ... class Question(models.Model): question = models.CharField(max_length=140) class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers') answer = models.CharField(max_length=70) class Response(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='responses') question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.ForeignKey(Answer, on_delete=models.CASCADE) Each question has multiple answers but each user can only pick one answer to each question. Each user can answer multiple questions. I have a ViewSet that authenticated users can access that is supposed to return a list of users with the same answers as them. serializer_class = serializers.ProfileSerializer def get_queryset(self): user_answers = qmodels.Answer.objects.filter(response__user=self.request.user) return models.Profile.objects.prefetch_related( Prefetch( 'user__responses', queryset=qmodels.Response.objects.filter(answer__in=user_answers), to_attr='common_answers' ) ) class ProfileSerializer(serializers.ModelSerializer): common_answers = ResponseSerializer(many=True) However, I'm getting the following error: Got AttributeError when attempting to get a value for field `common_answers` on serializer `ProfileSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Profile` instance. Original exception text was: 'Profile' object has no attribute 'common_answers'. I've added a print after prefetch_related and it is showing the base records properly but there is no common_answers field -
Django: How to Auto-Populate field with a related-model's field
I have two basic models: class ModelA(models.model): ... #some fields score = models.IntegerField() class ModelB(models.model) ... #some fields related_model=models.OneToOneField(ModelA) score = models.IntegerField(default=related_model.score) What I want is that upon creation of ModelB, it's score field be filled with the value of score of ModelA to which it has a OneToOne relation. I have tried setting the score = models.IntegerField(default=related_model.score) but upon migration I get the error:AttributeError: 'OneToOneField' object has no attribute 'score' I also tried defining a method under ModelB as follows and passing it to the default: def get_score(self, *args, **kwargs): return self.threat.score This doesn't work either. when I set default=get_score() I get the error: missing one required positional argument: self How can I automatically set a model's field to be a field of it's related model's (by OneToOne Relation) field? -
how to run Laravel project and Dajngo project using same apache server
After i have done Django configuration in apache2.conf file my all laravel projects stop working I want to run laravel and Dajngo project deployed on different domain using same apache server -
How can i create a web page for upload big file in Django with process bar
i want to create a web page in Django for upload big file (any file) with process bar but i don't know how can i do it? i can't create process bar? i create a model for uploaded files and one form for render model and a html page for that form i created '''python class uploadfile(models.Model): filename=models.charfiled(max_length=10) file=models.filefiled(upload_to='myfile') class formuploadfile(forms.Form): filename = forms.ChoiceField() file = forms.FileField() ''''' -
How can i retrieve values in a table from forms.py in django
I'm trying to make a form where the user can view the rule created by that user Only. I have This Model class Rule(models.Model): name = models.CharField(max_length=30) color = models.CharField(max_length=7, default='#007bff') companyId=models.ForeignKey(User,unique=True, on_delete=models.CASCADE) def __str__(self): return self.name def get_html_badge(self): name = escape(self.name) color = escape(self.color) companyId = escape(self.companyId) html = '<span class="badge badge-primary" style="background-color: %s">%s</span>' % (color, name,companyId) return mark_safe(html) This Form class DepartmentSignUpForm(UserCreationForm): rules = forms.ModelMultipleChoiceField( queryset=Rule.objects.all(), # queryset=Rule.objects.filter(companyId=self.request.user), widget=forms.CheckboxSelectMultiple, required=False )`class Meta(UserCreationForm.Meta): model = User`enter code here` @transaction.atomic`def save(self): user = super().save(commit=False) user.user_type = 3 user.save() department = Department.objects.create(user=user) department.rules.add(*self.cleaned_data.get('rules')) return user ` And this view @method_decorator([login_required, company_required], name='dispatch') class DepartmentSignUpView(CreateView): model = User form_class = DepartmentSignUpForm template_name = 'registration/signup_form.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'department' return super().get_context_data(**kwargs) def form_valid(self, form): form.save() messages.success(self.request, 'The Department created successfully') return redirect('company:homePage') I want to retrieve the rules in the department sign up page created by the logged-in company only. What I am getting is the rules created by all the company -
how to get data from html page and save it to database in several steps?
i have a some model and i need get data from my html pages that users can complete it.one of them is here: class Doctor(models.Model): PersonalInfo=models.OneToOneField( Personalnfo, on_delete=models.CASCADE, ) ReceptionInfo=models.OneToOneField( ReceptionInfo, on_delete=models.PROTECT, null=True,blank=True ) MedicalComplex=models.ForeignKey(MedicalComplex,on_delete=models.CASCADE) MedicalNumber=models.IntegerField() Expertise=models.CharField(max_length=100) ExpertiseCode=models.CharField(max_length=5) UserName=models.CharField(max_length=32) PassWord=models.CharField(max_length=32) SelfPicture=models.ImageField() Bio=models.CharField(max_length=1000,null=True,blank=True) Website=models.CharField(max_length=50,null=True,blank=True) fields with name "PersonalInfo" and "ReceptionInfo" are from another class.problem is here.i want to create many html pages and use each one for one field. for example one page for PersonalInfo data , one page for ReceptionInfo data,and one page for other fields of my class.i mean step by step. now how can i get data from my pages and save them in my db? -
How to solve the problem of django.core.exceptions.FieldError?
I am trying to add new input field in users page in django admin, but it is showing me email, password, confirm password fields. I want it to show Id_card_number also. I have codes in different files but when I run the code, it is giving me django.core.exceptions.FieldError: Unknown field(s) (Id_number) specified for User. How to solve this problem? models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): Id_card_number = forms.CharField(max_length=15, required=True) settings.py AUTH_USER_MODEL = 'users.User' admin.py from django.contrib.auth.admin import UserAdmin from .models import * admin.site.register(User, UserAdmin) views.py from django.contrib.auth import get_user_model User = get_user_model() -
How can i make like dislike button for anonymous user using django , how can i manage this session ? Please anyone could explain this?
Recently i'm developing my first blog website using django , no i want add like and dislike button but anyone can give multiple like , so i want to handle that . But how ? Please explain someone. -
Apache2 Configuration for Django Project
I have tried all apache configuration for running my Django project at itssmartworld.com which is my one the domain but all solution and configuration not working Can you tell me all the configuration for running it well i have made some configuration in my /etc/apache2/sites-available/000-default.conf file and my django project is uploaded at file path /var/www/vhosts/itssmartworld.com/MyAwesomeCart WSGIScriptAlias / /var/www/vhosts/itssmartworld.com/MyAwesomeCart/mac/wsgi.py WSGIPythonPath /var/www/vhosts/itssmartworld.com/MyAwesomeCart Order deny,allow Allow from all i want to run Django project at http://itssmartworld.com/ url only but right now this is coming on this url Server Error 403 Forbidden You do not have permission to access this document. -
How to write a model in Django with category and author or reporter (As ForeignKey)? Can i use two foreignkey in same Post class model?
category = models.ForeignKey(Category, related_name='article', on_delete=models.CASCADE) reporter = models.ManyToManyField(User, on_delete=models.CASCADE, related_name='article') Can I write a model class like this? -
django:mysql:error(1045, "Access denied for user 'root'@'localhost' (using password: NO)")
I am a newbie, just getting into Django, I want to implement django and mysql connections,and i built django and mysql in linux environment. When I type command python3 manage.py makemigrations Then give an error MySQLdb._exceptions.OperationalError: (1045, "Access denied for user 'django1'@'localhost' (using password: NO)") I read a lot of questions about this error on the forum, all said that it is an account and password problem, so,I created a database Firstproject, then created a new user Django1, granted all privileges on Firstproject.* to foo_user@%, and flushed privileges. but after I set the account permissions, this problem still occurs. Setting.py about mysql configuration DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME':'Firstproject', 'USER':'django1', 'PASSSWORD':'asdewq', 'HOST':'localhost', 'PORT':'3306' } } More details about the error Traceback (most recent call last): File "/home/ccheng/.local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection self.connect() File "/home/ccheng/.local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 189, in connect self.connection = self.get_new_connection(conn_params) File "/home/ccheng/.local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 274, in get_new_connection conn = Database.connect(**conn_params) File "/home/ccheng/.local/lib/python3.6/site-packages/MySQLdb/__init__.py", line 84, in Connect return Connection(*args, **kwargs) File "/home/ccheng/.local/lib/python3.6/site-packages/MySQLdb/connections.py", line 164, in __init__ super(Connection, self).__init__(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (1045, "Access denied for user 'django1'@'localhost' (using password: NO)") Can someone point me where I am wrong? -
Compare annotations in Django ORM filter
I'm trying to translate this query into a Django ORM call. Model: class model(models.Model): member = CharField() pos = IntField() Query SELECT member FROM model GROUP BY member HAVING MIN(pos) = MAX(pos); What I'm trying: q = model.objects.all() q.annotate(min=Min('pos'), max=Max('pos')).values('member','pos').filter(min=max) This almost works, if it wasn't for the last call to .filter(min=max). Apparently, I'm not allowed to compare 2 annotations this way. TypeError: int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method' Is this possible in any other way? -
Django or SQL: finding how many unique values of a given column for an grouped queryset
I have a dataset that looks like this member position 0 1 0 0 0 1 0 1 1 0 1 1 1 0 1 1 1 1 2 0 2 0 2 0 What I'm trying to achieve is to know which member only has one position. I've started with SQL: SELECT * FROM 'table' GROUP BY member, position and it gives me member position 0 0 0 1 1 0 1 1 2 0 From this result, how can I enucleate all the members that appear only once? I've tried DISTINCT, but it doesn't solve the problem. Also, I'd like to write this in Django ORM, with a single queryset, but group_by must be used with annotate or aggregate, but these only work with Sum, Count, Avg... Would that be the right approach? -
How to send <textarea> text to python view in django?
I have a textview in my html template that allows the user to enter text <textarea name="texteditor" id="texteditor" style="width:100%; height:100vh; resize:none; font-size:20px; font-family:sans-serif; border:none;" placeholder="Start Writing!"></textarea> I want to get that text on a button click into my view def write_view(request, *args, **kwargs): texteditor = request.POST.get('texteditor') print(texteditor) return render(request, "write.html", {'texteditor': texteditor}) Is there a solution for this? -
How an endpoint can be generated with Angular, to send POST requests
I am new to Angular and Django, I am working with angular and django on a project, with angular from the frontend and Django from the backend, the question is that I need to send POST request from a form (Angular) to a set of views through a point final. The point is that I do not understand this endpoints well, I mean I am consuming an api rest from angular with Django Rest Framework to show it in the frontend, but the concept endpoint is new to me. The reason for sending this request is to send a parameter to DJANGO to generate and download a custom excel according to the parameter sent to you in the request (for example, filter me and just fill in the EXCEL with this condition EquipoOrigen = P79COL01, where EquipoOrigen is a The column of the table. -
Can I annotate on a OneToMany relationship for performance?
I have the following simplified models. class Service(models.Model): ... class ServiceLogs(models.Model): service = models.ForeignKey(Service, related_name='logs', ...) who_did = models.ForeignKey(User, ...) role_played = models.CharField(choices=(('CA','CA'), ('CO', 'CO'), ('TO', 'TO')), ...) I know I can find out who played what role by calling <service obj>.logs.filter(role='CA'), but this approach hits the database 3 times per object given I have 3 roles. I was reading the documentation about aggretation and annotation, but all the examples use numeric values like Sum, Avg, etc. Can I make this query more efficient so I hit the database once per object? -
How to import list of emails separated by semicolon using django import export
Wondering the easiest way to import a csv file that imports info into two tables using django import export ex: csv file: id,field1,primary,CC,alert 1,my_value,email1@e.com;email2@e.com,email3@e.com,email4@e.com;email5@e.com Desired import foo model: id field1 1 my_value email model: id type email_address foo_id 1 primary email1@e.com 1 2 primary email2@e.com 1 3 CC email3@e.com 1 4 alert email4@e.com 1 5 alert email5@e.com 1 I already used ForeingKey and ManytoMany widgets to export and import other data into single tables. But I don't have ideas for this particular request. I'm thinking to override some methods like before_import. What should be the best approach? Any help will be appreciate :) Thanks!! -
Django runserver error - No Module found cx_Oracle
I am trying to create a web application on Django with oracle backend on my local machine. I have python 3.7, Django 2.2, oracle 12c on win 10. I have installed cx_Oracle. I can connect to oracle from python without an issue. But when I tried to run python manage.py runserver on virtual env then I got following error: File "C:\Users\local.virtualenvs\ab1-k_8ZC6ny\lib\site-packages\django\db\backends\oracle\base.py", line 48, in raise ImproperlyConfigured("Error loading cx_Oracle module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading cx_Oracle module: No module named 'cx_Oracle' I tried to put the cx_Oracle folder location on the PATH but still did not work. I appreciate any help you can provide. -
deploy a django app from localhost app to web application using windows
i have a little experience in django applications but only all applications it was localhost, Now i would like to know step by step how to deploy a django localhost app to web application using www and donain name to be accessible to everyone. i have no idea how this can be done and i haven't found any guide for this task . only where I know is : I need static ip(?) Buy domain name. 3.settings.py ALLOWED_HOSTS = ['static ip','www.name.com'] I use windows os (or I can use windows server for application) in my machine where I want to have this app. any idea ?thank you -
How to pass dictionary value to html template after i append the dictionary into array of dictionary?
item = [] data = { 'name':'john', 'age' : 5, } # i am not able to pass value to html template below: # first i use this , it does not work item.append(data.copy()) # second i use this one item.append(data) # still it does not work. # this is how i pass to html template {{ item.name }} #but it still does not work. i am trying use both method i am not able to pass value to html template below: There is no error. However, the only problem is the value does not display anything on html template. -
How to check if celery task is already running before running it again with beat?
I have a periodic task scheduled to run every 10 minutes. Sometimes this task completes in 2-3 minutes, sometimes it takes 20 minutes. Is there any way using celery beats to not open the task if the previous task hasn't completed yet? I don't see an option for it in the interval settings.