Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django and prefetch_related Across Nested Relationships in a Custom Manager With to_attr Doesn't Attach Results to Model Instances
Consider a task list app with an editor that saves the state of the task list as a SnapShot after each edit (i.e., after inserting, editing, or deleting a TaskItem, a new SnapShot is generated, capturing the new state of the task_items, and their positions in the TaskList). Here is a simplified model: from django.db.models import Prefetch class TaskList(models.Model): objects = AnnotatedQuerySet.as_manager() class SnapShot(models.Model): task_list = models.ForeignKey(TaskList, on_delete=models.CASCADE) EDIT='ED' WORKEDIT='WE' LIVE = 'LI' STATUS_TYPES = ( (EDIT, 'Edit'), (WORKEDIT, 'Working Edit'), (LIVE, 'Live'), ) status = models.CharField(max_length=2, choices=STATUS_TYPES, default=EDIT) task_items = models.ManyToManyField(TaskItem, through='TaskItemInclude') class TaskItem(models.Model): content = models.TextField() class TaskItemInclude(models.Model): snapshot = models.ForeignKey(SnapShot, on_delete=models.CASCADE) task_item = models.ForeignKey(TaskItem, on_delete=models.CASCADE) position = models.SmallIntegerField() class Meta: ordering = ['position'] class AnnotatedQuerySet(QuerySet): def with_task_items(self, mode): if mode == SnapShot.LIVE: ti_qs = TaskItem.objects.filter(snapshot__status=SnapShot.LIVE) elif mode == SnapShot.WORKEDIT: ti_qs = TaskItem.objects.filter(snapshot__status=SnapShot.WORKEDIT) else: raise ValueError('mode must be LIVE or WORKEDIT.') return self.prefetch_related( Prefetch('snapshot_set__task_items', queryset=ti_qs, to_attr='fetched_task_items'), ) SnapShot, via its relationship with TaskItem through TaskItemInclude, captures the state of the TaskList. For each TaskList, there is one publicly visible live (SnapShot.LIVE) SnapShot, one current working edit (SnapShot.WORKEDIT), and possibly multiple inactive edits (SnapShot.EDIT). Inactive edits (SnapShot.EDIT) are saved for undo/redo/restore operations. My goal is to present the entire … -
Specify heigh of images in css doesn't work
I am currently working on a django blog. However, I am experiencing some difficulties with the size of the post thumbnails. Here's a picture: What I marked in yellow is how the image should be filling the space. The width is fine, but the heigh isn't working well as you can see. Here's the code: {% extends 'base.html' %} {% load static %} {% block content %} <style> img { height: 100%; width: 100%; } </style> <!-- Post--> {% for obj in object_list %} <div class="row d-flex align-items-stretch"> {% if not forloop.first and not forloop.last %} <div class="image col-lg-5"><img src="{{ obj.thumbnail.url }}" alt="..."></div> #Here's the image {% endif %} <div class="text col-lg-7"> <div class="text-inner d-flex align-items-center"> <div class="content"> <header class="post-header"> <div class="category"> {% for cat in obj.categories.all %} <a href="#">{{ cat }}</a> {% endfor %} </div> <a href="{{ obj.get_absolute_url }}"> <h2 class="h4">{{ obj.title }}</h2> </a> </header> <p>{{ obj.overview|linebreaks|truncatechars:200 }}</p> <footer class="post-footer d-flex align-items-center"><a href="#" class="author d-flex align-items-center flex-wrap"> <div class="avatar"><img src="{{ obj.author.profile_picture.url }}" alt="..." class="img-fluid"></div> <div class="title"><span>{{ obj.author }}</span></div></a> <div class="date"><i class="icon-clock"></i> {{ obj.timestamp|timesince }} ago</div> <div class="comments"><i class="icon-comment"></i>{{ obj.comment_count }}</div> </footer> </div> </div> </div> {% if forloop.first or forloop.last %} <div class="image col-lg-5"><img src="{{ obj.thumbnail.url }}" alt="..."></div> #Here's the … -
Getting a list from ListAPIView
I'm trying to get a list of an object "Contract" on a simple HTML page from a ListAPIView. But I cant get it to print what i need. It returns a Response. as needed: Response But it doesn't show anything on an HTML page (template in this case): {% extends "main.html" %} {% block contract %} <h1> Hello </h1> {% if contract_list %} <ul> {% for contract in contract_list %} <li> <h1> {{ contract.contractName }} </h1> </li> {% endfor %} {% else %} <h1>There are no contracts in the library.</h1> {% endif %} {% endblock %} It doesn't see contract_list at all. What am I doing wrong? Here it is in Views.py: class ContractSerializer(serializers.ModelSerializer): class Meta: model = Contract fields = ('contractName','zakupkiId','dateStart','dateEnd','display_tasks','get_absolute_url') class ContractView(generics.ListAPIView): model = Contract template_name = 'contracts/contract_list.html' # context_object_name = 'cotracts' # queryset = Contract.objects.all() def get(self, request): contracts = Contract.objects.all() # the many param informs the serializer that it will be serializing more than a single article. serializer = ContractSerializer(contracts, many=True) # render_classes = render(request, 'contract_list.html') return Response({"contracts": serializer.data}) And urls.py url(r'^contracts/$', views.ContractView.as_view(), name='contracts') -
How to add map on site?
I am new to djnago. I want to add a map to the site, where the user can select places on it, which will be saved to the database. I found how the user can select a location on the map: https://developers.google.com/maps/documentation/embed/get-started?hl=ru, but I do not know how to save it to the model -
Django ORM filter SUM different related objects
I have the following models: class Developer(models.Model): name = models.CharField(max_length=100) class Skill(models.Model): code = models.CharField(max_length=30) class Experience(models.Model): date_from = models.DateField(blank=True, null=True) date_to = models.DateField(blank=True, null=True) developer = models.ForeignKey(Developer, related_name='experience', on_delete=models.CASCADE) class SkillExperience(models.Model): skill = models.ForeignKey(Skill, on_delete=models.CASCADE, related_name='skill_experience') experience = models.ForeignKey(Experience, on_delete=models.CASCADE, related_name='skill_experience') years_experience = models.IntegerField() I need a query to retrieve Developers that have at years_experience of at least 5 in skill code 'python', for example. However I can't simply do Developer.objects.filter(skill_experience__years_experience__gte=5) because I could have two experiences in Python but one 3 years and another one 2 years and that won't show in the query above. So I need to sum up all the years_experience that are from skill__code="Python" and evaluate it. Is there some way to do it with a single query? -
Content not showing on page using ListView
I'm trying to show data from database using ListView but the nothing would show on the page even though database has data views.py class CatAdoption(ListView): model = Cat template_name = 'adoptions/adoptionhome.html' context_object_name = 'cats' urls.py from .views import CatAdoption, DogAdoption, OtherAdoption urlpatterns = [ path('adoption-home/', CatAdoption.as_view(), name='adoptionhome'), adoptionhome.html <div class="animals"> {% for animals in cats %} <div class="animalpictures"> <div class="animalInfo"> <img alt="animalPic" src="https://1590597482.jpg" alt=""> <div class="animalDesc"> <h1>{{ animals.name }}</h1> <p>{{ animals.description }}</p> </div> </div> </div> {% endfor %} </div> (I have same code for another blog page which shows all contents from database) -
how customize User validator to accept whitespaces
I want have custom validation for User to create name user with whitespaces in name. I do this like below but, I create User2 and change regex expression but it not changed validation conditions, it's not work. Have anybody idea why or how instead of I can do it? models from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import User from django.contrib.auth.validators import UnicodeUsernameValidator class MyUnicodeUsernameValidator(UnicodeUsernameValidator): print('test My') regex = r'^[\d]' message = _( 'Enter a valid username. This value may contain only letters, ' 'numbers, and @/./+/-/_ characters.' ) flags = 0 class User2(User): username_validator = MyUnicodeUsernameValidator() print(username_validator) view from django.shortcuts import render, get_object_or_404 from .models import User2 from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import logout from blog.models import Article class MyUserCreationForm(UserCreationForm): class Meta: model = User2 fields = ("username",) def sign_up(request): context = {} form = MyUserCreationForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.save() return render(request, 'accounts/index.html') context['form'] = form return render(request,'registration/sign_up.html', context) -
how to display a single vendor to its related product in django?
well, I am a beginner but a mid-level beginner and I am building an e-commerce website. I have vendor, customer and products which relate to a specific vendor. I have made a view to display the all kind of products on the page and I have also parsed the Vendor model in products view. but I am getting all vendors on a single product which shows that code is not working well as it should have. I hope you guys got the point what I want to ask? for convenience here is the code. views.py: def products(request): vendor = Vendor.objects.all() products_list = Item.objects.all() context = { 'vendors': vendor, 'products': products_list, } template = 'vstore/products.html' return render(request, template, context) products.html: <div class="row"> {% for item in products %} <div class="col-3"> <div class="item"> <div class="strip"> <figure> {% if item.discount >= 20 %} <span class="ribbon off">{{item.discount}}% OFF</span> <a href="{% url 'product_detail_view' item.pk %}" class="strip_info"> <img class="" src="{{ item.image.url }}" alt="Vendor's Photo"> </a> {% else %} <a href="{% url 'product_detail_view' item.pk %}" class="strip_info"> <img class="" src="{{ item.image.url }}" alt="Vendor's Photo"> </a> {% endif %} </figure> <ul> <li><span class="loc_open">{{ item.name }}</span></li> <li> <div class="score "><div class="score "><span class="">{% for vendor in vendors %}{{vendor.name}}{% endfor %}<h5><div … -
Better way to optimize bulk_create when uploading CSV file, with records related to junction model?
I have the following view: ### VIEW ### def project(request, project_id): creator_id = request.user.id # Get project project = get_object_or_404(Project, pk=project_id, creator_id=creator_id) # Get all backers all_backers = project.backers.all().distinct() # CSV UPLOAD csvform = csvUploadForm() if request.method == 'POST': csvform = csvUploadForm(request.POST, request.FILES) if csvform.is_valid(): csvform = csvform.save(commit=False) csvform.for_project_id = project_id csvform.creator_id = creator_id csvform.save() # READ CSV csv_file = csvform.csv data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) backers_list = csv.reader(io_string, delimiter=',', quotechar='"') objs = [ Backer( backer_number=row[0], backer_uid=row[1], name=row[2], email=row[3], shipping_country=row[4], shipping_amount=row[5], reward_title=row[6], backing_minimum=row[7], reward_id=row[8], pledge_amount=row[9], rewards_sent=row[10], pledged_status=row[11], notes=row[12], pid=project_id ) for row in backers_list ] try: msg = Backer.objects.bulk_create(objs) returnmsg = {"status_code": 200} print('imported successfully') except Exception as e: print('Error While Importing Data: ',e) returnmsg = {"status_code": 500} # Add backer_id and project_id in Backed new_backers = Backer.objects.filter(pid=project_id) backed_ids = [ Backed( backer_id=bid.id, project_id=project_id ) for bid in new_backers ] try: msg = Backed.objects.bulk_create(backed_ids) returnmsg = {"status_code": 200} print('imported successfully') except Exception as e: print('Error While Importing Data: ',e) returnmsg = {"status_code": 500} return redirect('project', project_id=project_id) else: csvform = csvUploadForm() ... Through this view I am uploading a CSV file, creating a list of it and using bulk_create to push it to model (Backer), in order to speed … -
Django problem with request.get to postgresql
Getting stuck with this issue, I've got a table that has date, category and sum and I'm trying to make a query that can choose between dates to get records, but when i pick dates it screams "column "2020-12-12" does not exist" views.py def outgoings_history(request): if request.method == "POST": date_from= request.POST.get('date_from') date_to= request.POST.get('date_to') search_result = Outgoings.objects.filter(user=request.user).order_by('-date')\ .raw('SELECT suma, kategoria, date FROM outgoings WHERE date BETWEEN "2020-12-12" AND "2020-12-12"') return render(request, 'outgoings_history.html', {'data': search_result}) else: displaydata = Outgoings.objects.filter(user=request.user).order_by('-date') return render(request, 'outgoings_history.html', {'data': displaydata}) forms.py class PickADate(forms.Form): date_from= forms.DateField(widget=DateInput()) date_to= forms.DateField(widget=DateInput())[enter image description here][1] The date '2020-12-12' is just a example and it has records this day but still doesn't show anything -
react send image file to api with axios
I have the following axios call in my app: export const createProduct = (form) => { const requestString = inventoryApiString + "products/"; return axios .post(requestString, form, getAuthHeader()) .then((Response) => { return { product: Response.data, message: null, }; }) .catch((Error) => { let errorMessage = getErrorMessage(Error); return errorMessage; }); }; And this is the content of key photo of parameter form: I am putting the content of the file field in the form when the user selects a file, but I get this error from Django Rest Framework backend api: {"photo":["La información enviada no era un archivo. Compruebe el tipo de codificación del formulario."]}, which means Information sent is not a file. Check the codification type of the form. I don't know what it means. -
How to set the name value and choice field value in html form fields without using django-forms?
Suppose I want to give user 2 option in html option form to choose 1. How can user user select one from html form without using django form?need views.py,models.py,index.html coding help Sample html code: <form method="POST"> <div class="form-row"> <div class="name">Name</div> <div class="value"> <div class="input-group"> <input class="input--style-5" type="text" name="name" required> </div> </div> </div> <div class="form-row"> <div class="name">Applying In</div> <div class="value"> <div class="input-group"> <div class="rs-select2 js-select-simple select--no-search"> <select name="subject" required> <option disabled="disabled" selected="selected"> Applying Department</option> <option>Backend</option> <option>Mobile</option> </select> <div class="select-dropdown"></div> </div> </div> </div> </div> -
is there a method to create a text field and color words in text in django?
i created a django project : so in my page html , i have a list of words colorated with different background colors : hello (colored in red) world (colored in yellow) i do this with : <span class="token-label" style="background-color=red">hello</span> in the same page , i want to display the text which contains the two words , but i want to colors the words in the text according to colors of each word: hello, i'am here ! hello world ! with "hello" colored with red and "world" in yellow -
How to use a view function on all pages in Django?
I'm building an app in Django in which I have a layout where I have the navbar and I extend this layout to each page. In order to have the navbar to receive the proper variables from the view I have to write the same code on each view. There has to be a way to write this code once and affect directly the layout so I won't need to type it multiple times but I haven't found the answer. How can I write the function one time? Something like a global variable in Django I guess. I hope I managed to explain myself ok, thanks in advance! -
Media files not displaying when DEBUG = False; what are the prerequisites to get them to show?
As I state in the title, when I set DEBUG = False in my project's settings file, the files from my media directory (the one the user uploads) don't display. The files from my static directory (the CSS and JavaScript files) load properly. I looked at this answer, but I don't understand the prerequisites to get this to work. I am testing this on my local machine, where I only have Django and PostgreSQL installed. I don't have any Apache servers running, as far as I'm aware. I want to deploy my app on Amazon AWS, so I'd like to try out how it will look in production there before I deploy it to Amazon AWS. Here are the relevant parts of my settings.py file: DEBUG = False ALLOWED_HOSTS = ['*'] STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' STATICFILES_DIRS = [ BASE_DIR / "static", '/var/www/static/', ] -
Django form.is_valid() always return false
I'm trying to make a login system in Django but I just can't go through Django form.is_valid statement because It returns false everytime.If I just type my usernameand passwordand submit the form, I can get the request.POSTdata but form.is_valid()still returns false. My Django view is at below @csrf_exempt def login_system(request): if request.method == 'POST': form = AuthenticationForm(request.POST) print(request.POST) if form.is_valid(): form.save() print("form is valid") username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username= username, password= password) login(request, user) return redirect("/") else: form = AuthenticationForm() context = {'form': form} return render(request, 'registration/login.html', context) and this is the htmlfile I've been trying to create a valid form. <!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> <form method='post' action="{%url 'login' %}"> {%if form.errors %} <p>Error occured try again</p> {%endif%} {{form}} <input type="submit" value="login"> </form> </body> </html> -
Can't add new user or group in django admin
I am trying to add new user and group in my newly created django web from admin panel . But it shows following error when I click save. This the admin panel of my django website Here new group "group1" is creating ''' OperationalError at /admin/auth/group/add/ no such table: main.auth_user__old Request Method: POST Request URL: http://127.0.0.1:8000/admin/auth/group/add/ Django Version: 2.1.5 Exception Type: OperationalError Exception Value: no such table: main.auth_user__old Exception Location: G:\MyPythonProject\django_web\venv\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 298 Python Executable: G:\MyPythonProject\django_web\venv\Scripts\python.exe Python Version: 3.9.0 Python Path: ['G:\MyPythonProject\django_web\web_project', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python39', 'G:\MyPythonProject\django_web\venv', 'G:\MyPythonProject\django_web\venv\lib\site-packages'] Server time: Sat, 12 Dec 2020 18:18:33 +0000'''' -
How can i add google maps in django which takes a location from user and his desired location and then calculates the distance between the locations?
I created a an app which adds map in page using 'https://www.fullstackpython.com/blog/maps-django-web-applications-projects-mapbox.html' this refernce. Now i want to take userlocation and then user can enter his desired location and then calculates the distance between them. -
POST returns "detail": "Method \"GET\" not allowed."
The way the project works is there should be a random code that is given in creating a room (avoiding duplicates and the guessing a code that isn't taken) and the host should create their own name. In the files, I've created the room and generated a random code that should be given when creating a room, but I receive an HTTP 405 Method Not Allowed. I'm attempting to POST and not GET so I'm confused as to why that's happening; and the other parameters (code and host) do not show up. I assumed the code and host key would show up in the create method, but it doesn't. I would also like to add that I receive and Integrity Error regardless of changing the serializer to add id, code, and host to the serializer or if I leave the code the way it is in the screenshots. models.py from django.db import models import random import string # Create your models here. def code(): """ function randomly creates room access code """ length = 7 while True: code = ''.join(random.choices(string.ascii_uppercase + string.digits, k=length)) if Room.objects.filter(code=code).count() == 0: break return code class Room(models.Model): """ sets up room requirements and stores it … -
Wagtail Pagination issue with Waypoint Infinite Scroll
I've implemented Waypoint Infinite Scroll just fine on a regular Page model for art gallery items. Those items can be added to a shop with a checkbox. I then use a Shop page to filter the gallery items that are marked as on sale. For some reason, when the infinite scroll feature seems to trigger just fine on the shop page but no new items are rendered. I get a 200 response from the server and no errors are logged to the console: [12/Dec/2020 11:40:46] "GET /shop/?page=2 HTTP/1.1" 200 26 The page it works with: class Gallery(Page): intro = RichTextField(blank=True, help_text="Text for the top of your gallery page. (Optional - recommended to leave empty for a more simplistic look.)") content_panels = Page.content_panels + [FieldPanel('intro', classname="full")] subpage_types = ['InstallationPage'] # parent_page_types = [] def get_context(self, request): context = super().get_context(request) filtered_medium = request.GET.get('medium', None) if filtered_medium: context['filtered'] = True mediums = InstallationMedium.objects.filter(name=filtered_medium) installations = InstallationPage.objects.child_of(self).order_by('-date').live().filter(mediums__in=mediums) else: mediums = InstallationMedium.objects.filter(installationpage__in=InstallationPage.objects.all()).distinct() installations = InstallationPage.objects.child_of(self).order_by('-date').live() paginator = Paginator(installations, 12) page = request.GET.get('page') try: pagin = paginator.get_page(page) except PageNotAnInteger: pagin = paginator.get_page(1) context['installations'] = pagin context['mediums'] = mediums return context Shop page where it doesn't work: class Shop(RoutablePageMixin, Page): ajax_template = "shop/shop_item_ajax.html" def get_context(self, request): context … -
How to render image which is in other folder and not in static folder in Django?
My matplotlib analysis images are saving in other folder instead of static folder "images". I need to give a path to that folder where my analysis images are being saved. this is the folder where my analysis images are saving. -
How to organize a multiple users roles project with Django?
i am a doubt regarding the organization of my code. I am starting a new project with Django 3.1 that should work with different users types. First step was extending the User model with the AbstractUser (from django.contrib.auth.models import AbstractUser), adding a new field called role: class User(AbstractUser): ADMINISTRATOR = 1 AGENT = 2 EDITOR = 3 REPRESENTATIVE = 4 ROLES = [ (ADMINISTRATOR, _('Amministratore')), (AGENT, _('Agente')), (EDITOR, _('Editore')), (REPRESENTATIVE, _('Commerciale')) ] role = models.PositiveSmallIntegerField( choices=ROLES, default=AGENT, ) ... As you can see i have (for the moment) 4 roles to manage. Each role has its own control panel where can manage its things. With control panel i am not referring to the Admin control panel, I need to create 4 backends where the users can manage their things. For this reason i thought to create 4 applications: administrator agent company representative and a fifth called backend that is basically the theme i would like to use as base for the users panels. (Being a theme it it only has templates/ templatestags/ and static/) Then, I am creating an app for each thing to manage, with "thing" i mean something like Invoice management, Quote management, Article management and so on... … -
How to query another Django model in template view based on the relation to another model
I have these models class Protocol(models.Model): name = models.CharField(max_length=200) class Description(models.Model): name = models.CharField(max_length=200) protocol = models.ForeignKey(Protocol) class Trait(models.Model): desc = models.CharField(max_length=200) protocol = models.ForeignKey(Protocol) class State(models.Model): desc = models.CharField(max_length=200) trait = models.ForeignKey(Trait) class Expression(models.Model): state = models.ForeignKey(State) description = models.ForeignKey(Description) So a Protocol (e.g. protocol "A") consist of a certain amount of Traits (e.g. height, weight, color). Each Trait can have multiple States (e.g. low, medium, high). Then, a Description is a collection of Expressions related to a specific Protocol. For example Description #1 is made with Protocol "A" and consist of two Expressions: height -> low, weight -> high; but Trait color is not specified. Basically, what i want to do is display in a template view all the Traits linked to the specific Protocol of the selected Description, and then the corresponding Expression which can also be empty for some Trait. Like this: | Trait | Expression | |--------+------------| | height | | | weight | high | | color | blue | Using the shell i can easily return what i need # Select a Description desc = Description.objects.first() # Get the protocol protocol = desc.protocol # Get all traits in the selected protocol all_traits = … -
Django wait notify mechanism for webhooks
I have the below function which calls an API: def verify(request): if request.method=='POST': url=some_url data={some data} r=requests.post(url, data=json.dumps(data)) else: return render(request,'users/verify.html') Now I get a webhook callback on an endpoint which is handled by another view function: @csrf_exempt def onFetchMode(request): response=json.loads(request.body) Now how do I notify my initial function about the result of my webhook so that I can proceed with the flow of my application? -
Letsencrypt SSL certificate on staging and production servers
Suppose my domain is example.com being managed by AWS Route53. I have an EC2 instance serving a Wordpress site (production) at www.example.com and example.com. I also have a staging server for a Django app at development.example.com. Once I have done my testing for the Django app, I will be taking down the Wordpress site and replace it with my Django site. In the end, I will have one production server for Django and another for internal testing on the staging server. Will I need a separate LetsEncrpyt certificates for the two servers? I don't want to bring down my current Wordpress site as my app is not really ready yet.