Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python/HTML: Using form inputs as variable, submit form and print output in HTML file
I am a beginner in Python. I have created a Python script that requires two variables to be entered as input that works without problem. I have created a Django project and I intend to have an HTML page with a form with two input and a submit button. When the submit button is pressed, the script should run with the two form inputs as variables. Then the output from the script should be printed in a separate HTML page. I have read about views, httpresponse, websockets... As I said, I am an almost complete beginner to Python so every bit of help is appreciated! Thanks! -
Django audio, video and image upload
I have trying to solve this problem for so long somebody please please please help me. So I am a newbie I'm django and I am learning it. I made an app where you can upload files. I have used the filefield in my models but the problem is if I want to upload a image file I have to use the img tag in html and if I want to upload a video I have to use the video tag and similarly for audio I have to use the audio tag but the problem is if I upload a video it won't show in img tag and vice versa. So how do I make that the user just upload a file and it automatically use the required tag in html just like instagram, you can upload video audio image. If any one knows anything please help please please please. -
Creating a Serializer to work with model relationships
I am new with Django Rest Framework and wanted to understand what's the accepted practice for writing Serializers that work with nested relationships. Say, I have a models called Client and Invoice (this is just an illustrative example): class Client(models.Model) name = models.CharField(max_length=256) class Invoice(models.Model) client = models.ForeignKey(Client) date = models.DateTimeField() amount = models.DecimalField(max_digits=10, decimal_places=3) I want to create a Serializer for Client that supports the following use cases: Create a Client When I create an Invoice, refer to the Client using its id. Let's say I use this implementation: class ClientSerializer(serializers.ModelSerializer): class Meta: model = Client fields = ['id', 'name'] class InvoiceSerializer(serializers.ModelSerializer): client = ClientSerializer() class Meta: model = Invoice fields = ['id', 'client', 'date', 'amount'] def create(self, data): client = Client.objects.get(pk=data['client']['id']) invoice = Invoice(client=client, date=datetime.fromisoformat(data['date']), amount=Decimal(data['amount'])) invoice.save() With this code, if I try to create an Invoice, I need the client object in the POST data to contain name as well. There is no config of the name field (read_only=True, write_only=True, required=False) that allows me to create and read Client as well as not be required when creating the Invoice. How should this be solved? Is the accepted practice that the request include the name field anyways? Can … -
Image files upload to AWS S3 Bucket, but don't render on django heroku App
I have a Django webapp that is hosted on Heroku. The site functions perfectly except or the image rendering. I am using AWS S3 buckets. How my images currently look. This is the output when right click and view image in a new tab This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>InvalidRequest</Code> <Message> The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256. </Message> <RequestId>B965F49FC9AD8BD8</RequestId> <HostId> NyDkC2+pLPd/5tzWgJb+dEJOWu7eNCfbVyqLdZWOr1JyIFTe6rZ8BbRJHlbweCLU1MJ7xmlrxEM= </HostId> </Error> Settings.py import os import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # (os.environ.get('DEBUG_VALUE') == 'True') ALLOWED_HOSTS = ['xxx.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'users.apps.UsersConfig', 'blog.apps.BlogConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_cleanup', 'taggit', 'hitcount', 'storages', ] *************** *************** # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' CRISPY_TEMPLATE_PACK = 'bootstrap4' LOGIN_REDIRECT_URL = 'blog-home' LOGIN_URL … -
Is it possible to call as_view from the controller?
Is it possible to call the as_viev() method of class from the controller? I need to pass a variable that is initialized in the controller. It looks like routing urlpatterns = [ path('form/check/', room_check, name='room_check'), path('contact/', BookWizard.as_view(FORMS, initial_dict=initial)), ] Book Wizard - a class inherited from SessionWizardView from 'formtools' module The following is a piece of the controller where the variable is created initial = { '0': {'check_in_date': check_in_date, 'date_of_eviction': date_of_eviction, 'category': category, 'number_of_adults': number_of_adults, 'number_of_children': number_of_children}} return redirect(BookWizard.as_view(FORMS, initial_dict=initial)) As a result, I get this error: error Maybe there is another way to pass the variable and call the method? -
Django,referring objects with double underscore
I have a function in the view file of Django Rest Framework project. Where it filters out comments (A model) with related to the specific Post class CommentListCreate(APIView): def get(self, request,pk): comment = Comment.objects.filter(post_id=pk) serializer = CommentSerializers(comment, many=True) return Response(serializer.data) The above function is able to filter according to the post_id, but if I change filter arguments as mention below def get(self, request,pk): comment = Comment.objects.filter(post__id=pk) The function works fine, why do we use double underscore to refer the the post id ? Git Link to my views.py https://github.com/Anoop-George/DjangoBlog/blob/master/blog/views.py -
Django, how to calculate monthly salary from constraints
I have the following models.py: class PersonaleDipendente(models.Model): start=models.DateField end=models.DateField monthly_salary=models.DecimalField monthly_number=models.DecimalField I want to obtain a queryset that yearly calculate the monthly salary ( given by the following formula monthly_salary*monthly_number/12) taking into account the start and end date. Just an example: If the data are the following: start=1/10/2020 end=1/08/2020 monthly_salary=100 monthly_number=12 the queryset will be: [100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 100.0, 0, 0, 0, 0] I have tried the following code but does not give me the result wanted. for year, month, totale in (PersonaleDipendente.objects.values_list('start__year', 'start__month').annotate(totale=ExpressionWrapper(Sum(F('monthly_number')*F('monthly_salary')/12), output_field=FloatField())).values_list('start__year', 'end__month', 'totale')): personale_dipendente=list(defaults) index=month-1 personale_dipendente[index]=totale -
How to make use of Django's security features (i.e. CSRF) with TokenAuthentication in Django Rest Framework
I am currently building my app with TokenAuthentication (can I use SessionAuthentication instead for a seperate SPA, I didn't fully understand that part of the documentation, but it sounds like SessionAuthentication should only be used for XHR coming from websites, where the frontend is served by Django). I have heard that there are several security issues with just storing the token in a cookie and calling it a day. So my goal is to have persistent sessions (my users don't have to login each time they visit my site) and to protect myself against attacks (I am thinking of CSRF, XXS and CORS, am I missing some?). To solve the first problem, I had the idea of storing the token in a secure Http-Only cookie (and sending it therefore automatically with every request to the backend). I already found a solution to this here: Django-rest-auth use cookie instead of Authorization header Now what I'm wondering is: Am I using the correct approach, is there some easy way that I'm missing/haven't heard about? How would I go about securing my site against CSRF and XXS when using TokenAuthentication? I've read the official documentation about this, but not getting much sense out … -
how to use SQL connection string class in python
i want to create a class which maintain sql connection instead of creating sql connection everytime. models.py in models.py i declare sql connection in sqlconn method whenever i call this i want to establish sql connection in views.py from django.db import models import pyodbc def sqlconn(request): constr = "DRIVER={SQL Server};SERVER=localhose;DATABASE=testdb;UID=user;PWD=password" conn = pyodbc.connect(constr) return conn Views.py in this views.py i'm retrieving employee data from database instead of writing sqlconnection string in every views.py method. I want to call sqlconn method from models and i want to do further process like getdata, insertdata, deletedata, updatedate from django.shortcuts import render from .models import sqlconn import pyodbc def getEmpData(request): conn = sqlconn cursor = conn.cursor() #cursor.execute("select * from Employee") cursor.execute("exec sp_demotable") result = cursor.fetchall() return render(request, 'getempdata.html', {'result':result}) i tried above code but its not working its showing error, any help thanks in advance Note: what is the best practices for python any articles are videos tutorials provide its great help for me, because i'm new to python but i've good knowledge in .NET Programming -
trying to applying DRY principle to model methods in django
I have these two methods that are identical except in name and one variable, and it really bugs me, but no matter what I do, I can't figure out how make it so that I just pass a variable into a method in django. These are the two methods, I can post the model if it's needed but I'm fairly sure all the info that is needed is in here, but for clarity, the two model fields are 'launch', 'staff_trials' and 'published' all three are just dates, all other variables are created in the method: @property def progress_launch(self): timeline = self.launch - self.published.date() current = self.launch - datetime.now().date() if timeline < current: percentage == 100 else: percentage = 100 - round((current/timeline) * 100) min_bar = 1 max_bar = 100 if percentage is not None: if percentage < min_bar: return min_bar elif percentage > max_bar: return percentage else: percentage = max_bar return percentage @property def progress_trials(self): timeline = self.staff_trials - self.published.date() current = self.staff_trials - datetime.now().date() if timeline < current: percentage == 100 else: percentage = 100 - round((current/timeline) * 100) min_bar = 1 max_bar = 100 if percentage is not None: if percentage < min_bar: return min_bar elif percentage > … -
Modal Formbuilder for wagtail?
Hello im new to wagtail and its been really awesome so far. However im facing an issue trying to create a modal version of the formbuilder. My intentions is to create an action button within the base.html of which the user can click at any point in time and enter a modal pop up form to leave a feed back . Is there a way of accomplishing this? -
Django ORM join without FK on aggregated table
I am trying to write an ORM query to join a table with itself after aggregation (Hence select_related etc won't work). The simple SQL query is with table transaction with fields (account_id, amount, booking_date, reference, ...) select * from transaction t join (select account_id, sum(amount) as total_amount from transaction where amount > 0 group by account_id) aggr on t.account_id = aggr.account_id where amount > 0.4 * total_amount; So far no luck. I even tried the join_to/CustomJoin from Django ORM. Joining subquery, but this didn' work. -
How to substitute data from another model into the form?
I want the data from another model that I identified by "id" to be substituted into the form and substituted in the url to go to the page with the form in which the data from the model field that I identified by "id" will be inserted form.py class AdmissionForm(forms.ModelForm): class Meta: model = Admission fields = ['date', 'name', 'admission'] class EquipmentWorkersForm(forms.ModelForm): class Meta: model = EquipmentWorkers fields = ['date', 'id_admission', 'id_type', 'id_workers', 'id_room'] views.py class AssignToWorker(View): def get(self, request, admission_id): admission = Admission.object.get(id=admission_id) form = EquipmentWorkersForm(instance=admission) return render(request, 'inventory/assignToWorker.html', context={'form': form, 'admission': admission}) def post(self, request): form = EquipmentWorkersForm(request.POST) if form.is_valid(): form.save() return redirect(equipments_list) return redirect(relocation_list) url.py path('assignToWorker/<str:admission_id>/', AssignToWorker.as_view(), name='assign_to_worker_url'), -
Tinye MCE and Django: HTMLField toolbar options (admin)
I have a Djando App running, I added a new simple Model with an order and a content field, the content is of type HTMLField, I manage to edit the field's content and format it just fine, my problem is that I need to be able to add bulleted lists in that field and I cannot find the way to tweak Tiny MCE's configuration to make it happen. I have tried to add tiny_mce.js file along with another js file with the parameters, and add a TINYMCE_DEFAULT_CONFIG section to config.py, but it's not working at all, I'm BTW new to Django and Python I'd appreciate if someone could give me a guide to be able to handle the Tiny MCE toolbar options from zero Thanks in advance! -
Django problem with creating instance of model basing on pre_delete signal
I have a model which represents the archives. Once the main advert has been deleted, it's archives version is being created to later view. I wanted to acomplish it basing on signals. I believe my code is correct but for some reason it does not launch signals. signals.py from django.db.models.signals import post_save, post_delete, pre_delete from django.dispatch import receiver from core.models import Advert, Archive @receiver(pre_delete, sender=Advert) def archive_advert(sender, instance, **kwargs): archives = Archive.objects.create(user=instance.user, title=instance.title, category=instance.category, price=instance.price, quantity=instance.quantity, description=instance.description, image=instance.image) models class Archive(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(blank=True, null=True, max_length = 100) category = models.CharField(blank=True, null=True, max_length = 3) price = models.FloatField(blank=True, null=True) quantity = models.IntegerField(blank=True, null=True) description = models.TextField(blank=True, null=True, max_length = 1000) posted = models.DateTimeField(blank=True, null=True) image = models.ImageField(blank=True, upload_to="advert_images") apps.py class CoreConfig(AppConfig): name = 'core' def ready(self): import core.signals -
How to create a form for dealing with multiple django model objects
So I have a model Post with the following definition: class Post(models.Model): post_body = models.TextField() user = models.ForeignKey( to=User, on_delete=models.CASCADE ) published = models.BooleanField( default=False ) schedule = models.DateTimeField( default=timezone.now ) I have created a form in HTML template allowing the user to select the posts he want to send to another website or social media account. Like so: <form> <table class="table table-hover"> <thead> <tr> <th scope="col">Select</th> <th scope="col">Post Body</th> <th scope="col">Published?</th> <th scope="col">Schedule (Editable)</th> </tr> </thead> <tbody> {% for post in posts %} <tr> <td> <div class="form-group"> <input type="checkbox" value="{{ post.id }}"> </div> </td> <td>{{ post.post_body }}</td> <td>{{ post.published }}</td> <td> <div class="form-group"> <input type="datetime-local" class="form-control" name="schedule" value="{{ post.schedule|date:"Y-m-d\TH:i" }}"> </div> </td> </tr> {% endfor %} </tbody> </table> <button class="btn btn-primary" type="submit">Post</button> </form> I want to create a Form in the forms.py in order to process this information (i.e. know which all posts were selected) and then perform further actions (calling other APIs in order to publish these to other sites), also since the field schedule is editable, I want to be able to save that as well. Please help as I cannot think of a possible form for this. -
Inherit models whith seperate primary key in django model
I have a abstract model which I want all of my models inherit from it: from django.db import models class Audit(models.Model): create_date = models.DateTimeField(auto_now_add=True) last_modify_date = models.DateTimeField(auto_now=True) create_by = models.CharField(null=True, max_length=50) last_modify_by = models.CharField(null=True, max_length=50) class Meta: abstract: True now fro example I have two models: from general.AuditableModel import Audit class Province(Audit): name = models.CharField(max_length=30) class Meta: db_table = 'province_v2' verbose_name_plural = _('provinces') verbose_name = _('province') class City(Audit): province_id = models.ForeignKey('address.Province', on_delete=models.CASCADE, related_name='cities') name = models.CharField(max_length=30) class Meta: db_table = 'city_v2' verbose_name_plural = _('cities') verbose_name = _('city') in my database it makes tables like this: create table province_v2 ( audit_ptr_id integer not null primary key references general_audit deferrable initially deferred, name varchar(30) not null ); create table city_v2 ( audit_ptr_id integer not null primary key references general_audit deferrable initially deferred, name varchar(30) not null, province_id_id integer not null references province_v2 deferrable initially deferred ); create index city_v2_province_id_id_12975070 on city_v2 (province_id_id); but I want my models have independent id integer primary key without abstract table, now it made general_audit table -
Django - 'WSGIRequest' object has no attribute 'get' when rendering the form
I'm working on a question management system. I have two different types of questions which make things a little more complicated. I have a page where every question is listed and I'm making the question detail page. When I access this page, I have this 'WSGIRequest' object has no attribute 'get' error. My models : import uuid from django.db import models from django.contrib.auth.models import User class Question_Num(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) num_question = models.IntegerField(default=0) question = models.TextField(max_length=1000, unique=True) reponse = models.IntegerField(default=0) class Meta: verbose_name = 'Question' verbose_name_plural = 'Questions' def __str__(self): return f'Question n°{self.num_question}' class QCM(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) num_question = models.IntegerField(default=0) question = models.TextField(max_length=1000, unique=True) choix_1 = models.CharField(max_length=200, unique=True, default='') choix_2 = models.CharField(max_length=200, unique=True, default='') choix_3 = models.CharField(max_length=200, unique=True, default='') choix_4 = models.CharField(max_length=200, unique=True, default='') class Meta: verbose_name = 'QCM' verbose_name_plural = 'QCM' def __str__(self): return f'QCM n°{self.num_question}' My forms : from django import forms from django.contrib.auth.models import User from .models import Question_Num, QCM class Modif_QCM(forms.ModelForm): num_question = forms.IntegerField( initial = QCM.num_question ) question = forms.IntegerField( initial = QCM.question ) choix_1 = forms.IntegerField( initial = QCM.choix_1 ) choix_2 = forms.IntegerField( initial = QCM.choix_2 ) choix_3 = forms.IntegerField( initial = QCM.choix_3 ) choix_4 = forms.IntegerField( initial = … -
I'm Working on a django project where i extended the auth_user table for add the operators and this will give an error
MY HTML CODE === This is my html code for adding the operator in the database {% extends 'Adminside/master.html' %} {% block content %} <div class="col-md-12"> <!-- general form elements --> <div class="card card-primary"> <div class="card-header"> <h3 class="card-title">Add Operator</h3> </div> <!-- /.card-header --> <!-- form start --> <form role="form" action="{% url 'addoperator' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="card-body"> <div class="form-group"> <label for="exampleInputEmail1">Name</label> <input type="text" class="form-control" id="exampleInputname" name="name" placeholder="Enter Your Name"> </div> <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <input type="email" class="form-control" id="exampleInputEmail1" name="email" placeholder="Enter email"> </div> <div class="form-group"> <label for="exampleInputPassword1">Password</label> <input type="password" class="form-control" id="exampleInputPassword1" name="password" placeholder="Password"> </div> <div class="form-group"> <label for="exampleInputEmail1">Address</label> <input type="text" class="form-control" id="exampleInputaddress" name="address" placeholder="Enter Your Address"> </div> <div class="form-group"> <label for="exampleInputEmail1">Phone Number</label> <input type="text" class="form-control" id="exampleInputnumber" name="number" placeholder="Enter Your Phone Number"> </div> <div class="col-sm-6"> <!-- radio --> <div class="form-group clearfix"> <div class="icheck-primary d-inline"> <input type="radio" id="radioPrimary1" name="gender" value="Male" checked=""> <label for="radioPrimary1"> Male </label> </div> <div class="icheck-primary d-inline"> <input type="radio" id="radioPrimary2" value="Female" name="gender"> <label for="radioPrimary2"> Female </label> </div> <div class="icheck-primary d-inline"> <input type="radio" id="radioPrimary3" disabled=""> Gender </label> </div> </div> </div> <div class="form-group"> <label for="exampleInputFile">Image Upload</label> <div class="input-group"> <div class="custom-file"> <input type="file" name="userimage" class="form-control" required> </div> </div> </div> <div class="form-group"> <label for="exampleInputFile">Document Upload</label> <div class="input-group"> <div class="custom-file"> <input type="file" … -
Remove title of the data from Django Rest Frame
I have this models.py class Topologies(models.Model): topology = models.CharField(max_length=50) component = models.CharField(max_length=50) latency = models.FloatField() capacity = models.FloatField() time = models.CharField(blank=True, max_length=10) def __str__(self): return self.topology And this serializers.py class Last10TopoTime(serializers.ModelSerializer): class Meta: model = models.Topologies fields = ('latency', 'capacity') The output is this: [ { "latency": 19.218, "capacity": 0.048 }, { "latency": 19.218, "capacity": 0.054 }, { "latency": 19.219, "capacity": 0.054 } ] But I only want this [ { 19.218, 0.048 }, { 19.218, 0.054 }, { 19.219, 0.054 }, I don't have any articles on this can anyone suggest anyway show that I can do it. -
How to get the data from BoundField?
I would like to get the number 2 from my BoundField object, that's problematic because it is not iterable or doesnt support indexing. <BoundField value=2 errors=None> Can someone please help? -
Searching through a ManyToManyField in Django
I have a model that contains a ManyToManyField. It looks like this.. applicable_events = models.ManyToManyField(Event) I am trying to basically search using something like this: if 'Video' in prop.applicable_events.all(): print("here") But it isn't fully working as I expected. I want it to search that applicable_event (which is another model). The applicable_event model contains a field named 'name' which I am trying to search against. If I do something like this print(prop.applicable_events.all().filter(name=cur_event)) It prints <QuerySet [<Event: Video Sign In Started>]> So basically I am trying to find out if the string 'Video' is contained in that. -
Unexpected Behaviour of PasswordResetView which sends too many consecutive emails
My Django 3.0 Project is using the default Django Reset Password view, so in my url.py: path('password_reset', auth_views.PasswordResetView.as_view(), name='password_reset') There is a strange behaviour because when I request reseting the password, the view sends a lot of emails to the email address I introduced (let´s say 37 emails). This happened regardless using SendGrid or AWS SES, so something wrong is happening in the view. I investigated and I think the problem is in the PasswordResetForm class which the view uses to send emails. Such form has a get_users() method, which return matching user(s) who should receive a reset, it retrieves all the active users who provided the email. def get_users(self, email): """Given an email, return matching user(s) who should receive a reset. This allows subclasses to more easily customize the default policies that prevent inactive users and users with unusable passwords from resetting their password. """ email_field_name = UserModel.get_email_field_name() active_users = UserModel._default_manager.filter(**{ '%s__iexact' % email_field_name: email, 'is_active': True, }) return ( u for u in active_users if u.has_usable_password() and _unicode_ci_compare(email, getattr(u, email_field_name)) ) The save() method of the form sends an email to each of the users returned by get_users(). I think my problem is that I registered several users … -
change the language attrib in HTML tag based on user's language Django Wagtail
how to change the language attribute <html class="no-js" lang="en"> in HTML tag based on user's language dynamically? in .. Django & #Wagtail templates -
Django 3 - What is the method for creating list and Django detail view urls with stub or slug of name and not int of pk?
In Django 3 what is the correct method for creating list and detail view with friendly urls with either a stub or slug of name and not a int of pk? stub versus slug for list and detail view I want to be able to use list and detail view with a readable urls more friendly then number or int? I tried a variety of tutorials but they all seam to use different methods like url, path, re path, include, reverse, reverse lazy etc. I have been able to do using urls patterns something like this but is the int method r'^starwars/(?P<pk>\d+)$' I am trying to do something like this. it will be using a template inheriting from a base template for both list and detail views. ``` http://127.0.0.1:8000/ #as homepage http://127.0.0.1:8000/starwars/ #as list of series http://127.0.0.1:8000/starwars/the_mandalorian/ # page is detailed view with list of the mandalorian characters ``` Instead of http://127.0.0.1:8000/ #as homepage http://127.0.0.1:8000/starwars/ #as list of series http://127.0.0.1:8000/starwars/1/ path to templates Project_folder |_ starwars |_ templates |_ starwars |_ starwars_base.html starwars_detail.html starwars_list.html ------ Settings.py ------- I add the template directories here like this in two places # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = …