Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Image upload not POSTing
I am trying to let a user upload and change their picture. Currently the form displays the current picture for the user without any issues, but I seem to have messed something when it comes to the upload part since the upload is not working (no error messages). Also, is it possible to create a custom image form? Currently, this makes use of Djangos default one which is not that style-friendly. Views.py @login_required def edit(request): if request.method == "POST": FormImage= UserProfileForm(request.POST, request.FILES, instance=request.user) if FormImage.is_valid(): FormImage.account_id = request.user.id FormImage.save() return HttpResponseRedirect(request.path_info) else: imageForm = UserProfileForm(instance=request.user) return render(request, 'accounts/info.html', { "FormImage": FormImage, }) Forms.py class UserProfileForm(UserChangeForm): FRUIT_CHOICES = ( ('Banana', 'Banana'), ('Orange', 'Orange'), ('Apple', 'Apple'), ) fruits = forms.CharField(widget=forms.Select(choices=FRUIT_CHOICES)) class Meta: model = Account fields = ( 'fruits', 'profile_picture', ) Template <form method="POST" action="" enctype="multipart/form-data"> {% csrf_token %} <label class="col-lg-3 col-form-label form-coantrol-label">Change picture</label> <div class="col-lg-9"> {{ FormImage.profile_picture }} </div> <div class="form-group row"> <div class="container"><input class="btn btn-primary" type="submit" value="Save profile"></div> </div> </form> My model field for profile pic profile_picture = models.ImageField(default="default.png", null=True, blank=True) -
How register and login in django in same time with class based views?
I have a simple registration view, i want to create a view can register user and login him at same time. my code not working, what should do i do to do it? my views.py: class user_register(SuccessMessageMixin,CreateView,): model = User template_name = 'register.html' success_url = reverse_lazy("company:home") form_class = UserRegisterationForm success_message = "You registered successfully." def form_valid(self,form): user = authenticate(username=form.cleaned_data.get('username'),password=form.cleaned_data.get('password')) if user is not None: login(self.request,user) return redirect('company:home') return super().form_valid(form) -
How to pass the product id dynamically to the Django view?
How to change (id=3) automatically? When I click on a product to get a detailed view, the slug in the url is correct, but the displayed data doesn't match. views.py works fine: def product_detail_view(request, slug_text): obj = Product.objects.get(id=3) context = { 'object': obj } return render(request, 'store/product.html', context) urls.py works fine: urlpatterns = [ path('<slug:slug_text>/', views.product_detail_view, name ="product"), ] -
Duplicated querysets in each view - django
I have a few querysets that I need in each of my view. I'm wondering if there is a better way that duplicating those in every single view. Querysets results are the same for every view They look like this Company_user = Company.objects.get(User = request.user) User_info = User_info.objects.get(User = request.user) Groups_user = request.user.groups.values_list('name',flat = True) Sales_company = Sales.objects.filter(Company = Company_user) -
Django + https on localhost
I have files of TLS certificate(.crt) and key(.key) How can i add them in settings.py and run localhost with https( it is need to add them as text variables not path to these files)? Thanks in advance! -
python - django extra_context wont show
I have a form in ListView view using FormMixin that form takes a string lastname and querys to take a queryset of Account object, I want that Queryset on my template via extra_context. The form works and I have the queryset that I want, I pass it into self.extra_context and I can see it on console with print BUT it dosent show in my template. Im feeling stacked, please help me if tou can. def post(self, request, *args, **kwargs): form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): lastname = form.cleaned_data['lastname'] lastname = valuateLastname(lastname) self.extra_context['operators'] = Account.objects.filter(is_active=True, department=self.request.user.department, last_name__contains=lastname) print(self.extra_context['operators']) return super(DepartmentFilesListView, self).form_valid(form) In my template I can see anything else is in my self.extra_context but anything Im tried to pass in my form_valid function doesnt shown. It is like my extra_context cant update in this function. -
(Django - Javascript) Timer javascript and datetime python variable in html template
I've found a timer countdown in javascript online and it works fine... I have to pass python variable to it but, although the result is correct, the countdown doesn't run, it shows the correct remaining time but doesn't continue to decrease (at least I refresh the page)... These are my piece of codes: views.py import datetime auction = Auction.objects.get(id=id) endDateFormat = auction.endDate.strftime("%Y-%m-%dT%H:%M:%S") startDateFormat = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S") template.html <script> // Set the date we're counting down to var countDownDate = new Date("{{endDateFormat}}").getTime(); // Update the count down every 1 second var x = setInterval(function() { // Get today's date and time var now = new Date("{{startDateFormat}}").getTime(); // Find the distance between now and the count down date var distance = countDownDate - now; // Time calculations for days, hours, minutes and seconds var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); // Output the result in an element with id="demo" document.getElementById("demo").innerHTML = days + "d " + … -
Django custom command to write a file without debug logging
I have a Django custom command to write csv file. In the code, I use writer = csv.writer(sys.stdout, lineterminator=os.linesep). When I run it with python manage.py write_csv>sample.file, it contains the file content and debug information, like CDLL(libgeos_c.so.1) Library path: 'libgeos_c.so.1' DLL: <CDLL 'libgeos_c.so.1', handle 5609f58baeb0 at 0x7f03df6b2c88> Trying CDLL(libc.so.6) Library path: 'libc.so.6' DLL: <CDLL 'libc.so.6', handle 7f03ea069450 at 0x7f03df6b2b70> System check identified some issues: and also the part of logging: logging.info('finish uploading') is in the file. Is there anything I can do to prevent those debug information write to file? -
Multiprocessing.Pool runs only one process
I have a Django project and I must fill/update the database with data from an external API. For every user, I must update the values for every minute of every day fetched by the external API. As you understand this is a time-consuming process if I pass multiple months. Please note that I make a call for each day, and process the data of the fetched json. After a specific number of requests, I must wait one hour. With all that in mind, I prepared a script that did all the work but it was taking ages to complete so I decided to proceed with multiprocessing. There is a method user_sync(day_list, user) that handles everything and works perfectly. and here are the lines of code that initiate multiprocessing. user_list = User.objects.filter(username__startswith='US') start_date = datetime.datetime(2020, 6, 28, 0, 0, tzinfo=pytz.UTC) end_date = datetime.datetime(2021, 1, 20, 0, 0, tzinfo=pytz.UTC) day_list = create_day_list(start_date, end_date) pool = multiprocessing.Pool() try: part = partial(user_sync, day_list) pool.map(part, user_list) pool.join() except Exception as e: print(e) pool.close() finally: pool.close() print('FINISHED') To my understanding, it should run multiple user_sync methods for every user in parallel but it doesn't Any help or point to the right direction would be much appreciated. -
Why doesn't HTML input type range work in Django
Am trying to play a song with the input type range in html. I made my own music player with HTML and javascript and when django return's a song, javascript handles it and plays it in the player. It loads the songs and even play it but the range doesn't work. I don't think i should use form widgets range since am not trying to submit a form. Am just playing a song. I did the same thing before in Flask and the range worked but in django it's not working. So am no sure if django support input type. I did alot of research i didn't get an answer so am stuck Here are the songs.(When the image is clicked the song plays) {% for song in playlist %} <div class="card" style="width: 17rem; border: none; margin-right: 20px;"> <img src="{{song.song_img.url}}" width="300" height="300" id="img" class="card-img-top" alt="..." onclick="add_data('{{song.id}}','{{song.song_name}}' ,'{{song.song_path.url}}')"> <div class="card-body"> <h5 class="card-text" id="song" ><a href="{{song.song_path.url}}" style="color: black; text-decoration: none; cursor: pointer;">{{song.song_name}}</a></h5> </div> </div> {% endfor %} Here is the html player <div class="own" id="own" style="display: none;"> <div class="buttons"> <div class="prev-track" onclick="prevPlay()"> <i class="fa fa-step-backward fa-2x"></i> </div> <div class="playpause-track" onclick="play()"> <i class="fa fa-play-circle fa-4x" id='pause'></i> </div> <div class="next-track" onclick="nextPlay()"> <i class="fa fa-step-forward … -
UserCreationForm don't return ValidationError
I don't understand why this form don't raise the ValidationError if the input don't contains only letters, what is wrong?, I tried to follow the steps in order to make a custom validation for these inputs but it seems that is not in the right way? class UserRegistrationForm(UserCreationForm): email = forms.EmailField(widget=forms.EmailInput(), help_text='Enter a help text ex: name@example.com') first_name = forms.CharField(widget=forms.TextInput(), help_text='Enter just letters') last_name = forms.CharField(widget=forms.TextInput()) marketing_email = forms.BooleanField(widget=forms.CheckboxInput(), required=False) accept_terms_and_conditions = forms.BooleanField(widget=forms.CheckboxInput()) class Meta: model = User fields = [ 'email', 'username', 'first_name', 'last_name', 'password1', 'password2', 'marketing_email', 'accept_terms_and_conditions' ] error_messages = { 'first_name' : _('First name can contain only letters'), 'last_name' : _('Last name can contain only letters') } def clean_first_name(self): first_name = self.cleaned_data.get('first_name') if not first_name.isalpha(): raise forms.ValidationError( self.error_messages['first_name'], code='first_name_invalid' ) return data def clean_last_name(self): last_name = self.cleaned_data.get('last_name') if not last_name.isalpha(): raise forms.ValidationError( self.error_messages['last_name'], code='last_name_invalid' ) return data template: <div class="form-row"> <div class="form-group col-md-6"> <label for="firstName">First name</label> {% render_field user_update_form.first_name class="form-control" placeholder="John" id="firstName" %} {% for error in user_update_form.first_name.errors %} <small class="text-xs font-weight text-danger">{{ error }}</small> {% endfor %} </div> <div class="form-group col-md-6"> <label for="lastName">Last name</label> {% render_field user_update_form.last_name class="form-control" placeholder="Hanks" id="lastName" %} {% for error in user_update_form.last_name.errors %} <small class="text-xs font-weight text-danger">{{ error }}</small> {% endfor %} … -
Docker + Django + Vue + Nginx configuration not reading CSS or JS files (Ioading wrong MIME type)
I have been working on a project that uses Django REST Framework for an API with an embedded Vue frontend. The Vue frontend is located within the Django project folder and uses Django templates for authentication. I have been trying to get this project working with Docker using Nginx as the server. I have it mostly working but have been struggling with getting the media and static folders to work properly. In my most recent version, Nginx is able to find them but the browser is giving a warning that they are being read as text/html and have the incorrect MIME type. I already have "include /etc/nginx/mime.types" included in my Nginx conf file, attempted to add a location function for css and js but nothing seems to work. My docker-compose file looks like this: version: '3' services: backend: build: context: ./django command: > sh -c "python3 manage.py wait_for_database && python3 manage.py collectstatic --no-input && python3 manage.py makemigrations && python3 manage.py migrate --no-input && gunicorn django.wsgi -b 0.0.0.0:8000" networks: - django-nginx volumes: - ./django:/app - django-static:/django/static - django-media:/django/media environment: - DB_HOST=db - DB_NAME=keeptrackdb - DB_USER=postgres - DB_PASS=postgres depends_on: - db db: image: postgres:10-alpine environment: - "POSTGRES_HOST_AUTH_METHOD=trust" - POSTGRES_DB=djangodb - POSTGRES_USER=postgres - … -
Using Database VIEW statements in Django
Hopefully just a quick question. I am having some difficulty with using Database VIEW statements in Django. I came across Getting the SQL from a Django QuerySet But its seems all those post are outdated. I have a couple of Postgresql VIEW that i want to use them in django. Models.py class Boookshelf(models.Model): title = models.CharField(max_length=100) id = models.IntegerField(primary_key=True) class Meta: managed = False db_table = "bookshelf" I would like the official Django way of doing this if its exist. Whenever i add this code i cant use in my page. Nothings happen. How do i check if its work or not? I think so i missed something here. PS: IN PSPQL side everything is fine and VIEW bookshelf is ready to use. -
Query ManyToMany models to return number of instance of A that are linked to B and reverse?
I have 2 models (Customers and Orders) with a declared throught models (Customers_Orders) to manage manytomany relationship. But I did'nt understand how to query to have : for one Customer, all its orders: How many orders were made by each customer for one Order, all its customers: How many customers were associated for each order class Customers(SafeDeleteModel): customer_id = models.AutoField("Customer id", primary_key = True) orders = models.ManyToManyField(Orders, through = Customers_Orders, related_name = "CustomersOrders") created_at = models.DateTimeField("Date created", auto_now_add = True) class Orders(SafeDeleteModel): order_id = models.AutoField("Order id", primary_key = True) created_at = models.DateTimeField("Date created", auto_now_add = True) class Customers_Orders(SafeDeleteModel): order = models.ForeignKey("Orders", on_delete = models.CASCADE) customer = models.ForeignKey("Customers", on_delete = models.CASCADE) -
if there are instances of method that user created display them else display a string Django
code: views.py: @login_required(login_url='loginPage') def boardPage(request): if Board.objects.filter(user=request.user).exists(): boards = get_list_or_404(Board, user=request.user) context = {'boards': boards} return render(request, 'tasks/boards.html', context) else: context = {'boards': False} return render(request, 'tasks/boards.html', context) boards.html: {% extends 'tasks/main.html' %} {% block content %} <center>board page<hr> <a href="{% url 'boardAdd' %}">add board</a> <br><br> your boards: <br> <br> {% if boards is false %} <p>you don't have any boards... Have you tried creating one? ;)</p> {% else %} {% for board in boards %} <a href="{% url 'insideBoard' board.id %}">{{board}}<br></a> {% endfor %} {% endif %} <br> <br> <hr> <a href="{% url 'logoutPage' %}">Logout</a> </center> {% if messages %} {% for message in messages %} <u><br>{% if message.tags %} {% endif %}>{{ message }}</u> {% endfor %} {% endif %} {% endblock %} models.py: class Board(models.Model): title = models.CharField(max_length=50, null=True) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) def __str__(self): return self.title class Task(models.Model): title = models.CharField(max_length=200, null=True) done = models.BooleanField(default=False, null=True) created_at = models.DateTimeField(auto_now_add=True, null=True) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) board = models.ForeignKey(Board, null=True, on_delete=models.CASCADE) due_to = models.DateField(null=True, validators=[dateValidation]) def __str__(self): return self.title every time user deletes all of his/her boards or new user visits that page (new users doesn't have any boards yet, they are able to create one … -
Add "\n" or "<b>" to select options in Django Forms
I need to display the values of my form with something like this: Telecomunicaciones y Redes\nIngeniería en Informática <p> Telecomunicaciones y Redes <br>Ingeniería en Informática WHAT I WANT Telecomunicaciones y Redes Ingeniería en Informática HOW IT IS RENDERED -
How to do checks on Django form classes
I'm playing with django forms a little, and trying to check if all form fields correspond to a field of a model through name-checking, this is being done in form constructor function, but i find silly to make such a check on every form instance made so, i would like to do so but on form class. I came to think that to attain it i would need models to be loaded first in django and maybe... to listen to a signal and wait for executing the code once they are loaded, but this is just a suposition. Is there a way to do it??. Any help is welcome. What you'll below on the code section is a form with a basic filtering functionality. FORM CODE : class NoticeFilter(forms.ModelForm): name = forms.CharField(max_length=12, required=False) def checkfields(self): #Check that the form fields are a subset of the model fields #Granting that every field defined here corresponds only to a model field #and has its same name, no aditional input. list_ = [] field_names = set(boundfield.name for boundfield in self) for model_field in self.__class__.Meta.model._meta.get_fields(): list_.append(model_field.name) set(list_) if field_names.issubset(list_): print('You are good to go') else: print('You have one or more fields whose name doesnt … -
Separating development/staging/production media buckets on S3 in Django
We are currently using AWS S3 buckets as a storage for media files in a Django 1.11 project (using S3BotoStorage from django-storages library). The relevant code is here: # storage.py from storages.backends.s3boto import S3BotoStorage class MediaRootS3BotoStorage(S3BotoStorage): """Storage for uploaded media files.""" bucket_name = settings.AWS_MEDIA_STORAGE_BUCKET_NAME custom_domain = domain(settings.MEDIA_URL) # common_settings.py DEFAULT_FILE_STORAGE = 'storage.MediaRootS3BotoStorage' AWS_MEDIA_STORAGE_BUCKET_NAME = 'xxxxxxxxxxxxxxxx' MEDIA_URL = "//media.example.com/" # models.py import os import uuid from django.db import models from django.utils import timezone from django.utils.module_loading import import_string def upload_to_unique_filename(instance, filename): try: extension = os.path.splitext(filename)[1] except Exception: extension = "" now = timezone.now() return f'resume/{now.year}/{now.month}/{uuid.uuid4()}{extension}' class Candidate(models.Model): [...] resume = models.FileField( storage=import_string(settings.DEFAULT_PRIVATE_FILE_STORAGE)(), upload_to=upload_to_unique_filename, ) [...] The issue is that the bucket key is hardcoded in the settings file, and since there are multiple developers + 1 staging environment, all of the junk files that are uploaded for testing/QA purposes end up in the same S3 bucket as the real production data. One obvious solution would be to override AWS_MEDIA_STORAGE_BUCKET_NAME in staging_settings.py and development_settings.py files, but that would make the production data unavailable on staging and testing instances. To make this work, we would somehow how to sync the production bucket to the dev/staging one, which I'm unsure how to do efficiently and … -
I learned Django for Python but hate making it look pretty. Need ideas
So, I learned Django. I'm fine with creating the view controller but hate making the looks of an app. I can make animations and stuff, just not the looks. I know this sounds stupid, but I want to freelance mobile dev. Is there any, and I mean ANY ideas you guys have for this? Is there a UI designer or something that you can convert to code? -
Django Admin CSS files is Broken on Plesk
i have problem with Django amdin CSS files. i'm using Plesk. i add static root and static url in settings.py and after that run command manage.py collecstatic, but still my admin dont have css files. please help me. STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') -
(Django - Python) Problems with timedelta saving form
I have a problem with my auction site because when I publish an auction the function doesn't save my variable correctly, these are my codes: views.py import datetime from datetime import timedelta def publishAuction(request): user=request.user form = auctionForm(request.POST, request.FILES) if request.method=="POST": if form.is_valid(): auction=form.save(commit=False) auction.advertiser=user auction.startDate=datetime.datetime.now() auction.endDate=auction.startDate+timedelta(days=1) auction.endPrice=request.POST.get("startPrice") auction.save() return redirect("../") else: form=auctionForm() models.py class Auction(models.Model): advertiser = models.ForeignKey(User, on_delete=models.CASCADE, related_name='auction_advertiser', null=True) winner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='auction_winner', null=True) title = models.CharField(max_length=30) text = models.TextField() startPrice = models.FloatField(null=True) endPrice = models.FloatField() status = models.BooleanField(default=True) image = models.ImageField(upload_to='images/') startDate = models.DateTimeField(auto_now=False, auto_now_add=True) endDate = models.DateTimeField(auto_now=False, auto_now_add=True) The publication is done correctly, everything except endDate that is always equal to startDate... I have tried also with datetime.datetime.now instead of auction.startDate or datetime.timedelta(days=1) but when I get the value in the shell is always the same... In the scratch.py file I write the same codes and it works, I don't know why doesn't work in the function... :S Thanks to everyone! -
TypeError Posting from React Native to Django Rest API (Server 500 Error)
The error I am receiving is is a 500 server error: TypeError: 'Habit' object does not support item assignment found in the debug log of my Django App. (Habit is the name of the model connected with a Foreign Key in the Post model) I have a React Native app where I post data using fetch. An example of a post that works: Serializers.py from rest_framework import serializers from .. import models class EFHabitMeasSerializer(serializers.ModelSerializer): class Meta: model = models.HabitMeasurement fields = ('id','habit_record','habit','reply','created') Views.py from rest_framework import viewsets from .. import models from . import serializers from rest_framework import permissions class EFHabitMeasViewset(viewsets.ModelViewSet): def get_queryset(self, *args, **kwargs): return models.HabitMeasurement.objects.order_by('-created') serializer_class = serializers.EFHabitMeasSerializer Models.py class HabitMeasurement(models.Model): habit_record = models.ForeignKey(HabitRecord, on_delete=models.CASCADE, related_name='habitmeasurements') habit = models.ForeignKey(Habit, on_delete = models.CASCADE, related_name="habitsentered") REPLY_CHOICES = (("Yes","Yes"),("No","No")) reply = models.CharField(max_length = 10, choices=REPLY_CHOICES, default = 1) created = models.DateTimeField() slug = models.SlugField(max_length=200, allow_unicode=True, unique=True, blank=True) def save(self, *args, **kwargs): created_slug = str(self.habit_record) +'-'+ str(self.habit) +'-'+ str(self.created) self.slug = slugify(created_slug) super().save(*args, **kwargs) def __str__(self): return '[{}] {} {} taken on {}'.format( self.habit_record, self.habit, self.reply, self.created ) class Meta: ordering = ['-created'] The Function submitYes = () => { fetch(`${this.props.enemies.internet}/api/habit_measurements/`, { method: "POST", headers: { // "Accept": "application/json", "Content-Type": "application/json", // … -
Unkown Column error on django admin, how to fix it?
i have an error in my django admin: (1054, "Unknown column 'flora2estado.id' in 'field list'") the model flora2estado has two fields, they are used in unique together as a pseudo composite key, how can i fix this? admin.py admin.site.register(Flora2Estado) models.py estado = models.OneToOneField(Estados, models.DO_NOTHING, primary_key=True) especie_id = models.IntegerField() flora2estado = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'flora2estado' unique_together = (('estado', 'especie_id'),) I tried to add the "flora2estado" field without sucess. All migrations done, thank you for your time -
divide django form fields to two divs
hi guys i have a form with a checkbox that if checked needs to display an additional bunch of fields, is it possible to tell the form to wrap some fields in one div and the rest in another div? this way I can play around client-side with javascript, I also want to do it client-side for styling purposes, any help will be greatly appreciated thanks in advance -
In settings.py, how should environment variables be loaded/set if they're only used in one environment?
I have a Django application where I'm handling environment variables using python-decouple and separate .env files. This works fine for variables that exist in both development and production environments, such as DEBUG. SECRET_KEY = config('SECRET_KEY') DEBUG = config('DEBUG', cast=bool) ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv()) While DEBUG has distinct values in each environment, other variables like SECURE_HSTS_SECONDS only need to be set in production and do not need to be set at all in development. I'm currently just hard-coding these values in my settings.py file: if not DEBUG: SECURE_HSTS_SECONDS = 60 SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_REFERRER_POLICY = 'same-origin' SECURE_HSTS_PRELOAD = True SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True I suppose I could include these values in my dev .env file and just set them to their default values, but that seems unnecessary. Is there a cleaner way to implement this or a best practice?