Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how do i properly include a template inside another template in django
i am trying to include a template(header.html) from another view into another template(index.html) that has another view but nothing seems to display from the header section when i load the page heres the views.py from django.contrib.auth import get_user_model from django.views.generic import TemplateView, ListView from baykay.models import Projects, Profile User = get_user_model() class HomeView(TemplateView): template_name = 'portfolio/index.html' class Header(ListView): template_name = 'portfolio/header.html' model = Profile context_object_name = 'header' here is the header.html <div class="container clearfix"> {% for profile in object_list %} {% if profile.image %} <img class="profile-image img-fluid float-left avatar-img" src="{{ profile.image.url }}" alt="young-baykay"/> {% endif %} <div class="profile-content float-left"> <h1 class="name">{{ profile.user.get_full_name|title }}</h1> <h2 class="desc">{{ profile.profession|title }}</h2> </div><!--//profile--> {% endfor %} <a class="btn btn-cta-primary float-right" href="#" target="_blank"><i class="fas fa-paper-plane"></i> Contact</a> </div> here is the index.html <!DOCTYPE html> <html lang="en"> <head> {% include 'portfolio/styles.html' %} </head> <body> <header class="header"> {% include 'portfolio/header.html' with profile=object_list only %} </header><!--//header--> {% include 'portfolio/footer.html' %} {% include 'portfolio/javascript.html' %} </body> </html> here is the model.py from django.contrib.auth import get_user_model from django.db import models User = get_user_model() class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(upload_to='profile_pic', blank=True, null=True) profession = models.CharField(max_length=50, blank=True, null=True) bio = models.TextField(blank=True, null=True) city = models.CharField(max_length=10, blank=True) country = models.CharField(max_length=10, blank=True) website … -
How do I upload files from Django admin directly to Google Cloud Storage, and how do I render them in the templates?
I am trying to store images in Google Cloud Storage for a production website. I have google cloud storage currently and I am wondering how to have the images uploaded in the Django admin store in GCS and how to render these in the templates. I have tried assigning the MEDIA_URL to the GCS bucket but they are not storing. Basically I just need some guidance from the start on how to achieve this. -
Many To Many Django, create instance
En estos momentos estoy desarrollando un proyecto, en el cual una de las secciones permite realizar una serie de anuncios, la idea del mismo es que estos tengan varias imágenes relacionadas,en la forma en la que tengo desarrollada esa sección, solo me permite almacenar una imagen por anuncio, y me gustaría saber como puedo hacer para agregar varias al mismo tiempo, a continuación presento el modelo, los formularios, y la vista para crearlo. Modelo class Ad(models.Model): id_user = models.ForeignKey(Account, on_delete=models.CASCADE) id_store = models.ForeignKey(Store, on_delete= models.CASCADE,default=None, blank=True, null=True) id_location= models.ForeignKey(Location, on_delete= models.CASCADE) id_ad_kind= models.ForeignKey(AdKind, on_delete= models.CASCADE) id_category= models.ForeignKey(Category, on_delete= models.CASCADE) id_unit= models.ForeignKey(Unit, on_delete= models.CASCADE, default = None, blank=True, null=True) ad_name= models.CharField(max_length=100) ad_description= models.TextField() price= models.FloatField() date_created = models.DateTimeField(auto_now_add=True) ad_images= models.ManyToManyField(Image, related_name="get_images_ad") def __str__(self): return self.ad_name class Meta(): verbose_name= "Anuncio" verbose_name_plural= "Anuncios" class Image(models.Model): img_route= models.ImageField(upload_to="Images", verbose_name="Ruta de la Imagen") class Meta(): verbose_name= "Imagen" verbose_name_plural= "Imagenes" Formulario class AdCreateForm(forms.ModelForm): class Meta(): model= Ad fields=('ad_name', 'ad_description','price','id_location', 'id_ad_kind','id_category','id_unit',) class AdImageForm(forms.ModelForm): class Meta(): model= Image fields=('img_route',) Vista def AdCreate(request): model = Ad if request.method == "POST" : ad_form= AdCreateForm(request.POST) img_form= AdImageForm(request.POST,request.FILES ) print("img es "+ str(img_form.is_valid())) print(img_form) if ad_form.is_valid() and img_form.is_valid(): img= img_form.save() ad= ad_form.save(False) ad.id_user = request.user ad= ad_form.save() ad.ad_images.add(img) ad.save() print("Almacenado") return render(request,'ad/ad_list.html') … -
Django Postgresql Cannot Decrypt From Query
Error: ERROR: function pg_sym_decrypt(bytea, unknown) does not exist LINE 1: select pg_sym_decrypt(users_customuser.email, 'hello') from ... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. Query: select pg_sym_decrypt(users_customuser.email, 'hello') from users_customuser I installed pgcrypto in pgadmin but it seems like the function is missing? Does the Django package not allow decryption from sql, and instead only allows decryption from the Django code? My objective is to decrypt the encrypted emails from the database using queries. How would I do that? Django Package: https://github.com/incuna/django-pgcrypto-fields Django settings.py: PGCRYPTO_KEY = 'hello' Django models.py: from pgcrypto import fields email = fields.EmailPGPSymmetricKeyField() -
Validation Error when filtering by UUID Django
I am attempting to return all the friends of friends of a certain user who is the author of the relationship. However, I keep getting this error: ValidationError at /author/posts ["“[UUID('8c02a503-7784-42f0-a367-1876bbfad6ff')]” is not a valid UUID."] class Author(AbstractUser): ... uuid = models.UUIDField(primary_key=True, default=uuid4, editable=False, unique=True) ... class Post(models.Model): ... author = models.ForeignKey(Author, on_delete=models.CASCADE) ... class Friend(models.Model): class Meta: unique_together = (('author','friend'),) author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='author') friend = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='friend') This foaf line in particular is where the error is coming from. How else could I do this? friends = Friend.objects.filter(author=userUUID) foafs = Friend.objects.filter(friend=[friend.friend.uuid for friend in friends]) -
BookingConfirmation() missing 1 required keyword-only argument: 'amount'
I pretty new in Python and Django,and I am trying to build a hostel reservation using stripe. I am trying to pass data(The price of the room) from my room detail view to the Charge view but I get the following error. TypeError at /booking/confirm/ BookingConfirmation() missing 1 required keyword-only argument: 'amount' Request Method: POST Request URL: http://localhost:8000/booking/confirm/ Django Version: 3.0.2 Exception Type: TypeError Exception Value: BookingConfirmation() missing 1 required keyword-only argument: 'amount' Exception Location: C:\Users\Administrator\Desktop\hostel\env\lib\site-packages\django\core\handlers\base.py in _get_response, line 113 Python Executable: C:\Users\Administrator\Desktop\hostel\env\Scripts\python.exe Python Version: 3.7.3 Here is my Room Detail View def RoomBookingView(request,pk): publishkey = settings.STRIPE_PUBLISHABLE_KEY if request.method == 'POST': if pk: room_id = Room.objects.get(pk = pk) amount = room_id.price student_id = request.user room_id.is_reserved = True, reservation = Reservation( room_id = room_id.id, student_id = student_id.id, ) reservation.save() try: room = Room.objects.get(id=pk) room.is_reserved = True amount = room_id.price room.save() except BaseException: pass return redirect(reverse('confirm', args=[amount])) context = { 'STRIPE_PUBLISHABLE_KEY' : publishkey, } return render(request,'room-detail.html',context) And my Charge View def BookingConfirmation(request,*args,amount): amount = args if request.method == 'POST': charge = stripe.Charge.create( currency='usd', amount = amount, description='A Django charge', source=request.POST['stripeToken'] ) return render(request,'booking-confirm.html',{}) -
How to setup a flexible django models
I'm new to django. What I'm trying to achieve is when the ProductType combobox is changed, the fields changes to its specific fields then the users inputs using those field and entered to the database. My problem is how to create a flexible model that would accept extra fields Sample: Input from django.db import models class Product(models.Model): """SKU""" stock = models.IntegerField(default=None) class ProductType(models.Model): product_field = models.ForeignKey(ProductFields, on_delete=models.CASCADE) name = models.CharField(max_length=255) class ProductFields(models.Model): """Fields of ProductType""" Here's an DB example I'm trying to achieve See Image -
Function performance: backend vs frontend
I would like to know if it's better for the user's experience to execute a high resources demand function in the backend (django) or in the frontend(JS), for example, a function that performs a query and then a sorting. -
Annotate based on calculation in ManyToManyField
I am trying to annotate a Django model by calculating a non-trivial expression using a property of a ManyToManyField in the model. The situation can be translated into the following simple example structure of "payments" that should be split between a number of "companies" according to their relative sizes. Which companies participate in a given payment is stored as a ManyToManyField: class Company: relative_size = models.DecimalField() ## can be assumed to add up to 1 among all companies class Payment(models.Model): companies = models.ManyToManyField(Company, related_name='payments', blank=True) amount = models.DecimalField() I'm now trying to query for the total amount that each company participated in. If the share was the same in each of the payments, this would be as simple as companies = Company.objects.annotate(total_payments=Sum(F('payments__amount')*F('relative_size'))) for company in companies: print("Company %s: %s" (str(company), total_payments)) But how to do this in the case where I have to calculate the correct fraction for every payment based on which companies participated? I tried something with SubQuery similar to the following, but couldn't really make sense of it or get it to work: ## this is clearly wrong, but just to illustrate what I'm after payments_per_company = Payment.objects.filter(company=OuterRef('pk')).values('company') payment_total_size = payments_per_company.annotate(totalfraction=Sum(F('companies__relative_size'))) companies = Company.objects.annotate(total_payments=Sum(F('payments__amount')*F('relative_size')/Subquery(payment_total_size))) Can anyone help … -
Cannot display all the results in a M2M relationship
Currently, I have the following entity relationship model : Table relationship ------------ ----------------- ------ | Objective | ------- | Objective_Task | ---------| Task | ------------ ----------------- ------ and I am trying to display the results as in the following table | id | Task | Task status | Objective | ---------------------------------------------------------------- | 1 | Set up drivers | In progress | Set up my machine | | 2 | Configure network | In progress | Set up the network | | 3 | Test the network | In progress | Set up the network | But the result I get is: | id | Task | Task status | Objective | ----------------------------------------------------------------------- | 1 | Set up drivers | In progress | objective.Objective.None | | 2 | Configure network | In progress | objective.Objective.None | | 3 | Test the network | In progress | objective.Objective.None | Below is the setup of my class models for this entity relationship: Objective model class Objective(models.Model): id = models.AutoField(primary_key=True) objective = models.CharField(null=False, max_length=60) initial_date = models.DateField(default=timezone.now(), null=False) expiration_date = models.DateField() class Meta: ordering = ['initial_date'] db_table = 'goal_objective' Task model class Task(models.Model): ACTIVE = 'Active' FINALIZED = 'Finalized' STATUS = [(ACTIVE, ACTIVE), (FINALIZED, … -
Cannot set value to instance
I am building a vote system for my app. I have 2 models, topic where votes are registers and VoteUser that takes topic as a foreign key and set the vote user to true Models : class Topic(models.Model): author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) votes = models.IntegerField(default=1) class VoteUser(models.Model): topic = models.ForeignKey(Topic, on_delete=models.CASCADE, null=True, blank=True, related_name='TopicVote') vote_status = models.BooleanField(default=False) author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) Now when an user vote I want the model "VoteUser" to set the topic to a certain value and set vote_status to true So I tried this : View : def upvote(request, qa_id): vote = VoteUser.objects.create(author=request.user) qa = get_object_or_404(Topic, pk=qa_id) vote = get_object_or_404(Topic, pk=qa_id) qa.votes += 1 qa.save() But I am not able to set the topic even when I used the pk from a topic I know exist. Could you help ? -
Django Statement Scoped View Query
I have three models, Result, Environment and Test. Environment and Test are FKs in Result. I was trying to find the latest Result in a given Environment for each Test - essentially to produce a page for an Environment that shows the latest Result for each Test. In the process of trying to optimize a PostreSQL query, I came up with the following: WITH CR AS (SELECT "cases_result"."test_id", max("cases_result"."created_at") "created_at" FROM "cases_result" WHERE "cases_result"."environment_id" = 1001 GROUP BY "cases_result"."test_id" ) SELECT CR.* , "cases_test"."id", "cases_test"."created_at", "cases_test"."updated_at", "cases_test"."name", "cases_test"."usage", "cases_test"."result_id", "cases_test"."health", "cases_test"."variance", "cases_test"."duration", "cases_test"."required", "cases_test"."ticket", "cases_test"."removed_at" FROM CR JOIN "cases_test" ON CR."test_id" = "cases_test"."id" ORDER BY CR."test_id" ASC, CR."created_at" DESC I'm now trying to see if I can implement this in my models.Manager. I currently have: tests = Test.objects.order_by('name') if environment.domain != 'example.com': tests = tests.exclude(name__startswith='sample') results = ( self.filter(test__in=tests, environment=environment) .select_related('test') .prefetch_related('test__teams') .order_by('test_id', '-created_at') .distinct('test_id') ) for test in tests: for result in results: if result.test == test: yield result break Can I use Django ORM to create this query, or will I need to use raw SQL and fetch the associated result objects? -
Django Ajax form not showing up
I trying to use Ajax and Django to submit forms. However, when I click on the button nothing happens and there is no response and the modal does not open. I am trying to prompt users to create a post and then post it to the page without refreshing. So far my code is this: my home/home.html where the button that should open the post is: <button class="btn btn-sm btn-primary show-form ml-auto" data-url="{% url 'home:post-create' %}"><i class="fas fa-plus-square"></i></button> my modal and script in same file: <div class="modal fade" id="modal-post"> <div class="modal-dialog"> <div class="modal-content"></div> </div> </div> <script> $(document).ready(function(){ $('.show-form').click(function(){ $.ajax({ url: '/home/post/create', type: 'get', dataType:'json', beforeSend: function(){ $('#modal-post').modal('show'); }, success: function(data){ $('#modal-post .modal-content').html(data.html_form); } }); }); $('#modal-post').on("submit",".create-form", function(){ var form = $(this); $.ajax({ url: form.attr('data-url'), data: form.serialize(), type: form.attr('method'), dataType: 'json', success: function(data){ if(data.form_is_valid){ $('#post-list div').html(data.posts); $('#modal-post').modal('hide'); } else { $('#modal-post .modal-content').html(data.html_form) } } }) return false; }) }); </script> my views for creating a post: @login_required def save_all(request,form,template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True posts = Post.objects.all() data['posts'] = render_to_string('home/home_post.html',{'posts':posts}) else: data['form_is_valid'] = False context = { 'form':form } data['html_form'] = render_to_string(template_name,context,request=request) return JsonResponse(data) @login_required def post_create(request): if request.method == 'POST': form = … -
Designing a WebApp and Android/IOS app in Python Django
I have a design question, this is the first time I am trying to design/architect a complete Web app solution for myself. The requirements are much common. The WebApp has a Website/UI - It shall work from the desktop browsers, tablet browsers, and phone browsers. It has to automatically change the rendering based on the device used. What do I need to use it for accomplishing this? Web interface and android/ios app to have an optional registration/sign-in option. They can create records and purchases without having to log in. Logging in is better but not required. The WebApp needs API - for Geographic lookup and other functions. The Web interface and the Android/IOS apps should be able to make calls to it without authentication. How to achieve security for the API, rate limit, and use of API keys for tracking, ownership, and control? Even though anyone can use the API but only the source/android/ios profile who created a certain record should be able to modify it. Is it better to have the API behind authentication as much as possible, except few publicly essential calls? In Django what API framework can best achieve this, some of the API calls do not … -
Django Reverse Regex Match
I have a table (Django Model) and each row/object contains a regular expression that I should evaluate over a given input to filter relevant objects. Is there any Django ORM method to do this? In Postgre it will be: SELECT * FROM 'value' ~ column; and the opposite of what I am searching for is: Model.objects.filter(column__regex='regex') I know that evaluating the regular expressions on the application side would give similar performance as the query, but my application design requires me to move that filter on the database side (as a proper ORM-based query). Any ideas how can I achieve that using Django? Thank you! Best regards, Dorinel Filip -
How to switch off the django debug screen
I have django project. In my development, when error happens like not import modules... etc. It shows the error on the browser, but I don't want to show that in production. Where can I switch off the debug mode??? -
Weasyprint 'cairo' error on Windows 10 x64
I want to use WeasyPrint to render html to pdf in django. I followed all the steps in the WeasyPrint documentation. But I'm getting this error again. cannot load library 'C:\msys64\mingw64\bin\libcairo-2.dll': error 0xc1 cannot load library 'libcairo.so': error 0x7e cannot load library 'libcairo.2.dylib': error 0x7e cannot load library 'libcairo-2.dll': error 0xc1 I also set the system variables properly. I check the location of the files with the WHERE command. The PATH variable outputs the address I have defined. But I keep getting this error. Where's my fault? -
django contrib message appearing behind my input instead on top
I have a contrib message that appear when the user login information is not valid! messages.info(request, "Sorry, your password was incorrect.") but the problem is that the pessage pop behind my input(So we can't clearly see the message) , I want to make it appear on top on my Login input....I tried to change the code position of the {{ message }} on my html files but it didn't worked. Maybe the problem is on my css files? Thanks for helping.... login.html {% load static %} <link rel="stylesheet" href="{% static "test.css" %}"> <head> <div class="container"> <div class="col-md-8"> {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}"> {{ message }} </div> {% endfor %} {% endif %} </div> </div> <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <!------ Include the above in your HEAD tag ----------> <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <!------ Include the above in your HEAD tag ----------> <link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <!-- Include the above in your HEAD tag --> </head> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css"> <div class="main"> <div class="container"> <center> <div class="middle"> <div id="login"> <form action="" method="post"> {% csrf_token %} <fieldset class="clearfix"> <p ><span class="fa fa-user"></span><input … -
bash: django-admin: command not found
recent days I uninstall python and everything because i had some OS problem so i fix it. i delete all cash and everything and install Python again. after i install Django but when i want to starptoject getting no command found django-admin.. but Django is installed because when I'm going with shell I'm getting this message. >>> import django >>> print(django.get_version()) 3.0.4 but after I want star project getting this error Ketis-iMac:~ ketiaslanishvili$ Django-admin startproject test bash: django-admin: command not found Ketis-iMac:~ ketiaslanishvili$ -
Django | Correct way to pass key identfiers to query sting
I was reading this Django doc: https://docs.djangoproject.com/en/3.0/topics/db/sql/#executing-custom-sql-directly It explains how to use params for preventing SQL-Injections and the documenation also just deals with paramaters, which in valid sql can become single quoted. Django simple escapes with single quotes by using: self.baz = "test" cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz]) becomes: b"UPDATE bar SET foo = 1 WHERE baz = 'test'" This shows that we cannot use the param argument for key identifiers like tablenames: cursor.execute("SELECT %s FROM %s", [column, table]) since single quotes are invalid sql query (back-ticks would be valid): b"SELECT 'id' FROM 'atablename'" This means that we can just pass data with string formatting e.g.: cursor.execute(f"SELECT {} FROM {}".format(column, table)) cursor.execute("SELECT "+column+" FROM "+ table) This way we have to take care ourselfs for sql-injections. Is there anything I am missing? How can I escape key identifiers in Django, so that there are no sql-injection possibilites? -
Django Model Object Automatic Filtering
I am working on a Django project, and I would like do a command like this: Student.objects.all().filter(name__iexact="Some name") in away that's can be more, well, malleable, e.g: someFunction(Student,objects.all(),'name__iexact',"Some name") or: Student.objects.all().some_advanced_filter(key='name__iexact',value='Some name') Thanks! -
Django how to save POST into form?
I'm trying to save the POST into my form. views.py def index(request): if request.method == 'POST': print('!PRINT request.POST') print(request.POST) form = PostForm(request.POST, request.FILES) print('!PRINT form') print(form) if form.is_valid(): form.save() return redirect('/') returned: !PRINT request.POST ~'title': ['Bart', 'Mat'], 'Create Match': ['Submit']}> !PRINT form ~name="title" value="Mat" maxlength="200" required id="id_title" ~name="title1" class="errorlist" This field is required. -
which database can handle about thousands of images effectively/easily?
I am about to start a project (going to develop a website), in which i'll have to deal with thousands of images. I'll upload those images into database and then i'll train,test them (using machine learning algorithms). My website will provide the user it's desired trained images, from the images he uploads. I can work with Django using python. will it work? or should i switch to SQL or MySQL? -
Following Django tutorial, "python manage.py migrate" doesn't create any django tables (MySQL, Pycharm)
In mysite.settings.py I have: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.path.join(BASE_DIR, 'test'), #'NAME': 'test', 'USER': 'root', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '3306', }} When I run 'python manage.py migrate' in the PyCharm terminal, nothing happens, no error message etc. No new tables are created in the database specified. I tried two things for NAME as you can see. MySQL Server version 8.0.19 MySQL Connector/Python 8.0.19 Python version 3.8 In PyCharm I have package mysqlclient 1.4.6 installed. Any advice on how to find the problem? How to get an error message? Thank you -
Creating a waiting queue in Django Channels?
I am currently working on a "wait queue" application on my Django app using channels. I have a channel layer using Redis to handle the connections within a group. I am also using a model in my database to track the amount of users in the queue. My question is if there is an easier and more scalable way. Will there be any issues down the road with this? class ChatConsumer(AsyncWebsocketConsumer): @database_sync_to_async def get_waiting_room(self): return WaitingRoom.objects.all().count() @database_sync_to_async def add_to_waiting_room(self, name): return WaitingRoom.objects.create(name=name) @database_sync_to_async def remove_from_waiting_room(self, name): return WaitingRoom.objects.filter(name=name).delete() async def connect(self): self.waiting_list = 'waiting_list' await self.channel_layer.group_add( self.waiting_list, self.channel_name) await self.accept() async def receive(self, text_data): self.text_data = json.loads(text_data) await self.add_to_waiting_room(self.text_data['user']) users = await self.get_waiting_room() await self.channel_layer.group_send(self.waiting_list, { 'type': 'user_list', 'users': str(users) }) async def disconnect(self, close_code): await self.remove_from_waiting_room(name=self.text_data['user']) await self.channel_layer.group_discard( self.waiting_list, self.channel_name) users = await self.get_waiting_room() await self.channel_layer.group_send(self.waiting_list, { 'type': 'user_list', 'users': str(users) }) async def user_list(self, event): users = event['users'] await self.send(text_data=users) When a user connects, they are added to a group in the channel_layer (Redis) and accepts the connection, when my user clicks a button, it sends a request to the channel and adds them to the waiting room (My Django model), on disconnect, it removes Model instance and …