Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pinoychannel build desktop zoom the same as mobile zoom in c++?
Hi every one i am pinoychannel and i want to make the desktop app of zoom in similar to mobile app of zoom in by using C++. is their anyone expert to give me the easy way to make it? -
ValidationError doesn't get printed in my web
I've been learning django for two weeks now and I'm currently learning raising forms.Errors such as forms.ValidationError. Here's the code I've written: def clean_email(self, *args, **kwargs): email = self.cleaned_data.get('email') if not email.endswith("gmail.com"): raise forms.ValidationError("This is not a valid email") return email The problem I have is when I write an email that doesn't contain gmail.com, ValidationError doesn't get printed in the web. -
how to implement an admin approval system for posting blogs in pythondjango
I am building a website where user come and login, after login user publish articles with admin approval . I do not know how to do it. I made a user authentication system where user can login. But i do not know how to make him post data with admin approval. -
Django 500 error report in production exclude Invalid HTTP_HOST header errors
I'm running a Django 2.2 application in production configured using AWS ECS and Load balancer. Since the application is in production mode, it is sending all 500 errors to the ADMIN email configured. I see the logs and receiving lots of Invalid HTTP_HOST errors where I see users are trying to visit the website by the IP address of the ELB or the ELB URL and not the URL pointing CNAME to the ELB. The errors receiving are frequent at an interval of 5 to 10 minutes and are being logged by the Google Groups Since I'm sure that the application will be accessible only to the IP or host mentioned in the ALLOWED_HOSTS settings and other requests will be blocked. Is there any way to prevent such requests? If not, how can I prevent Django to report such errors? -
Searching database table through get method in django
i am new to django and having trouble to get result from my models database table through 'GET' method, my model is: ``` class records(models.Model): sex = ( ('M', 'MALE'), ('F', 'FEMALE'), ) reg_number = models.CharField(max_length=15) mic_number = models.CharField(max_length=15) dog_name = models.CharField(max_length=20) dog_breed = models.CharField(max_length=50) color = models.CharField(max_length=20) dog_Sex = models.CharField(max_length=1,choices=sex) Breeder = models.CharField(max_length=30) Owner_name = models.CharField(max_length=50) address = models.TextField(max_length=264)``` my views is: ```from django.shortcuts import render import datetime from .forms import RecordForm from .models import records # Create your views here. def index (request): return render(request, "newyear/index.html") def search (request): mic = request.GET['mic'] r = records.objects.filter(mic_number__iexact = mic ) return render(request,"newyear/search.html", {"records": r} )``` my index template is: ```<form action="{% url 'search'%}" enctype="application/x-www-form-urlencoded" method="GET"> <ul> <input type="text" name = "mic"> </ul> <button type="submit" name= "search">search</button> </form> ``` my search template is: ```!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>THIS IS RESULT PAGE</h1> {% if records %} <table> {% for records in records %} <tr> <td>{{records.color}}</td> <td>{{records.dog_name}}</td> <td>{{records.mic_number}}</td> </tr> {% endfor %} </table> {% endif %} </body> </html>`<form action="{% url 'search'%}" enctype="application/x-www-form-urlencoded" method="GET"> <ul> <input type="text" name = "mic"> </ul> <button type="submit" name= "search">search</button> </form> ``` my search template is: {% if records … -
append shipping address and billing address on checkout object
This is about the first process of checkout. Here the argument that will be sent to server will be email, lines which consists of quantity and variant's id, shipping_address and billing address. I have no problem in saving email and lines(quantity and variants) but for shipping address and billing address there are multiple cases. Guest user will not have address book so they can't send already created address. Logged in user can either send already created address or new address. So now user should be able to send new address as well thus my schema a server needs to create checkout object is as follow # these are the arguments needed to pass to server while creating checkout input CheckoutCreateInput { lines: [CheckoutLineInput]! email: String shippingAddress: AddressInput billingAddress: AddressInput } input AddressInput { firstName: String lastName: String companyName: String streetAddress1: String streetAddress2: String city: String cityArea: String postalCode: String country: CountryCode countryArea: String phone: String } on such cases, what is the proper way to handle shipping address and billing address? Here is how I tried def resolve_checkout_create(obj, info, input): print('input', input) user = info.context.user checkout = Checkout() if (input['email']): try: user = User.objects.get(email=input['email']) except User.DoesNotExist: print('User does not exist') … -
Django, combining a list of QuerySets into 1 Queryset
So I am building a clothing comparer in Django. I have created multiple checkboxes so that people can filter the products into for instance: Jackets and Trousers. To get all the products in my Postgresql database I made a dictionary with the keys being the categories and the values being the words that are linked to the category. If a match is found the products get appended to a list which contains all the products I want to show. The problem is that I have multiple QuerySets in that list and I cant output it to my HTML. Is there a way to combine all the QuerySets in the list into one QuerySet? The code: mylist = request.POST.getlist('checkbox') categorie_list = ['jackets', 'sweaters', 't-shirts', 'polo-shirts', 'trousers', 'shorts', 'hats', 'bags'] cat_dict = {'jackets': ['zip-up', 'jacket', 'overshirt', 'parka'], 'sweaters': ['hoodie', 'sweatshirt', 'jumper']} list1 = [] for item in mylist: if item in categorie_list: if item in cat_dict.keys(): print(item) for value in cat_dict[item]: print(value) data = models.Product.objects.filter(name__regex=value) list1.append(data) else: pass else: pass print(list1) list1 looks something like this: [<QuerySet [<Product: >, <Product: >]>, <QuerySet [<Product: >, <Product: >]>, <QuerySet [<Product: >, <Product: >]>] -
ModuleNotFoundError: No module named '\\ --access-logfile'
please i need help with gunicorn. i am a junior developer in python. i was setting up a server for a client, when i came across this error No module named '\ --access-logfile'. this is the gunicorn.service unit [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target this is the gunicorn.service Service [Service] User=metalcode Group=www-data WorkingDirectory=/home/metalcode ExecStart=/home/metalcode/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ gworldtc.wsgi:application please help me. -
Project for making Categories and Subcategories and product and displaying it
I need to make project where in a webpage --> product has to be taken from user and subcategories and categories have to be taken from django admin and then have to display whole database to user.All subcategories are link to category and all products are Linked to Subcategory. It has to be made in django I am wroking on it from 1 month and still not able to get desired result . -
How to after django form is submitted to be redirected to another webpage and have form data to be sent to backend database
Aim: for when django form is submitted for data to be sent and saved to admin side. problem: i can redirect it to another page after form is submitted but when i go onto admin side the data is not saved. how can i fix this? using django or javascript? html: <form method="post" > {% csrf_token %} {{form.as_p}} <input class="btn" type="submit" value="Log In"> </form> models.py: from django.db import models from django import forms class Customer(models.Model): first_name = models.CharField(max_length=200, verbose_name='') last_name = models.CharField( max_length=200, verbose_name='') def __str__(self): return self.first_name + ', ' + self.last_name forms.py: from django.forms import ModelForm from django import forms from .models import Customer class CustomerForm(ModelForm): class Meta: model = Customer fields = '__all__' views.py: from django.shortcuts import render from .forms import CustomerForm def index(request): form = CustomerForm() if request.method == 'POST': form = CustomerForm(request.POST) if form.is_valid(): form.save() context = {'form': form} return render(request, 'app/index.html', context) if you need any other files just ask -
Django queryset values get foreign key field "foo" instead of "foo_id"
according to the django documentation below: If you have a field called foo that is a ForeignKey, the default values() call will return a dictionary key called foo_id, since this is the name of the hidden model attribute that stores the actual value (the foo attribute refers to the related model). When you are calling values() and passing in field names, you can pass in either foo or foo_id and you will get back the same thing (the dictionary key will match the field name you passed in). For example: >>> Entry.objects.values() <QuerySet [{'blog_id': 1, 'headline': 'First Entry', ...}, ...]> >>> Entry.objects.values('blog') <QuerySet [{'blog': 1}, ...]> >>> Entry.objects.values('blog_id') <QuerySet [{'blog_id': 1}, ...]> So, Is that possible to call values() or any other way without passing fields explicitly to get fields without "_id"? >>> Entry.objects.values() <QuerySet [{'blog': 1, 'headline': 'First Entry', ...}, ...]> -
Retrieve saved FileFiled to save beside manage.py using django
I have saved a docx file in database using FileField of django. mainFile = models.FileField(upload_to='media/', null=True) Now, in views.py, I am writing a function to send this file to the user once requested. But I must do some edits and add some sentences in into its content before sending to user. So, I decided to retrieve the file from database and save it on my folders beside manage.py. Then open it and do my edits using python-docx. But when I write doc= MyFiles.objects.get(Label=l).mainFile with open(r"result.docx", 'w') as f: f.write(doc) f.close() in views.py I receive the error of write() argument must be str, not FieldFile How can I save the files in the database and then retrieve and save them in my backend codes folder beside manage.py with proper original extension (here .docx)? Any help would be appreciated -
Skip to the right section in the contact form
how can I make the page jump right to the chosen section of the main page (for reference: klient/#contact) after submitting a contact form? def klient(request): if request.method == 'GET': form = ContactFormForClient() else: form = ContactFormForClient(request.POST) if form.is_valid(): messages.success(request, 'Form submission successful') company = form.cleaned_data['company'] from_email = form.cleaned_data['from_email'] phone = form.cleaned_data['phone'] subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] full_messege = """ WIADOMOŚĆ OD KLIENTA Firma: %s Numer telefonu: %s Adres e-mail: %s Temat: %s Treść: %s """ % (company, phone, from_email, subject, message) try: send_mail(company, full_messege, from_email, ['bow.infos.kontakt@gmail.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return render(request, 'client_pl.html') return render(request, "client_pl.html", {'form': form}) -
How to define dynamic parallel entries in finite state machine - python django
Below is my code a.py class Order(models.Model): STATUS_STARTED = 0 STATUS_SLOW =1 STATUS_FAST=2 STATUS_JUMP=3 STATUS_CHOICES = ( (STATUS_STARTED, 'STARTED'), (STATUS_SLOW,'SLOW') (STATUS_FAST,'FAST') (STATUS_JUMP,'JUMP') ) product = models.CharField(max_length=200) status = FSMIntegerField(choices= STATUS_CHOICES, default=STATUS_STARTED, protected=True) A person STARTED from a point & he is either FAST or SLOW. @transition(field=status, source=. [STATUS_STARTED], target=STATUS_FAST) def fast(self): print("person run fast") @transition(field=status, source=. [STATUS_STARTED], target=STATUS_SLOW) def slow(self): print("person run slow ") Here in above code, I can track for angle person entry only either SLOW or FAST. Any possibility to define entries for two person at a time & one at SLOW & another at FAST state. Like maintain separate track for each person. Parallel entries is possible in python django? Pls any help. -
How do I change a value in django database on clicking selected option instead button dropdown in HTML using Ajax-JavaScript?
I have done this functionality in which all the page re-load when I press any button. I just want to implement a function using Ajax-JavaScript, when I click on Activate Option, the value in my Django database for this field changes to 'Active' and is displayed on the HTML page as active with Activate Message. If De-Activate is clicked, the text changes to De-Active along with it's value in the django database and show De-Activated message HTML Button Part <div class="card-body"> <div class="table-responsive"> <table id="example1" class="footable default table table-hover toggle-plus"> <thead> <tr> <th>S.No.</th> <th>Campus Name</th> <th>HOD Name</th> <th>Status</th> </tr> </thead> <tbody> {% for published_item in published %} <tr> <td>{{ forloop.counter }}</td> <td>{{ published_item.campus_name }}</td> <td>{{ published_item.hod_name }}</td> <td> <div class="form-inline"> <div class="dropdown"> <a class="btn btn-secondary dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {{ published_item }} </a> <div class="dropdown-menu" aria-labelledby="dropdownMenuLink"> {% if published_item.is_published == 'Activated' %} <a class="dropdown-item" href="{% url 'test_update' pk=published_item.pk %}">Deactivated</a> {% else %} <a class="dropdown-item" href="{% url 'test_update' pk=published_item.pk %}">Activated</a> {% endif %} </div> </div> </div> </td> <td> </tr> {% endfor %} </tbody> </table> </div> </div> HTML Select Part (Select Option Method) I want to change the "HTML Button Part" to "HTML Select Part" in which I use … -
Django python error: auctions.models.Listing.DoesNotExist: Listing matching query does not exist
I am try to display a listing page. Though it displays well, django keeps giving this error as below: raise self.model.DoesNotExist( auctions.models.Listing.DoesNotExist: Listing matching query does not exist. the index view displays all the listings by iteration, and the listing view displays a specific listing view by receiving a variable as "form.title". my code is as follows: views.py: def listing_view(request, title): # if get a listing page categories = Category.objects.all() # Get all the forms submitted forms = Listing.objects.all() # get the highest bid for a listing highest_price = Bid.objects.filter(title=title).order_by("-bid_price").first() # Get the listing with the title listing = Listing.objects.get(title=title) if highest_price is not None: listing.current_price = highest_price.bid_price # else set starting price as the current price else: listing.current_price = listing.starting_price listing.save() index.html: <!-- image of a listing --> <div class="col-4"> <a href="{% url 'listing_view' form.title %}"> {% if form.image %} <img src="{{ form.image.url }}" alt="" width="267px" /> {% elif form.image_url %} <img src="{{ form.image_url }}" alt="" width="267px" /> {% endif %} </a> </div> listing.html: <!-- image in the left of the container --> <div class="col-4"> {% if listing.image %} <img src="{{ listing.image.url }}" alt="" width="267px" /> {% elif listing.image_url %} <img src="{{ listing.image_url }}" alt="" width="267px" /> {% endif … -
How can i test my changes before hitting the Reload button in Pythonanywhere?
I want to test my updates and changes before hitting the Reload www.yourdomainname.com button to make sure that there are no server error 500 or any bad thing that could happen so I don't lose users, is there any way to do so? when I do python3 manage.py runserver It tells me Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). September 05, 2020 - 08:18:49 Django version 3.1, using settings 'dfreemedia.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Error: That port is already in use. even though i'm not using it -
Converted Video File not showing in templates. Also how to delete the uploaded file and replace it with converted file in the database?
Hey guys I have a video encoding function which works fine and converts video and save it in database. I am able to see the uploaded file and converted file in my pc under the media folder but the template is not able to play the file and the path of the new file after updating the field shows the wrong path in the database. I want to delete the file I uploaded and store only the converted video in the database, also need to correctly mention the path so that I can play the video in the browser. This is my views. class CreateVideoPostView(LoginRequiredMixin, BSModalCreateView): def get(self, *args, **kwargs): form = VideoPostForm() context = { 'form':form, } return render(self.request, 'videos/video/create_video.html', context) def post(self, *args, **kwargs): form = VideoPostForm(self.request.POST or None, self.request.FILES or None) if form.is_valid(): video = form.save(commit=False) video.user = self.request.user video.save() form.save_m2m() print(video.id) task_video_encoding(video.id) return redirect('videos:my_video_home') else: raise ValidationError('Check all form fields.') encode.py def encode_video(video_id): video = VideoPost.objects.get(id = video_id) old_video = video.file input_file_path = video.file.path # print(input_file_path) input_file_name = video.title #get the filename (without extension) filename = os.path.basename(input_file_path) # print(filename) # path to the new file, change it according to where you want to put it output_file_name … -
How can i use distinct in Django Views.py?
Views.py def user_detail(request): user_id = request.session.get('user_id') user = User.objects.get(username = request.user.get_username()) submit = Submit() submit_list = Submit.objects.filter(author=user).filter(result='AC').order_by('problem').distinct() context = {'User': User, 'submits':submit_list} return render(request, 'koj/user_detail.html', context) detail.html Solved : {% for submit in submits%} <th> {{ submit.problem }} <th> {% endfor %} result => Name : ziho2463 Solved : 1000 1000 1000 1000 1000 1000 1001 1001 1002 what i want => Name : ziho2463 Solved : 1000 1001 1002 this is my code. filter is working well but when i add '.distinct('problem')','DISTINCT ON fields is not supported by this database backend' error is occurred. also i used .values('problem').distinct('problem') or .values_list('problem', flat=True).distinct('problem') but that code didn't give me the result I wanted. => Name : ziho2463 Solved : 1 2 3 How can I solve this problem? -
Javascript affecting django Redirect/Refresh
There is a Patient model, and I'm creating new patient using CreateView, url link which is `/addpatient/. Designs for HTML page are built using DesignModo. When I am rendering the form simply without using any template from DesignModo, then everything is working fine that is to say that when I am pressing submit button the patient is created and I am redirected to the required page. {% block content %} <form method="POST">{% csrf_token %} {{form}} <button type="submit">submit</button> </form> {% endblock content %} the last line of below HTML code contains that script that {% extends 'patient/base.html' %} {% load static %} {% load widget_tweaks %} {% block content %} <link rel="stylesheet" href="{% static 'patient/add_patient/css/style.min.css' %}"> <!-- Form 14 --> <section class="pt-105 pb-100 bg-light form_14"> <div class="container px-xl-0"> <div class="row justify-content-center"> <div class="col-xl-8 col-lg-10"> <h2 class="small text-center" data-aos-duration="600" data-aos="fade-down" data-aos-delay="0">Patient details</h2> <form action="form-handler.php" method="post" class="mt-50 px-100 pt-85 pb-35 radius10"> <div class="row"> <div class="col-md-6 mb-35 block" data-aos-duration="600" data-aos="fade-down" data-aos-delay="0"> <div class="mb-10 f-14 semibold text-uppercase sp-20">First Name</div> {% render_field form.first_name class+="input w-full border-gray focus-action-1 color-heading placeholder-heading" type="text" name="firstname" required="required" %} </div> <div class="col-md-6 mb-35 block" data-aos-duration="600" data-aos="fade-down" data-aos-delay="300"> <div class="mb-10 f-14 semibold text-uppercase sp-20">Last Name</div> {% render_field form.last_name type="text" name="lastname" required="required" class="input w-full … -
Follow a log file in Django
I am trying to provide a live log mechanism for each ongoing execution on the dashboard. After doing some workout I've found the below code working but when I put this on production, it worked for some time but now if someone clicks on it don't show any live log but just a blank screen. urls.py url(r'^live_log/$', views.stream_response, name="Live console log") views.py @condition(etag_func=None) def stream_response(request): log_file = request.GET.get('filename', None) resp = StreamingHttpResponse( stream_response_generator(log_file), content_type='text/html') return resp def stream_reader(logstream): logstream.seek(0, 1) while True: line = logstream.readline() if not line: time.sleep(2) continue yield line def stream_response_generator(log): yield '''<html><head> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script type='text/javascript' src='/static/assets/js/scroll.js'></script> </head><body onmousedown='scrolled=true;' onmouseup='scrolled=false;' style='background-color:black' id='live_log'>\n''' with open(log, 'r') as logfile: loglines = stream_reader(logfile) for line in loglines: if "-INFO-" in line: yield '''<div style='color:white;font-family:Consolas;font-size:14'> <script type="text/javascript">update()</script>%s</div>\n ''' % line time.sleep(.05) elif "-ERROR-" in line: yield '''<div style='color:red;font-family:Consolas;font-size:14'> <script type="text/javascript">update()</script>%s</div>\n''' % line time.sleep(.05) yield "</body></html>\n" html code <td>{% if row.execution_log %} <a href="/live_log/?filename={{ row.execution_log }}"> <i class="fas fa-terminal fa-lg"></i> </a>{% else %}Unavailable {% endif %} </td> Please let me know how can I follow the log stream for each user execution and also if some other details are required. Many thanks :) -
Django project TypeError: argument of type 'WindowsPath' is not iterable
This error I'm getting and I'm unable to load my static files (css,javascript and images) Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\Dell\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Dell\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Dell\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 341, in run_from_argv connections.close_all() File "C:\Users\Dell\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\utils.py", line 230, in close_all connection.close() File "C:\Users\Dell\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\Dell\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 261, in close if not self.is_in_memory_db(): File "C:\Users\Dell\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 380, in is_in_memory_db return self.creation.is_in_memory_db(self.settings_dict['NAME']) File "C:\Users\Dell\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\sqlite3\creation.py", line 12, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'WindowsPath' is not iterable -
How can I model the "popularity" concept in code?
I am building a tags Django application to display a feed of tags ranked by "popularity." Currently, my Tag model in models.py looks like this: class Tag(models.Model): tag = models.CharField(max_length=64, unique=True) slug = models.SlugField(max_length=64, unique=True) Ultimately, I would like to query tags in my index view in views.py kind of as follows: def index(request): context = {"tags": Tag.objects.order_by("popularity")} return render(request, "tags/index.html", context) How can I model the "popularity" concept in code? Should I add a popularity field to the Tag model and basically count how many times a tag has been used, or is there a better, slicker way to achieve the same result? -
Django REST framework: get field of related model in serializer
I'm new to Django Rest Framework. I'm trying to get my ListAPI to show various fields of my Quiz (and related) models. It's working fine, except for my attempt_number field. I'm getting the right queryset, but I'm not sure how to get only the relevant value for every query. My model setup is as follows: class Quiz(models.Model): title = models.CharField(max_length=15) slug = models.SlugField(blank=True) questions_count = models.IntegerField(default=0) class Question(models.Model): quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) label = models.CharField(max_length=1000) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.CharField(max_length=100) is_correct = models.BooleanField('Correct answer', default=False) class QuizTaker(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) correct_answers = models.IntegerField(default=0) completed = models.BooleanField(default=False) attempt_number = models.PositiveIntegerField(default=0) My serializer for the ListAPI looks as follows: class MyQuizListSerializer(serializers.ModelSerializer): attempt = serializers.SerializerMethodField() # etc.. class Meta: model = Quiz fields = "__all__" def get_attempt(self, obj): try: quiztaker = QuizTaker.objects.filter(user=self.context['request'].user, quiz=obj) for attempt in quiztaker: attempt_number = attempt.attempt_number return attempt_number If I do it like this, I always get the last value for attempt_number (because the loop overwrites the value). So then I tried to append it to a list instead, like this: a = [] for attempt in quiztaker: attempt_number = attempt.attempt_number a.append(attempt_number) return a But then I get the list … -
NameError : name 'os' is not found
I m getting this error in Django when I run the command Python manage.py collect static Error found - STATIC_ROOT = os.path.join(BASE_DIR, 'static') NameError : name 'os' is not found And I already import os what can I do, I am new in Django please help me. Thanks in advance.