Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to block requests from apps like postman, insomnia and allow only one origin - django rest framework
I try to block the possibility to send a post request to my app via postman or insomnia. I want to limit the source of a request to one domain www.sample.com. I did add this domain to the ALLOWED_HOSTS and CORS_ORIGIN_WHITELIST, and nothing more and still I can send a request and save the data in my django app. How can I limit the origin of a request to the one domain and block all others or return "Unauth msg"? Stack: DJANGO REST Framework -
Translated URLs in Django that work simultaneously for all languages
Given a view defined by a function about_us, I would like it to be accessible by either one of these URLs: /about/ /acerca-de/ In a way that requesting any of those activates the corresponding language and renders the view, but both URLs remain accessible at all times regardless of the currently active language. I would also like to reverse these URLs inside templates using the path name, so reverse('about_us') can give me the URL that corresponds to the currently active language. Django offers a mechanism for translating URLs by wrapping the string matchers for path objects in gettext_lazy so reverse URL resolution can return the one appropriate for the current language, but AFAIK only one of the URLs works at any given time, depending on the current language. If I instead define two path objects then I can point them to the same view wrapped by some view decorator that activates the given language first, but then I lose the ability to perform reverse URL resolution and I am forced to perform some ugly tricks to get links to respect the current language. Has anyone found a solution to this problem? -
Django 'str' object has no attribute 'field' context
I have a problem, i got this error: 'str' object has no attribute 'field' This is my views: from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse from .models import Company from .forms import NewCompanyForm # Sociétés def companies_index(request): companies_list = Company.objects.order_by('-id') context = { "companies_index": "active", 'companies_list': companies_list, } return render(request, 'companies/index.html', context) def companies_create(request): context = { "companies_create": "active", } if request.method == 'POST': form = NewCompanyForm(request.POST) if form.is_valid(): form.save() return redirect('companies_index') form = NewCompanyForm() return render(request,'companies/create.html',context,{'form': form}) def companies_delete(request, pk): company = get_object_or_404(Company, pk=pk) company.delete() return redirect('companies_index') The problem is with the "create" action i want to know how i can pass the context variable and the form variable to my template. Best regards. Thx. -
ContentType matching query does not exist. django=3.0.7
from django.contrib.contenttypes.models import ContentType def posts_detail(request,slug=None): instance = get_object_or_404(Post, slug=slug) if instance.publish > datetime.datetime.now().date() or instance.draft: if not request.user.is_staff or not request.user.is_superuser: raise Http404 share_string = quote_plus(instance.content) initial_data = { "content_type": instance.get_content_type, "object_id": instance.id } form = CommentForm(request.POST or None, initial=initial_data) if form.is_valid() and request.user.is_authenticated: c_type = form.cleaned_data.get("content_type") content_type = ContentType.objects.get(model=c_type) obj_id = form.cleaned_data.get('object_id') content_data = form.cleaned_data.get("content") new_comment, created = Comment.objects.get_or_create( user = request.user, content_type= content_type, object_id = obj_id, content = content_data, ) if created: print("yeah it worked") comments = instance.comments context = { "title": instance.title, "instance": instance, "share_string": share_string, "comments": comments, "comment_form":form, } return render(request, "post_detail.html", context) Showing following error ContentType matching query does not exist. Request Method: POST Request URL: http://127.0.0.1:8000/posts/gchgjvhbk/ Django Version: 3.0.7 Exception Type: DoesNotExist Exception Value: ContentType matching query does not exist. Exception Location: C:\Users\ANUPYADAV\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py in get, line 417 Python Executable: C:\Users\ANUPYADAV\AppData\Local\Programs\Python\Python37\python.exe Python Version: 3.7.6 Python Path: ['C:\Users\ANUPYADAV\Desktop\try19\src', 'C:\Users\ANUPYADAV\AppData\Local\Programs\Python\Python37\Scripts', 'C:\Users\ANUPYADAV\Desktop\try19\src', 'C:\Users\ANUPYADAV\AppData\Local\Programs\Python\Python37\python37.zip', 'C:\Users\ANUPYADAV\AppData\Local\Programs\Python\Python37\DLLs', 'C:\Users\ANUPYADAV\AppData\Local\Programs\Python\Python37\lib', 'C:\Users\ANUPYADAV\AppData\Local\Programs\Python\Python37', 'C:\Users\ANUPYADAV\AppData\Roaming\Python\Python37\site-packages', 'C:\Users\ANUPYADAV\AppData\Local\Programs\Python\Python37\lib\site-packages'] -
Passing parameters in URLs in Django
This is supposed to be a stupidly simple thing, nevertheless I can't get my head around it. I want to create a 'bulletin' page where I filter a few models by start- and end- date. path('bulletin/<int:startyear>-<int:startmonth>-<int:startday>/<int:endyear>-<int:endmonth>-<int:endday>/', bulletin_view, name="bulletin"), And the view: def bulletin_view(request, startyear, startmonth, startday, endyear, endmonth, endday): start_date= startyear + '-' + startmonth + '-' + startday end_date= endyear + '-' + endmonth + '-' + endday dateEvents = dateEvent.objects.filter(start_date_time__gte=start_date).filter(start_date_time__lte=end_date).order_by('start_date_time') context = { 'dateEvents': dateEvents, } return redirect('bulletin') When I go to this URL: /bulletin/2020-06-01/2020-06-30/ I keep getting: TypeError at /bulletin/2020-06-01/2020-06-30/ bulletin_view() got an unexpected keyword argument 'startyear' I've changed parameters names, replaced '-' with '/', taken the 'int:' out; nothing, I still get the error. What am I missing? -
how to get each id of each selected in M2M djnago
i want to get the ID of selected imeis class Mobile(models.Model): mobile = models.CharField(max_length=20,unique=True) quantity = models.IntegerField() imei = models.ManyToMany(Imei,on_delete=models.CASCADE) class Imei(models.Model): imei = models.CharField(max_length=13,unique=True) if i selected 10 imei's i want to get 10 ID's of selected imeis!? i tried this ways but no one worked ! instance.imei__id instance.imei.id instance.imei_id i appreciate your helps -
Generating HTML from AJAX
I am making an AJAX pagination in my Django project. First time using it and I am doing it step by step, debugging along the way. I want the user to paginate through its favorite products. Each product has it's picture, name, brand... What I have now is a functional AJAX that get a set of datas back. I have everything I need to display the list but I find it hard to display my HTML from AJAX. My AJAX $(".nav_button_2").on("click", function(event) { event.preventDefault(); var page = $(this).val(); console.log (page); var url = '/register/account/'; $.ajax({ url: url, type: "POST", data:{ 'page': page, 'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val() }, datatype:'json', success: function(resp) { $('#fav_list').html('') var resp = JSON.parse(resp); $.each(resp, function(i, val) { $('#fav_list').append('<h2>' + val.sub_pic + '</h2>') }); } }); }); My HTML: <div class='row d-flex justify-content-between'> <div class="card mb-3" style="width: 49%;"> <div class="row no-gutters"> <div class="col-md-2 my-auto"> <img class="mx-auto d-block" style="width:auto; height:auto; max-width:100px; max-height:100px; " src="{{ saved.original_product.picture }}"> </div> <div class="col-md-10"> <div class="card-body"> <h5 class="card-title"><a href="{% url 'finder:detail' saved.original_product.id %}" class="aaccount">{{ saved.original_product.real_name }}/ {{ saved.original_product.real_brand }}</a> </h5> <img src="/static/finder/img/nutriscore-{{ saved.original_product.nutrition_grade}}.svg" style="width:70px;"><br> </div> </div> </div> </div> This HTML is for the first page displayed by django, for the other pages I will substitute all … -
Django annotations m2m duplication
I am trying to do an annotation with django, for some reason I am getting a weird result when I add the m2m of task: qs = qs.annotate(Sum('activitytime__cost'), Sum('tasks__tasktime__cost')) activitytime__cost = 600 ! WRONG ! When I do: qs = qs.annotate(Sum('activitytime__cost')) I get the correct value of 200, but it seems like it's multiplying by the amount of tasks I have when trying to sum the m2m of tasks. Any help is much appreciated. -
How to display extended user model extrafield at django-rest-auth registration endpoind
I am trying to use the django-rest-auth library on my django rest framework api. What I have done here, is extending my user model by using a one to one field to the basic user model, and adding an extra field role, which is going to be a choice between "Student" and "Teacher". Here is my model: from django.db import models from django.contrib.auth.models import User ROLES = [ ('Student', 'Student'), ('Teacher', 'Teacher'), ] class AxessUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) role = models.CharField(max_length=7, choices=ROLES, default="Student") The role field is displayed as an inline inside the admin site. In fact, the result is the following: So far so good. Now when I try to access the rest-auth endpoint for registration, obviously I am presented with a registration form for the generic django user model. So my question is, how do I implement this field inside the rest-auth registration endpoint? -
Why does my flask app error with "Permission Denied" when I try to deploy and run on AWS?
I created my flask web app in AWS so I could deploy it on the server. But, it won't let me run it. It keeps giving an error. This is my traceback. Traceback (most recent call last): File "/home/ec2-user/environment/qgen/helloworld/application.py", line 102, in <module> flaskrun(app) File "/home/ec2-user/environment/qgen/helloworld/flaskrun.py", line 29, in flaskrun port=int(options.port) File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 944, in run run_simple(host, port, self, **options) File "/usr/local/lib/python3.6/site-packages/werkzeug/serving.py", line 1052, in run_simple File "/usr/local/lib/python3.6/site-packages/werkzeug/serving.py", line 1005, in inner fd=fd, File "/usr/local/lib/python3.6/site-packages/werkzeug/serving.py", line 848, in make_server host, port, app, request_handler, passthrough_errors, ssl_context, fd=fd File "/usr/local/lib/python3.6/site-packages/werkzeug/serving.py", line 740, in __init__ HTTPServer.__init__(self, server_address, handler) File "/usr/lib64/python3.6/socketserver.py", line 456, in __init__ self.server_bind() File "/usr/lib64/python3.6/http/server.py", line 136, in server_bind socketserver.TCPServer.server_bind(self) File "/usr/lib64/python3.6/socketserver.py", line 470, in server_bind self.socket.bind(self.server_address) PermissionError: [Errno 13] Permission denied and this is my code #!flask/bin/python from flask import Flask, redirect, url_for, render_template, request from mainforqupld import * from outputtostring import storetheprintoutputasstring from VolumeQ1 import volumeQ1 from random import choice from mainforqupld import * from LinearEquationsQ1 import linearEquationsQ1 from ExponentialEquationsQ1 import exponentialEquationsQ1 from PercentageQ1 import percentageQ1 from ProbabilityQ1 import probabilityQ1 from CoordinateGeoQ1 import coordinateGeoQ1 from RadicalsQ1 import radicalsQ1 from SystemsQ1 import systemsQ1 from flaskrun import flaskrun app = Flask(__name__) @app.route('/') def home(): return render_template("qgenhtml.html") @app.route('/', methods=['GET','POST']) def my_form_post(): … -
Getting "Message.receiver" must be a "User" instance in Django forms
I get this error message and I don't know how to fix it, I tried every possible solution I could find in StackOverflow or I could think of. Cannot assign "'2'": "Message.receiver" must be a "User" instance This is my forms.py file : class SendMessageAuditorForm(forms.ModelForm): auditors = User.objects.filter(is_staff=True).values_list('id', 'username') message = forms.CharField( validators=[NOSPECIAL_CHARACTERS], widget=forms.Textarea(attrs={'maxlength': '500'}), required=True, label="Write your message" ) receiver = forms.ChoiceField( choices = auditors, required=True, label="Send to" ) class Meta: model = Message fields = ('message', 'receiver',) This is my models.py file: class Message(models.Model): date = models.DateTimeField( verbose_name="Date d'envoie" ) sender = models.ForeignKey( User, related_name='sender', on_delete=models.PROTECT, verbose_name="Sent from" ) receiver = models.ForeignKey( User, related_name='receiver', on_delete=models.PROTECT, verbose_name="Sent to" ) message = models.TextField( blank=False, null=False, verbose_name="Message" ) is_read = models.BooleanField( default=False, verbose_name="message is read" ) class Meta: ordering = ['-date'] verbose_name = "Message" verbose_name_plural = "Messages" def __str__(self): return "{} : {} - {} - {}".format(self.date, self.sender, self.message, self.receiver) and this is my view.py : @login_required def send_message(request): if user.profile.institution: institution = user.profile.institution else: institution = None user = request.user form = SendMessageAuditorForm(request.POST) if request.method == 'POST': if form.is_valid(): post_data = dict(request.POST.lists()) now = datetime.now() message = form.save(commit=False) message.date = now message.sender = user #*The problem might be here* receiver_id … -
Modify default queryset in django based on condition
assume the following table | id |policy_start_date| amount | is_renewed | original_policy |renewed_counter| | 10 | 01-06-2019 | 134 | 0 | NULL | 0 | | 12 | 05-06-2019 | 454 | 0 | NULL | 0 | | 35 | 04-06-2020 | 121 | 1 | 12 | 1 | My Issue is, when is_renewed is True , i want to show the a prefix R along with renewed_counter and original_policy instead of the original policy id. for example : for the third entry, i want to show id as R112 instead of 35 To achieve the above, I'm using ModelManager as below but unable to get the desired result in my model.py : class CustomManagerTest(models.Manager): def get_queryset(self): policies = super(CustomManagerTest,self).get_queryset().filter(is_renewal=True) for policy in policies: policy.id = str("R" + str(policy.renewal_counter) + policy.renewal_policy_id) return policies class Policy(models.Model): objects = CustomManagerTest() policy_start_date = models.DateField() amount = models.IntegerField() is_renewed = models.BooleanField(default = False) original_policy = models.IntegerField(Null = False) renewed_counter = models.IntegerField(default = 0) my function in views: def show_all_policies(request): policy_list = Policy.objects.all() return HttpResponse(policy_list) Error I'm getting: django.db.utils.OperationalError: (1054, "Unknown column 'myapp_policy.renewal_counter' in 'field list'") -
create a spare parts web API
I want to create a spare parts web API using Django, the question here is should I create my own spare parts database, or just use some API from professionals (like tecdoc), and how do i process in each method -
Nginx location doesnt workd
I have a Django app running with Nginx and Gunicorn on mysite.com. I would like it to be accessible only under mysite.com/myapp. This is my nginx configuration: server { listen 80; server_name server_domain_or_IP; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/sammy/myprojectdir; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } When I change location / to location /myapp/, I get "Not found error". Nginx error log doesn't seems to have anything. What could be the issue? -
how to have an "add another file" feature in a django form?
I have a Document model with a FileField. When creating a new Document , I can upload a file, submit and save the new Document. here is my code for a simple upload : models.py class Document(models.Model): document = models.FileField(upload_to='documents/') forms.py from .models import Document class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ('document', ) views.py from .forms import DocumentForm def model_form_upload(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('home') else: form = DocumentForm() return render(request, 'journal/model_form_upload.html', { 'form': form }) I wish to alter this to enable the user to successively add multiple files. (not selecting multiple files with a unique submit button) example of process : 1) select a file, click on upload, 2) display : the name of the uploaded file, a button to remove this file if needed a button to upload another file 3) eventually click on submit to save the Document and its multiple files. -
Using same foriegn key in multiple tables django
I have a table named class student(models.Model): std_name= models.CharField(max_length=20 , blank=False, null=False) std_username = models.CharField(max_length=20 , blank=False, null=False) And another table named std_admission. Can I use the student fields in this table is foreign keys like this? And if so can I use it the same way in other tables as well? class std_admission(models.Model): admission_date= models.CharField(max_length=20 , blank=False, null=False) std_name = models.ForeignKey(student, default=1, on_delete=models.SET_DEFAULT) std_username = models.ForeignKey(student, default=1, on_delete=models.SET_DEFAULT) -
Django following system using many to many field
So I have the following model (a profile for the user where the user is the default django user): class Profile(models.Model): user=models.OneToOneField(get_user_model(), on_delete=models.CASCADE, null=True, related_name='getprofile') following=models.ManyToManyField(get_user_model()) Let's say I have a user Mark. Then I get who he is following like this: mark.getprofile.following.all() My question is how do I get a queryset of people that follow Mark? I think that since this is a many-to-many relationship this must be possible but I am quite new in Django so I don't know how to do it. Any help would be greatly appreciated! -
Static File Not Serving Django Python Socket IO Evenlet
I am trying to using python socket io library with django. For i am also using eventlet but problem is comming where my all static files not working. It is displaying not Not Found static file import os from django.core.wsgi import get_wsgi_application import socketio from apps.chatbox.views import sio os.environ.setdefault("DJANGO_SETTINGS_MODULE", "chatbot.settings") django_app = get_wsgi_application() application = socketio.Middleware(sio, wsgi_app=django_app, socketio_path='socket.io') import eventlet import eventlet.wsgi eventlet.wsgi.server(eventlet.listen(('', 8000)), application) Error Not Found: /static/js/main.a9e46e37.chunk.js 127.0.0.1 - - [08/Jun/2020 20:28:47] "GET /static/js/main.a9e46e37.chunk.js HTTP/1.1" 404 1976 0.017001 Not Found: /static/js/4.f274b99f.chunk.js 127.0.0.1 - - [08/Jun/2020 20:28:47] "GET /static/js/4.f274b99f.chunk.js HTTP/1.1" 404 1967 0.021015 Not Found: /static/js/main.a9e46e37.chunk.js 127.0.0.1 - - [08/Jun/2020 20:28:47] "GET /static/js/main.a9e46e37.chunk.js HTTP/1.1" 404 1976 0.010007 Without bellow code in wsgi file, everything works better import eventlet import eventlet.wsgi eventlet.wsgi.server(eventlet.listen(('', 8000)), application) -
Sending attachment in django using SendGrid
I have an html string I convert to PDF using Weasyprint and thereafter attaching it to an email which is sent using SendGrid. The code below is working. But I have two question: Since I store the file to MEDIA_ROOT using Weasyprint, will the fail be saved and therefore has to be deleted after sending? Or is it only stored temporary? Is there a way to generate the PDF file without storing it at all and in some way attach the PDF file from an object only? Code: message = Mail(from_email = ...... pdf_file = HTML(string=html_content, base_url=settings.MEDIA_ROOT).write_pdf() temp = tempfile.NamedTemporaryFile() temp.write(pdf_file) temp.seek(0) with open(temp.name, 'rb') as f: data = f.read() encoded = base64.b64encode(data).decode() #build attachment attachment = Attachment() attachment.file_content = FileContent(encoded) attachment.file_type = FileType('application/pdf') attachment.file_name = FileName('test.pdf') attachment.disposition = Disposition("attachment") attachment.content_id = ContentId("PDF Document file") message.attachment = attachment If anyone have any inputs on this I am very grateful. -
Problem With django-cron -code executes from command line, but not crontab
I am not sure if this is for StackOverflow or a different forum, but I have installed django-cron for my Django project and am struggling to get it working when the command is scheduled in crontab. I know that the code executes because if I run it from the command line as below then the code is executed and I can see the results. python3 manage.py runcrons If I then schedule the command to run in the crontab, I have tried both for root and logged on user, the code doesn't seem to execute. When I run "grep CRON /var/log/syslog" then I get the following output: Jun 8 15:55:01 DJANGO-DEV-1 CRON[6616]: (<username>) CMD (source /home/<username>/.bashrc && source /home/<username>/environments/<appname>/bin/activate && python3 /home/<username>/Documents/<appname>/manage.py runcrons > /home/<username>/cronjob.log) Jun 8 15:55:01 DJANGO-DEV-1 CRON[6617]: (root) CMD (source /home/<username>/.bashrc && source /home/<username>/environments/<appname>/bin/activate && python3 /home/<username>/Documents/<appname>/manage.py runcrons > /home/<username>/cronjob.log) Jun 8 15:55:01 DJANGO-DEV-1 CRON[6614]: (CRON) info (No MTA installed, discarding output) Jun 8 15:55:01 DJANGO-DEV-1 CRON[6615]: (CRON) info (No MTA installed, discarding output) Jun 8 15:55:01 DJANGO-DEV-1 CRON[6618]: (root) CMD (command -v debian-sa1 > /dev/null && debian-sa1 1 1) I can check for the "cronjob.log" file, but it is not there. If I deactivate the environment and … -
problem with serving static files of django on server with nginx
Hi everyone I have changed default file of nginx where is in /etc/nginx/sites-available/default as below upstream django { server 127.0.0.1:8000; } server { listen 80; location /static/ { root /home/django/chistaa/chistaa/settings; try_files $uri =404; } location / { try_files $uri @send_to_django; } location @send_to_django { proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://django; } } but it doesnt load my static files. What did I wrong?! -
Django ORM .values() not works properly
This code dos not work: analyzer_signs = Sign.objects.filter(is_analyzer_used=True).values('code', 'name') for analyzer_sign in analyzer_signs: print(analyzer_sign) It prints nothing (doesn't enter the cycle) But when I delete .values('code', 'name') - It works greate: analyzer_signs = Sign.objects.filter(is_analyzer_used=True) for analyzer_sign in analyzer_signs: print(analyzer_sign) And I even can print text from fields code and name. I dont know what the *uck happens. And no one of my teammates doesn't. Please, help! Here is the model code: class ShortNameMixin(models.Model): short_name = models.TextField(blank=True) class Meta: abstract = True # class CodeMixin(models.Model): code = models.CharField(max_length=125) class Meta: abstract = True class AbstractBaseItem(common_models.CommonInfoAutoIncrementPK): name = models.TextField() is_active = models.BooleanField(default=True) class Meta: abstract = True def __str__(self): return self.name class SimpleDirectoryItem(ShortNameMixin, CodeMixin, AbstractBaseItem): class Meta: abstract = True class Sign(SimpleDirectoryItem): additional_code = models.CharField(max_length=255, null=True, blank=True) .... is_analyzer_used = models.BooleanField(default=False) alias = 'it-is-allias' class Meta: db_table = 'signtable' unique_together = ('sign_type', 'name',) ordering = default_ordering default_permissions = () permissions = (.......) PS: I tried to install differents db dumps, launched this project on Linux Mint (virtualbox) and Windows - still not works! But my teammates says "It works on my machine"... Can you suppose, what the problem is? Any help! -
After creating a new row in a table using .append() and click this new created row jquery is not working
In my code when I click on a of a table, for every tr a corresponding page is open using jquery. But problem is after calling ajax when I add a new tr by using jquery .append() method new tr is added at the end of the table but jquery click event is not working for newly added row. It need to refresh the whole page. In this back-end I use django. My jquery code is here <script type="text/javascript"> $('#add_student_submit_btn').click(function() { image = document.getElementById('student_image').files[0]; name = $('input[name = student_name]').val(); email = $('input[name = student_email]').val(); phone = $('input[name = student_phone]').val(); formData = new FormData(); formData.append('image',image); formData.append('fullname',name); formData.append('email',email); formData.append('phone',phone); formData.append('csrfmiddlewaretoken',$('input[name = csrfmiddlewaretoken]').val()); $.ajax({ url: {% url 'ajax.addstudents' %}, type: "POST", data: formData, processData: false, contentType: false, success: function (data) { console.log(data); markup = '<tr scope="row" data-student-id="'+ data.id + '"class="students_row">'; markup += '<td><img src="{{ MEDIA_URL }}/' + data.image + '" alt="" class="student_img_table"></td>'; markup += '<td>' + data.fullname +'</td>'; markup += '<td>' + data.email +'</td>'; markup += '<td>' + data.phone +'</td>'; markup += '<td>' + '5' +'</td>'; markup += '</tr>'; tableBody = $("#student_table"); tableBody.append(markup); $('#add_student_model').modal('hide'); } }); }); $('.students_row').click(function(){ id = $(this).attr('data-student-id'); location.replace("/profile/"+id); }); </script> And here is my Html <section> <div class="container"> <table … -
Django formset set field queryset based on URL pk
I have a working formset. My goal is a one field gets choices from other model, based on queryset using pk passed on url. It's almost working, but init method is executed twyce and cleans wkargs passed. Model: class Delito(models.Model): numero = models.ForeignKey(Expediente, on_delete=models.CASCADE, blank = False) delito = models.ForeignKey(CatalogoDelitos, on_delete=models.CASCADE, blank = False) imputado = models.ForeignKey(Imputado, on_delete=models.CASCADE, blank = False) categoria = models.CharField('Categoria', max_length = 20, blank = False, choices = CATDEL_CHOICES) My URL: path('crear_delito/<int:pk>', login_required(CrearDelito.as_view()), name ='crear_delito'), Forms.py: class CrearDelitoForm(forms.ModelForm): class Meta: model = Delito exclude = () def __init__(self, numero_pk = None, *args, **kwargs): super(CrearDelitoForm, self).__init__(*args, **kwargs) self.fields["imputado"].queryset = Imputado.objects.filter(numero_id = numero_pk) DelitoFormset = inlineformset_factory( Expediente, Delito, form=CrearDelitoForm, extra=1, can_delete=True, fields=('imputado', 'delito', 'categoria'), } ) Views.py: class CrearDelito(CreateView): model = Delito form_class = CrearDelitoForm template_name = 'crear_delito.html' def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context['formset'] = DelitoFormset() context['expedientes'] = Expediente.objects.filter(id = self.kwargs['pk']) return context def get_form_kwargs(self, **kwargs): kwargs['numero_pk'] = self.kwargs['pk'] return kwargs If I print queryset, it works at first time, but is passed twice cleaning "numero_pk" value: System check identified no issues (0 silenced). June 08, 2020 - 11:33:57 Django version 2.2.12, using settings 'red.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. <QuerySet [<Imputado: Martín … -
Django template tags conditionals
Right, am struggling with my blog app when trying to render some logic through the template view. So the idea is to render a one time only button for the newly authenticated users that do not have a post published and after the user has published its first post the button will be rendered within a for loop so he/she'll be able to create/delete a new one from there. views.py @login_required(login_url='app_users:login') @allowed_users(allowed_roles=['admin', 'staff', 'users']) def blog(request): posts = BlogPost.objects.all().order_by('date_posted') context = {'title': 'Blog', 'posts': posts} return render(request, 'app_blog/blog.html', context) models.py class BlogPost(models.Model): title = models.CharField(max_length=100, null=True) content = models.TextField(null=True) date_posted = models.DateTimeField(default=timezone.now, null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title blog.html {% block content %} {% if request.user not in posts|last %} <div class="container" style="float: left;"> <a class="btn btn-primary btn-sm mt-1 mb-1" href="{% url 'app_blog:blog_create' user.id %}"><h5>C'mon {{ request.user.username }}, don't be shy! Create Your First Blog Post!</h5></a> </div> {% endif %} <br> <br> {% for post in posts %} <br> <div class="container"> <article class="media content-section"> <img class="rounded-circle account-img" src="{{ post.author.profile.image.url }}" alt="Image could not be uploaded!"> <div class="card-body media-body"> <div class="article-metadata"> <a class="mr-2" href="{% url 'app_blog:blog_user_detail' post.id %}">{{ post.author }}</a> <small class="text-muted">{{ post.date_posted|date:"d F Y" }}</small> </div> …