Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to test Django reusable templates?
In one of my templates for detailed view of a device assignment I had logic pertaining to if buttons should appear depending on the user's permission. I wrote tests for these buttons and they work as expected. Today I wanted to reuse these buttons elsewhere in another template so I extracted it into its own template file and put it in a "partials" folder. |-templates | |-assignments | | |-deviceassignment_form.html | | |-deviceassignment_detail.html | | |-deviceassignment_confirm_delete.html | | |-deviceassignment_list.html | | |-partials | | | |-deviceassignment_control_buttons.html | | | |-deviceassignment_infobox.html Obviously I can continue testing deviceassignment_detail.html which includes the control buttons and checks to make sure they work (appearing or not based on permissions). But then when I include control buttons elsewhere I might be tempted to test them again... Instead couldn't I write a test ONLY for the deviceassignment_control_buttons.html template? I want to render the template directly with a basic view context and check that everything works as expected. Is this possible? -
I am finding it difficult to do relative Import in Django application
I am relatively new to django and am finding it difficult to do basic module referencing. Even thou I have searched through couple of links I still don't get it. I have been here: Relative Import For the Billionth Time and I still don't get it Here is my folder structure main main/main main/main/urls.py main/sub_main main/sub_main/views.py In my urls module I have a line from ..sub_main import views However, I keep getting the error: ImportError: attempted relative import beyond top-level package Is there something am missing? -
How to prevent Django view to mix up data of two different users
Hy, I'm working on a Django project, and in my view of the app, I'm declaring some variables according to each individual's unique ID from database. Like this: def chat(request): if request.POST: global curCombo, curComboAlternate, firstSender # Getting the user ID of the user clicked toChatUserID = request.POST.get("userID") # Getting user ID of the login user from another function: try: # Looking if it is already defined in the "everyone" function curUserID = curUserID #Getting from another function except: # If not defined, then define it here curUserID = request.session.get("curUserId") # Combination of person itself and the person to talk curCombo = f"{curUserID}&{toChatUserID}" # Declaring this to use in case if the logined user is not the one on who's name the message combination is created in database curComboAlternate =f"{toChatUserID}&{curUserID}" # making this variable global to use it in the addMsgToDB function to determine the cur combo variable # If messages exist with opposite combination for "combo" if Message.objects.filter(combo=curComboAlternate).exists(): firstSender = "other"Message.objects.filter(combo=curComboAlternate) # If messages exist in normal combination for "combo" else: firstSender = "me" print("now the firsender is set to ----->me") curComboMsg = Message.objects.filter(combo=curCombo) # Getting the name of the person to whom message has to be sent to … -
How do I send a django model to javascipt?
How do I pass a django model to javascript? Specifically, I want to pass a django Movie model to javascript. In javascript, I would like to display the id something in the movie model at the time of score with an if statement. def index(request): if Movie.objects.order_by('-stars').exists(): movie = list(Movie.objects.order_by('-stars')) if TV.objects.order_by('-stars').exists(): tv = TV.objects.order_by('-stars') print(tv) context = { 'movie':movie, } return render(request, 'Movie/index.html',context) fetchTrendingResults("all", "week") var mediaType = document.getElementById("media_type") mediaType.addEventListener("change", function(event) { fetchTrendingResults(mediaType.options[mediaType.selectedIndex].value, "day") }) function fetchTrendingResults(media_type, time_window) { var trendingDiv = document.getElementById("trendings") trendingDiv.innerHTML = "" if (media_type == "score"){ var js_list = {{movie}}; } else{ fetch(`/api/trendings?media_type=${media_type}&time_window=${time_window}`, { method: "GET", headers: { "Content-Type": "application/json" }} // todo:movieとTVのIDをもらってこれをURLにFethして映画とTVの情報をそれぞれでスターが高い順に表示する。 ) .then(res => res.json()) .then(data => { for (let i=0; i<data.results.length; i++) { var mainDiv = document.createElement("div"); mainDiv.setAttribute("class", "card"); mainDiv.setAttribute("style", "width: 18rem;"); var img = document.createElement("img"); img.setAttribute("src", "https://image.tmdb.org/t/p/w200" + data.results[i].poster_path); img.setAttribute("class", "card-img-top"); img.setAttribute("alt", "..."); var body = document.createElement("div"); body.setAttribute("class", "card-body"); var title = document.createElement("h5"); title.setAttribute("class", "card-title"); if (data.results[i].name) { title.innerHTML = data.results[i].name; } else { title.innerHTML = data.results[i].title; } //var text = document.createElement("p"); //text.setAttribute("class", "card-text"); //text.innerHTML = data.results[i].overview; var link = document.createElement("a"); link.setAttribute("href", "/" + data.results[i].media_type + "/" + data.results[i].id + "/"); link.setAttribute("class", "btn btn-primary"); link.innerHTML = "View Details"; body.appendChild(title); //body.appendChild(text); body.appendChild(link); … -
Set the background of the body to an image while using Bootstrap 5
I am curious how to set the whole webpage background (the body) to an image. Ideally I would like to fade the image a bit so it isn't overpowering. <style> body { background-image:url("{% static 'portfolio/cherry_blossoms.jpg' %}"), } </style> I attempted to add this within the html body however it returned no result. Note I am using Bootstrap 5. -
Vue not displaying Django Rest API data
I am working on a brand new project using Vue and Django Rest Framework. I got the API set up and I am getting the data back as needed, as confirmed by network in dev tools. However, I am having an issue with the v-for loop displaying the results. Any reasons or ideas on why I am not getting the results displayed? Here is vue.js code (GetTasks.vue) <template> <div class="tasks"> <BaseNavbar /> </div> <div v-for="tasks in APIData" :key="tasks.id" class="container"> <div class="card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">{{tasks.task}}</h5> <p class="card-text">{{tasks.details}}</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> </div> </template> <script> import { getAPI } from '../axios-api' import BaseNavbar from '../components/BaseNavbar.vue' export default { name: 'GetTasks', data () { return { APIData: [] } }, components: { BaseNavbar, }, created () { getAPI.get('/tasks/',) .then(response => { console.log('Task API has recieved data') this.APIData = response.APIData }) .catch(err => { console.log(err) }) } } </script> Django model class Tasks(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) task = models.CharField(max_length=200) details = models.CharField(max_length=500) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateField(auto_now=True) -
Django_rq, jobs fails due to missing positional arguments
I've been trying to solve an issue with integrating Django_rq into my app. I have several .csv data imports that I have created which take quite a bit of time to process. All data imports are similar in nature, but vary in the amount of code being preformed. I have updated two of the data imports so far to use Django_rq and they run successfully. No issues with them. Little backstory, all these functions where using python threading module originally. The problem came when I went to update the 3rd data import function. In addition to updating it just like the first two, I reduced the amount of positional arguments from 5 down to just 1. When I run the data import and add the job to a queue, it fails immediately. When I check the failed job registry to review the trace back, it says Traceback (most recent call last): File "/srv/cannondj/venv/lib/python3.8/site-packages/rq/worker.py", line 1061, in perform_job rv = job.perform() File "/srv/cannondj/venv/lib/python3.8/site-packages/rq/job.py", line 821, in perform self._result = self._execute() File "/srv/cannondj/venv/lib/python3.8/site-packages/rq/job.py", line 844, in _execute result = self.func(*self.args, **self.kwargs) TypeError: process_task_data() missing 5 required positional arguments: 'all_jobs', 'all_tasks', 'all_assignment_types', 'all_assignment_statuses', and 'db_que' I find this odd, because those are the … -
How to constrain foreign key to field in other foreign key?
Sorry for the horrible question title, I'm not sure how to phrase this. Here's a dummy example to make things clear. If I have models like: class Shop(models.Model): mechanics = models.ManyToManyField(mechanic) class Mechanic(models.Model): name = models.CharField() class Car(models.Model): problem = models.CharField() shop = models.ForeignKey(Shop, on_delete=models.SET_NULL, blank=True, null=True) fixer = models.ForeignKey(Mechanic, on_delete=models.SET_NULL, blank=True, null=True) How do I restrict the model so that fixer is always only ever a mechanic in the same shop as the car? Hopefully this is straight forward, but I've been scouring the Django docs and Stackoverflow and things haven't quite come together. I've looked into using a CheckConstraint on the model, but I'm not sure how to format the query. I've also learned about the limit_choices_to of a ForeignKey, but have run into a similar problem. Any help is appreciated. Thank you! -
how can i show many-to-mant-field objects in a form?
hi i wrote a code to make genre section in site and i used many-to-many-field in models to add it: from django.db import models from django.contrib.auth.models import User class Genre(models.Model): name = models.CharField(unique=True,max_length=20) def __str__(self): return self.name.title() class Mdata(models.Model): name = models.CharField(max_length=100) artist = models.CharField(max_length=150) album = models.CharField(max_length=100) nation = models.CharField(max_length=100) duration = models.DecimalField(max_digits=4,decimal_places=2) released_in = models.DecimalField(max_digits=4,decimal_places=0) uploaded_at = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to='images/',blank=True,null=True) audio = models.FileField(upload_to='audios/',null=True,blank=True) genre = models.ManyToManyField(Genre) uploader = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.name.title()+" by "+self.artist.title() but when i check music itself in site it just show how many object I've selected not genre's as you can see here: [![screen shot][1]: https://i.stack.imgur.com/xHaMK.png here's my template: {% extends 'pages/base.html' %} {% block content %} <form> {% if mdata.image %} <img src="mdata.image.url" height="500" width="500"> {% endif %} {% for field in form %} <p>{{ field.label }} : {{ field.value}}</p> {% endfor %} </form> <a href="{% url 'pages:edit_music' mdata.id %}">edit</a> {% endblock %} and forms(forms is simple i just added models as field): from django import forms from django.forms import ModelForm from .models import Mdata class MdataForm(ModelForm): class Meta: model = Mdata fields =[ 'name', 'artist', 'album', 'genre', 'nation', 'duration', 'released_in', 'image', 'audio', ] -
How to sorting with attrgetter from common foreign key attribute
doc_skai = DocSKAI.objects.all() doc_added = DocAddedSKAI.objects.all() result_list = sorted(chain(doc_skai, doc_added),key=attrgetter('???'), reverse=True) both doc_skai and doc_added have foreign key with model Document, and Document model have a field of 'published_date'. How can I sort the result list from the published_date of Document? -
How to get a list of field names of a queryset in Django
I have a queryset whose fields are being selected with a multiple choice filter. So I wonder how can I get a list of field names of a query of this set. Person.objects.all() : <QuerySet [{'id': 1, 'name': 'Josh', 'surname': 'Smith', 'age': 28, 'address': 'New York'}]> What I'm trying to get : ['name', 'surname', 'age', 'address'] -
How do I fix an error when sending an email in django?
I have a PasswordReset setup in django for when I forget my password, but when I test it, I get this error. [WinError 10061] Could not connect because the target computer refused. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'localhost' EMAIL_PORT = 25 EMAIL_HOST_USER = 'apptest' EMAIL_HOST_PASSWORD = 'xxxxxxxx' EMAIL_USE_TLS = False -
File uploaded in my form is not showing up in my edit/update form
When I fill out my form with its file, it apparently submits, but when checking it out when editing/uploading, all data in the form shows up except my file. So, I cannot access it at all. I guess it probably has something to do with my views.py (the function is for both, save a form for the first time and visualizing them), so here it goes #views.py def contract_form(request, id=0): if request.method == "GET": if id == 0: form = ContractsForm(request.FILES) else: contratos = Contratos.objects.get(pk=id) form = ContractsForm( instance=contratos) return render(request,"contracts_form.html", {'form':form}) else: if id == 0: form = ContractsForm(request.POST, request.FILES) else: contratos = Contratos.objects.get(pk=id) form = ContractsForm(request.POST, request.FILES, instance= contratos, ) if form.is_valid(): form.save() messages.success(request, "Form submission successful") else: messages.error(request, "Error, contract not submitted") return redirect('/contracts') Just in case, every other instance that has something to do with the upload file: #models.py attached_file=models.FileField(upload_to="media", blank=True) My form is stated with <form enctype="multipart/form-data" action="" method="post" autocomplete="off" class="row g-3"> #contracts_form.html <label for="{{ form.subject.id_for_label }}">Attached File:</label> {{form.attached_file}} {% if Contracts.media %} <a href="{{Contracts.media.url}}"></a> {% endif %} #settings.py MEDIA_ROOT=os.path.join(BASE_DIR, 'uploads/') MEDIA_URL="/contracts-media/" path('contracts/edit/<int:id>', views.contract_form, name='edit'), #edit/update form path('contracts/add', views.contract_form, name = 'new-contract'), #add a contract ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ```` -
Changing TailwindCSS class using Django and JS
I have the following code: <nav class="mt-4 flex flex-1 flex-col space-y-2 bg-gray-300 space-y-auto" aria-label="Transporters"> {% if list_transporters_results|length > 0 %} {% for item in list_transporters_results %} <div> <div class="flex flex-row items-center justify-between p-2" id="container-button-transporter-{{ forloop.counter }}"> <button type="button" hx-get="{% url 'tool:results-transporter' slug=item.slug pk=item.pk %}" hx-target="#stats" hx-swap="innerHTML" hx-trigger="click" class="cursor-pointer" id="button-transporter-{{ forloop.counter }}" onclick="get_id_transporter(this.id)" >{{ item.transporter }}</button> <div class="bg-[#195266] rounded-full p-2 self-center mr-2"> <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"> <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/> </svg> </div> </div> </div> {% endfor %} {% else %} <div> <div class="flex flex-row items-center justify-between"> <p class="text-center">No transporters yet.</p> </div> </div> {% endif %} </nav> My objective is to change the class of the div id="container-button-transporter-{{ forloop.counter }}" by clicking on the button button-transporter-{{ forloop.counter }}. Using forloop.counter, I have div such as: container-button-transporter-1 container-button-transporter-2 etc. To update the Tailwind class, I have the following JS script: <script> var transporterId; var numberTransporter; function get_id_transporter(clickedId){ transporterId = clickedId; numberTransporter = parseInt(transporterId.split("-")[2]); } const button = document.getElementById(`button-transporter-${numberTransporter}`); if(button){ button.addEventListener('click', function handleClick() { document.getElementById(`container-button-transporter-${numberTransporter}`).className = "flex flex-row items-center justify-between p-2 bg-[#195266]"; document.getElementById(`button-transporter-${numberTransporter}`).className = "text-white"; }); } </script> The code above does not work with the variable numberTransporter. However, if I change to … -
usage of django context variable as html tag attribute
I'm trying to understand how context variables work in templates. Is it mandatory to use quotations around the context variable. for example if my code is as follows view: def view(req): return render(req, 'index.html', {'class': 'style'} html: <h1 class="{{class}}">hello world</h1> i saw the above usage in several places. here my doubt is since it's a string variable, can it be used without quotations like? <h1 class={{class}}>Hello World</h1> Or is there any reason to use those quotations? because those two are working same. am i missing anything? -
Como descargar una imagen/pdf Django templates
Como puedo descargar una imagen o pdf desde mis templates en Django? al momento de hacer la descarga del pdf este se abre en otra pestaña e igualmente cuando intento descargar una imagen.¨ models.py from django.utils import timezone from django.db import models from django.core.validators import FileExtensionValidator import uuid # Create your models here. class Imagenes(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) image = models.FileField(verbose_name='Imagenes' ,upload_to='imagenes', validators=[FileExtensionValidator(allowed_extensions=['jpg', 'jpeg', 'png'])]) fecha_subida = models.DateTimeField(default=timezone.now) class Meta: verbose_name = "Imagenes" views.py def imagelinks(request, id): imagen = get_object_or_404(models.Imagenes, id=id) descarga = models.Imagenes.objects.filter(id=id) data = {"formu":UploadImageForm(instance=imagen), 'descargas':descarga} return render(request, 'imagenes/linkimagenes.html', data) urls.py from django.urls import path from imagenes import views urlpatterns = [ path('downloadi/<id>/', views.imagelinks, name="imagenlinks"), path('imagenes/', views.SubirImage, name="imagenes") ] template {% extends 'base/base.html' %} {% block title %} {% endblock %} {% block header %} <h3 class="float-md-start mb-0"><a href="{% url 'home' %}">Archinon</a></h3> <nav class="nav nav-masthead justify-content-center float-md-end"> <a class="nav-link fw-bold py-1 px-0" href="{% url 'archivos' %}">Archivos</a> <a class="nav-link fw-bold py-1 px-0" href="{% url 'imagenes' %}">Imagenes</a> <a class="nav-link fw-bold py-1 px-0" href="{% url 'videos' %}">Videos</a> </nav> {% endblock %} {% block content %} <main class="px-10"> <h2>¡Descarga tu Imagen! </h2> {% load archivo_tags %} {% for file in descargas %} <a>{{file.image}}</a> <a href="{{ file.image.url }}" class="btn btn-primary btn-sm" … -
Fixing a typo in models.py and migration for django python project
I'm working on my first django project following along with a youtube tutorial. In models.py while following along I made a typo... crated_at = models.DateTimeField(default=datetime.now) "crated_at" should be "created_at". The typo is reflected in my migrations. I tried changing both models.py and the migrations py file but it leads to an error so I changed it back to "crated". I think the problem is that the database saves the information as "crated_at". I don't want to delete the migration and redo the migrations because from what I read the database is already labeled and it won't fix the problem. Also, I don't mind if it's left as "crated_at" in models.py and the migrations, but at least I would like it to see "created at" when I'm signed in as admin. I want to move on but when I sign in as admin "crated at" is staring me in the face. I feel like this is a good learning moment. Thank you. -
Python DJango avoid assigning variables
def myview(request): category="" brand="" series = "" model="" resolution="" ram="" #some process return render(request ,'mypage.html',{'category':category,'brand':brand,'series':series 'model':model,'resolution':resolution,'ram':ram} Sometimes in my Django projects I have to assign these variables first in my views because of the returning template tags. But doing this way is kinda ugly. Can I avoid assigning these variables in my views? -
Django - Storing user-defined querying logic in a model
I'm making a school app with DRF. Teachers are able to create Exercises and associate them with Tags. An Exercise is thus in m2m relationship with Tag: class Exercise(models.Model): MULTIPLE_CHOICE_SINGLE_POSSIBLE = 0 MULTIPLE_CHOICE_MULTIPLE_POSSIBLE = 1 OPEN_ANSWER = 2 JS = 3 C = 4 EXERCISE_TYPES = ( # ... ) DRAFT = 0 PRIVATE = 1 PUBLIC = 2 EXERCISE_STATES = ( # ... ) exercise_type = models.PositiveSmallIntegerField(choices=EXERCISE_TYPES) state = models.PositiveSmallIntegerField(choices=EXERCISE_STATES, default=DRAFT) text = models.TextField(blank=True) tags = models.ManyToManyField(Tag, blank=True) class Tag(models.Model): name = models.TextField() Teachers can use tags to create quizzes that randomly select exercises with certain tags. In order to do this, there's a Rule model, to which one or more Clauses are related. A Clause is in a m2m relationship with Tag. Let's say a Rule has two Clauses associated; the first clause is associated to tag t1 and t2, and the second clause is associated to t3 and t4. The Rule logic will pick an exercise that has these tags: (t1 OR t2) AND (t3 or t4) class EventTemplateRule(models.Model): pass class EventTemplateRuleClause(models.Model): rule = models.ForeignKey( EventTemplateRule, related_name="clauses", on_delete=models.CASCADE, ) tags = models.ManyToManyField(Tag, blank=True) The actual query is constructed at runtime using repated filter applications and Q objects. … -
Django django-otp non-admin
The following is an excellent article to implement django-otp for admin pages. I tried and it works like a charm. Adding the following two lines in project urls.py seems to do the trick for admin pages: from django_otp.admin import OTPAdminSite admin.site.__class__ = OTPAdminSite OTP for admin I am using django-volt-dashboard. What changes are needed for a similar functionality to access non-admin pages with a regular user? -
Filter object and order by number of filters matched
I have the objects >>> Post.objects.create(name='First post', tags=['tutorial', 'django', 'example']) >>> Post.objects.create(name='Second post', tags=['thoughts']) >>> Post.objects.create(name='Third post', tags=['thoughts', 'django', 'example']) I want to filter the Post objects to match a series of tags: >>> filtered = Post.objects.filter(tags__in=['thoughts', 'django', 'example']) Is there a way to order these results by the number of filters they matched? Wanted result: >>> filtered[0] <Post: Third post> >>> filtered[1] <Post: First post> >>> filtered[2] <Post: Second post> Actual result: >>> filtered[0] <Post: First post> >>> filtered[1] <Post: Second post> >>> filtered[2] <Post: Third post> I'm using Django 3.2.14 -
Django ORM query on fk set
I have a problem with lookup that looks for a value in related set. class Room(models.Model): name = models.Charfield(max_lentgh=64) class Availability(models.Model): date = models.DateField() closed = models.BooleanField(default=False) room = models.ForeignKey(Room) Considering that there is one availability for every date in a year. How can use ORM query to find whether room withing given daterange (i.e. 7 days) has: availability exist for every day within given daterange none of the availabilities has closed=True I was unable to find any orm examples that check whether all objects within daterange exist -
Reverse for 'profileEditor' with no arguments not found. 1 pattern(s) tried: ['regisApp/(?P<pk>[0-9]+)/profileEditor/\\Z']
Hello every one like a lot of people I'm having this ( Reverse for 'profileEditor' with no arguments not found. 1 pattern(s) tried: ['regisApp/(?P[0-9]+)/profileEditor/\Z'] ) I've been trying some of the solution given to other people but with no luck. This is what I'm trying to pass in my home.html menu, is a page were the user can edit their profile <li><a href="{% url 'profileEditor' %}">Edit Profile</a></li> in my url.py I have this path path('<int:pk>/profile_Editor/', editProfilePage.as_view(), name="profileEditor"), And this is my views.py class class editProfilePage(generic.UpdateView): model = Profile template_name = "registration/profileEditor.html" fields = [ 'bio', 'profile_pic', 'website_url', 'facebook_url', 'instagram_url', 'github_url' ] success_url = reverse_lazy('home') I don't get it cuz I did the same process for some of the other pages and they are working fine -
Is there a way to get a function from a user in python with different python functions(ie. if with personalized format)
I'm making a django model that takes a string from the user and that string would be something like '(some var)+15+IF((condition),(passed),(not passed))' and I want it to solve all of this and probably add other personalized functions in the future so mainly for the if this would initially not work with eval from what I looked at. -
Is there a way to create an on_delete function that uses info from the specific model that holds a foreign key in django?
I'm doing one of the problems in the cs50 web course and I made a model for a listing on an auction site. For the sake of avoiding iterating through all bids on a listing, each listing has a Foreign Key called 'current_bid' that points to the latest bid. If the bid were to be deleted though, I want to be able to set the current bid to be the bid that came before it. I've tried several approaches but the one that felt closest to working was making a function local to the model class that gets the lastest bid and tried to make it work by having on_delete call set(last_bid). def last_bid(self): bids = self.bids last = None for bid in bids: if last is None: last = bid elif bid > last: last = bid return last current_bid = models.ForeignKey('Bid', null=True, blank=True, on_delete=SET(last_bid), related_name="running_bids") It doesn't work because calling last_bid this way doesn't give it the needed 'self' parameter. Is there really no way for me to get a reference to the specific listing when the bid it's holding gets deleted?