Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django not rendering background images used in url <style> tag
I am trying to render static image files with Django and this is the first time I have encountered images referenced with the <div class="img" style="background-image: url;"></div> style tag. I will upload the code and the site as is showing when I run the server. <div class="founder d-flex align-items-center mt-5"> <div class="img" style="background-image: url('/static/images/doc-1.jpg');"></div> <div class="text pl-3"> <h3 class="mb-0">Dr. Zen Goode</h3> <span class="position">CEO, Founder</span> </div> </div> This is what the output shows when I run the server. (Of course, it shows other image files here but I assume its just the same): [22/Jul/2022 06:04:36] "GET /static/images/person_2.jpg HTTP/1.1" 404 1816 django.core.exceptions.SuspiciousFileOperation: The joined path (S:\maps.googleapis.com\maps\api\js?key=AIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s&sensor=false) is located outside of the base path component (C:\Wor\dentistt\dentist\static) [22/Jul/2022 06:04:36] "GET /static/images/doc-4.jpg HTTP/1.1" 404 1807 [22/Jul/2022 06:04:36] "GET /static/images/person_1.jpg HTTP/1.1" 404 1816 [22/Jul/2022 06:04:36] "GET /static/images/person_3.jpg HTTP/1.1" 404 1816 [22/Jul/2022 06:04:36] "GET /static/website/https%3A/maps.googleapis.com/maps/api/js%3Fkey%3DAIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s%26sensor%3Dfalse HTTP/1.1" 500 59 [22/Jul/2022 06:04:36] "GET /static/images/person_4.jpg HTTP/1.1" 404 1816 [22/Jul/2022 06:04:36] "GET /static/images/image_3.jpg HTTP/1.1" 404 1813 [22/Jul/2022 06:04:36] "GET /static/images/image_1.jpg HTTP/1.1" 404 1813 [22/Jul/2022 06:04:36] "GET /static/images/image_2.jpg HTTP/1.1" 404 1813 And this is the site: I know that with the 404 error, the files are not being found so how I can render the image correctly here? -
CORS, HttpOnly, CSRFCookie; Django; ReactJS
I have a question. I am developing a webApp. My backend is on xxxx.xxxx.xxxx.xxxx:8000 and my frontend is on xxxx.xxxx.xxxx.xxxx:3000. I am using Django and ReactJS. I have configured my CORS policies on the backend to allow only my fronted to make requests. So. Whenever I have to get CSRF cookies from my backend they come in a response under Set-Cookie with HttpOnly flag. My question is if we are not supposed to extract HttpOnly cookies with the JS how come I still can do that with my ReactJS app. However, whenever I remove that flag I cannot set or retrieve those cookies from the header anymore. Whta is wrong? Or what is right? Help me to understand that please. my django CORS setup: # CSRF Cookie Settings CSRF_COOKIE_AGE: Optional[int] = None CSRF_TRUSTED_ORIGINS = [ 'http://localhost:3000', 'http://xxxx.xxxx.xxxx.xxxx:3000' ] CSRF_COOKIE_HTTPONLY = True # CORS(cross origin resource sharing) settings CORS_ORIGIN_ALLOW_ALL = False CORS_ALLOW_CREDENTIALS = True CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', 'http://xxxx.xxxx.xxxx.xxxx:3000', ] CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'PATCH', 'POST', 'PUT', ] my reactjs request: fetch("http://xxxx.xxxx.xxxx.xxxx:8000/get_csrf",{ method: 'GET', mode: 'cors', credentials:'same-origin', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } }) .then(response => { console.log(...response.headers) response.json() }) .then( (result) => { console.log(this.getCookie('csrftoken')) }, (error) => { … -
How do I get super() to work in python? I keep getting an error message and the only way to get it to go away is to have something inside the ()
How do I get super to work? I'm taking a DJANGO class, everything is working great, but I keep getting an error message and the only way to get it to go away is to have something inside the (). like super(self). Everything I find online has the super() please help me figure out why it isn't working!!! def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context ['my_thing'] = "this is a new headline" return context -
How to Annotate Expense Sum From Another Table Through Fields That Aren't Date or DateTime Field
I am trying to annotate the sum of Interest Expense on Loans that got some Interest Expense during a day. My Data looks like this. Loan id, number type ..., InterestExpense (This is Many to One Model) id, loan_id (FK to Loan) amount day (positive small integer with Validator). (Unfortunately, doesn't respect DD format) month (positive small integer with Validator) (Unfortunately, doesn't respect MM format) year (positive small integer with Validator)(Respects YY format) So given start and end date I need to get sum of amount of InterestExpense for loans grouped by Loan Type. Dilemma I am having is I can't seem to create or annotate a date field out of those day, month, year small integer values. I tried Concat with to_date. But it doesn't like it has 1 digit months. initial_report_data = self.primary_report_model.objects.filter( ... (SOME FILTER) ).select_related('interestexpense').annotate( interest_date=Func( Concat('interestexpense__month', Value('-'), 'interestexpense__year', Value('-'), 'interestexpense__day', output_field=CharField()), Value('MM-YYYY-DD'), function='to_date', output_field=DateField() ) ) I am getting errors of Date Being Out Of Range Because For Month And Day Values, the digits from 1-9 aren't 0 padded. Is there a way I can get any date/datetime/timestamp value from those (Month, Day, Year) Fields So I can see if it is in range of … -
I have this error delete_post() missing 1 required positional argument: 'id' when I click on the delete link
I am trying to develop a function in django to delete a user's own post that he/she uploads to the website but I keep getting the following error. Can someone help me please? I am still relatively new to using Djangoenter image description here urls.py path('delete-post/int:id/',views.delete_post,name='delete-post'), views.py def delete_post(request, id): user = request.user.username user = get_object_or_404(User, id=id) if request.method == 'POST': user.delete() return redirect('home') return render(request, 'index.html') html <a href="delete-post/int:id/{{p_filter.id}}" class="flex items-center px-5 py-4 text-blue-500 hover:bg-lime-600 hover:text-red-500 rounded-md "> <i class="uil-trash-alt mr-1"></i> delete models.py class DeletePost(models.Model): p_id=models.CharField(max_length=500) username =models.CharField(max_length=100) def __str__(self): return self.username I would really appreciate a step by step explanation since my aim is to learn how to delete a post off a website. Thanks! -
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?