Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery only updates in resulting backend only when we call a task twice(Windows)
I am exploring celery with django, I have observed a very strange thing and I was unable to find any solution of it as of now. I am using the following simple task. @shared_task def add(x, y): return x + y I'm calling the above celery task from one of my class based view, which is following. class CallMe(View): def get(self, request): rr = add.delay(random.randint(1, 999), random.randint(1, 999)) return HttpResponse(f'hellllo world {rr}') it is mapped to the the following url path('', CallMe.as_view()) whenever I'm accessing 127.0.0.1:8000, I have to hit twice to see the any update in the celery command log. I'm using following command for celery celery -A my_proj worker -l DEBUG --pool=solo I am using RabbitMQ as a broker. I have to hit 127.0.0.1:8000 twice to see any update(only the second hit) in celery command log. BUT the celery flower is able to show two tasks(even celery log is showing only one) and it is showing success for both the task with the correct result. ALSO django_celery_results_taskresult is only INSERTING that task which is logged by the celery command log. The other task not even has any record in the django_celery_results_taskresult table, even though it's showing in the … -
Mocking psycopg2 Exceptions in Django Unit Tests
I'm struggling to write unit tests in Django for specific psycopg2 errors that ultimately raise django.db.IntegrityError as the end result. Typically I'd use mock.patch and have the side_effect set to the exception I would like raised. Ex. with mock.patch( "path_to.method_that_throws_integrity_error", side_effect=IntegrityError(), ) as mock_method: self.assertEqual(value, value_two) This works great if I cared about the next steps after every IntegrityError. However, in the case of this test. I only care about the logic in my code that follows psycopg2.errors.UniqueViolation which eventually bubbles up and throws an IntegrityError which I check the error.__cause__.diag.constraint_name and handle logic based on the result. If the UniqueViolation is thrown, I have custom logic that currently performs an action. If an IntegrityError is thrown that is not a UniqueViolation I want the error to raise so I'm alerted that there is an issue. I've tried many things, and cannot mock raise the UniqueViolation so that it sets the same psycopg2.extensions.Diagnostics object as the one that I get from actually throwing the error by violating the unique constraint in my Db. I also cannot set the __cause__ on the IntegrityError as the UniqueViolation. What I would like is something like this - def side_effect(): try: raise UniqueViolation({"constraint_name": "my_unique_constraint"}) … -
Django HTML template tag for date
I get date data from an API on the internet, but it comes as a string. How do I convert this to the following format using django HTML template tag? Current date data format: 2022-02-13 00:00:00 UTC My wish format: 13 February 2022 00:00 My wish another format: 13 February 2022 -
Optimising ModelChoiceField - too much queries on formset.is_valid (post)
I have a query performance problem with formset include form for model with FK. I wrote code according to strategy 2 shown in DjangoCon 2020 | Choose, and choose quickly: Optimising ModelChoiceField - Carlton Gibson. It works for get, but not for post. In POST, even if nothing has changed, during formset.is_valid (or formset.save(commit = False)), I have queries for each FK in each form. In total, there are hundreds of queries about the same (in the example below for SampleModel). How to use initialized choices for formset.save(commit=False)? I have: class MyClass(models.Model): name = models.CharField(max_length=100) sample_model = models.ForeignKey('SampleModel', on_delete=models.PROTECT) ... class MyForm(forms.ModelForm): def __init__(self, *args, **kwargs): sample_model_choices = kwargs.pop("sample_model_choices", None) ... super().__init__(*args, **kwargs) if sample_model_choices: self.fields["sample_model"].choices = sample_model_choices ... class Meta: model = MyClass fields = ['name', 'sample_model', ...] class MyFormSet(BaseModelFormSet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.sample_model_choices = [*forms.ModelChoiceField(SampleModel.objects.all()).choices] ... def get_form_kwargs(self, index): kwargs = super().get_form_kwargs(index) kwargs['sample_model_choices'] = self.sample_model_choices ... return kwargs class Meta: model = MyClass And in view for post: if request.method == "POST": myformset = modelformset_factory(MyClass, formset=MyFormSet, form=MyForm, extra=0, ...) qs = MyClass.objects.filter(... # i also tried prefetching data into qs but it doesn't help formset = myformset(request.POST or None, queryset=qs) if formset.is_valid(): # <- too … -
Django model data not appearing
My model data for my website wont appear on new page when using slug and I am unsure as to why this is happening as I managed to get it to work with the previous page of the website but when I try to call it on my html page nothing will load now and I use the slug in the view to access the page. Models.py class Parasite(models.Model): name = models.CharField(max_length=128, unique=True) slug = models.SlugField(max_length=100, unique=True) description = models.TextField(max_length=100000) image = models.ImageField(upload_to='parasite_images', default='default/default.jpg', blank=True) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Parasite, self).save(*args, **kwargs) def __str__(self): return self.name views.py def view_parasite(request,parasite_name_slug): context_dict = {} try: parasite = Parasite.objects.get(slug=parasite_name_slug) context_dict['parasites'] = parasite except Parasite.DoesNotExist: context_dict['parasites'] = None return render(request, 'parasites_app/viewpara.html', context = context_dict) viewpara.html {% extends 'parasites_app/base.html' %} {% load static %} {% block content_block %} {% for p in parasite %} <h3>{{p.name}}</h3> {% endfor %} {% endblock %} urls.py urlpatterns = [ path('login/', views.user_login, name='login'), path('logout/', views.user_logout, name='logout'), path('admin/', admin.site.urls), path('', views.public, name='public'), path('public/', views.public, name='public'), path('private/', views.logged_in_content, name='private'), path('public/<slug:parasite_name_slug>/',views.view_parasite, name='view_parasite'), path('<slug:post_name_slug>/', views.show_post, name='show_post'), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
cannot connect redis sentinels on django
I'm trying to connect sentinels, but every time we got the same error Exception: Could not connect to any sentinel CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [ { "sentinels": [("redis-cluster.local.svc.cluster.local", 26379, )] , "master_name": "mymaster"} ]} }, } I can't figure out where to put the password key and db key. And do I need to put in the url the sentinels url's ? or service is enough? note: when trying to connect redis/sentinels without channels we do not have any issue at all -
Django show me a none type and a __str__ return
https://dpaste.com/665WCWNNL [My error page][1] [1]:Hi everyone, i have got this error page and i d'ont know why, could you give me a hand please? -
Passing a information between views in DJANGO
so i have this two views, one used to display information and one that returns a file responde. I am trying to download a pdf file using the information on the first view: @login_required() def detail(request, location_name): if request.method == "POST": return search_in_employees(request) current = CurrentInfo() pdf_data = current.detail_employees_by_location(location_name) # this gives me the list of people context = { 'present': current.detail_employees_by_location(location_name), 'location': location_name, } print('Data: -------------->', pdf_data) return render(request, 'user_area/detail.html', context) and my second view just formats it as a pdf: @login_required() def download_pdf(request): buf = io.BytesIO() canv = canvas.Canvas(buf, pagesize=letter, bottomup=0) textob = canv.beginText() textob.setTextOrigin(inch, inch) textob.setFont("Helvetica", 14) lines = [ "Line 1 ", "Line 2 ", "Line 3 ", "Line 4 ", ] for line in lines: textob.textLine(line) canv.drawText(textob) canv.showPage() canv.save() buf.seek(0) return FileResponse(buf, as_attachment=True, filename='employees.pdf') Right now the PDF file only contains dummy data, but how can i pass pdf_data from the first view to the second? -
TypeError: Field 'id' expected a number but got <django.db.models.fields.related_descriptors
I have a simple view for showing all the current users that are conditionally filtered based on the user type that is requesting the data. serializers.py class MyAccountSerializer(serializers.ModelSerializer): image = serializers.ImageField() class Meta: model = User fields = ['id', 'sex', 'type', 'phone', 'image', 'email', 'student_id', 'firstname', 'middlename', 'lastname', 'image', 'joined_date', 'is_active', 'is_superuser', 'is_staff', 'last_login'] views.py class TeacherList(generics.ListAPIView): permission_classes = [IsAuthenticated, ] serializer_class = ListUsersSerializer queryset = User.objects.filter(type=User.TYPES.TEACHER) A simple filter like this works without any errors but since I need to filter the response based on the requesting user this is what I want to use class TeacherList(generics.ListAPIView): permission_classes = [IsAuthenticated, ] serializer_class = ListUsersSerializer # queryset = User.objects.filter(type=User.TYPES.TEACHER) def get_queryset(self): request = self.request.user if request.type == User.TYPES.OWNER: queryset = User.objects.filter( type=User.TYPES.TEACHER, workes=request.owns) elif request.type in [User.TYPES.STAFF, User.TYPES.DIRECTOR, User.TYPES.VICE_DIR]: queryset = User.objects.filter( type=User.TYPES.TEACHER, workes=request.workes) return queryset however this shows me an error that goes like this: Field 'id' expected a number but got <django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager object at 0x0000019D64AE7D60>. I suspect it has something to do with a many-to-many field of which I have one named owns which is what I'm using to filter in 1 of the conditions but don't know why it throws error -
Edit json object in form view, the JSON object must be str, bytes or bytearray, not NoneType
My model has Json Object. class BotContents(BaseModel): class Meta: db_table = 't_bot_contents' name = m.CharField(max_length=200) action = m.JSONField(blank=True, null=True) And in View. class BotContentsUpdateView(LoginRequiredMixin, UpdateView): model = BotContents template_name = 'bot_contents/bot_contents_edit.html' in bot_contents_edit.html {{form.action}} There comes error like this. the JSON object must be str, bytes or bytearray, not NoneType I thought it means the JSON object is already changed into dict. However how can I make the edit form (maybe textare?) in html? -
how can i convert django app to desktop app
I have a Django app up and running on DigitalOcean with Nginx and PostgreSQL. But some clients want an offline version of the app so that their data remains on their systems and they don't have to connect to the internet. One solution is to write the whole app from scratch but that would take time and cost. I was thinking of a solution where I can convert the Django app into a desktop app with minimal changes i.e. replace CDNs with files and remove functionality that requires internet. But I don't know how can I do this. I was thinking of electron, i,e, elctron will spawn a child process which will start django's server and then the electron will load 127.0.0.1:8000 in a webview. But how can I package this app into an executable because it would need python installed and configured on the user's system. Or does python itself has any library that can convert the Django app into a desktop app? Below is the file structure of my Django project project_folder/ app_1/ app_2/ app_3/ configurations/ templates/ __init__.py asgi.py settings.py urls.py wsgi.py media/ staticfiles/ manage.py Any help would be appreciated. -
After Mac OS update Pycharm django python console doesn't have right environmental variable but the "run server" works fine
I am using pycharm as editor of my django app. Everything was working fine until I updated my mac os. After that a lot of settings got messed up for the python interpreter. I managed to fix most of the issue and now I can "run the server" correctly. However, I still can't get the python console to run properly. When I open the console and I try to import a model, I get the following error: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. The thing that kills me is that I have the DJANGO_SETTINGS_MODULE set in my django server environmental variables so it's if the python console was not picking that up. -
Getting <django.db.models.query_utils.DeferredAttribute object at 0x1069ce0d0> instead of values
I wanna write all model fields to text file but i am getting this. How can i fix this. I am making patient register form and after register i wanna see all model fiels on the text file. This code works, i am getting text file but instead of value i have a deferredattribute. Where is my fault? This is my model.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse #from datetime import datetime, date class Post(models.Model): #post_date = models.DateField(auto_now_add = True) soru1 = models.CharField(verbose_name='Ad Soyad',max_length=10000, default="") soru2 = models.CharField(verbose_name='Tarih', max_length=10000, default="") soru3 = models.CharField(verbose_name='Doğum Tarihi', max_length=10000, default="") soru4 = models.CharField(verbose_name='Doğum Yeri', max_length=10000, default="") soru5 = models.CharField(verbose_name='Medeni Hali', max_length=10000, default="") This is my views.py from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post from .forms import PostForm from django.urls import reverse_lazy from django.db.models import Q from django.http import HttpResponse from django.core.files import File #Dosya Kaydetme def writetofile(request): f = open('/Users/emr/Desktop/ngsaglik/homeo/patient/templates/kayitlar/test.txt', 'w') testfile = File(f) kayitlar = Post.objects.all() lines = [] for kayit in kayitlar: lines.append(f'{Post.soru1}') testfile.write(str(lines)) testfile.close f.close return HttpResponse() And here is the result ['<django.db.models.query_utils.DeferredAttribute object at 0x1069ce0d0>', '<django.db.models.query_utils.DeferredAttribute object at 0x1069ce0d0>'] -
Django - how to show a mathematic result as percentage in dango admin
I have created a model that have one field that calculate the percentage of a month profit, the result is a float number rounded to 2 decimals, for example 0.50 I would like to have in the admin list as percentage, for example. 0.50 would show as 50.00%, is that possíble, how can i achieve that? my model: class PortfolioToken(models.Model): total_today = models.FloatField() order_value = models.FloatField() token_price = models.FloatField() month_profit = models.FloatField(editable=False) def save(self, *args, **kwargs): if PortfolioToken.objects.exists(): last = PortfolioToken.objects.latest('id') # month profit would show as percentage in admin self.month_profit = round((self.token_price - last.token_price)/last.token_price, 2) else ... My admin list class PortfolioTokenAdmin(admin.ModelAdmin): list_display =('total_today', 'order_value', 'token_price', 'month_profit') -
ValueError at /modifier_produit/1 ModelForm has no model class specified
this is my forms.py : class stockupdateform(forms.ModelForm): class Meta: model:stock fields =['categorie', 'nom', 'quantite'] my views.py : def list_nom(request): title='liste des produits' form =stockSearchForm(request.POST or None) queryset=stock.objects.all() context= { "title":title, "queryset":queryset, "form":form, } if request.method == 'POST': queryset = stock.objects.filter(categorie=form['categorie'].value(), nom=form['nom'].value()) context= { "title":title, "queryset":queryset, "form":form, } return render(request, "list_nom.html",context) my list_nom.html : <table class='table'> <thead> <tr> <th>id</th> <th>categorie</th> <th>produit</th> <th>quantite</th> </tr> </thead> {% for instance in queryset %} <tr> <td>{{forloop.counter}}</td> <td>{{instance.categorie}}</td> <td><a href="{% url 'modifier_produit' instance.id %}">{{instance.nom}} </a> </td> <td>{{instance.quantite}}</td> </tr> {% endfor %} </table> I have this probleme what i can do : ValueError at /modifier_produit/1 ModelForm has no model class specified. -
Show original data UpdateView
I have class which is the inheritance of UpdateView class BotContentsUpdateView(LoginRequiredMixin, UpdateView): model = BotContents template_name = 'bot_contents/bot_contents_edit.html' form_class = UploadBotContentsForm success_url = reverse_lazy("bot-contents-list") success_message = "success!!" class UploadBotContentsForm(forms.ModelForm): name = forms.CharField(label="name") class Meta: model = BotContents fields = ["name"] in bot_contents_edit.html {{ form.name }} In this case it shows text box automatically. It's quite easy but I want to show the original stored data in BotContents as placeholder. How can I do this? -
peerjs call.on("close") doesnt work. Can anyone help me?
I am developing a django project using with peerjs to make a video call and voice call..In my project everything works fine but if other user reject the my call , call.on("close",...) does not triggered. So I can not close calling modal from screen. document.getElementById("endCallButton").click(); and endCall(); does not work . Can anyone help me to fix that? const peer = new Peer(); var currentCall; peer.on("open", function (id) { $.ajax({ type: "GET", url: "/createPeerIdToUser", data: { 'peerId': id, }, }); }); async function callUser() { // get the id entered by the user const peerId=otherUserPeerId; const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true, }); document.getElementById("chatPart").style.display = "none"; document.getElementById("videoCallPart").style.display = "block"; document.getElementById("video2").srcObject = stream; document.getElementById("video2").play(); // make the call const call = peer.call(peerId, stream); call.on("stream", (stream) => { document.getElementById("video1").srcObject = stream; document.getElementById("video1").play(); document.getElementById("endCallButton").click(); }); call.on("data", (stream) => { document.querySelector("#video1").srcObject = stream; }); call.on("error", (err) => { console.log(err); }); //this part doesnt't triggered call.on("close", () => { document.getElementById("endCallButton").click(); endCall(); }); currentCall = call; } peer.on("call", (call) => { let nameOfuser="" let isSuccess="false"; $.ajax({ type: "GET", url: "/getOtherUserByPeerId", dataType: 'JSON', data: { 'peer': call.peer, }, success: function(data) { document.getElementById("comingRequestButton").click(); document.getElementById("comingRequestName").textContent=data.username; nameOfuser=data.username; isSuccess="true"; }, error: function(err) { console.log(err); }, }); document.getElementById("comingRequestYellow").addEventListener("click", function() { … -
How do I call my Django REST API endpoint with CURL?
I want to call my Django REST Framework API using cURL, but it doesn't do anything. My URL is like "https://MYURL/api/seedevents?secret=SECRET". In postman this works and returns a 201 Created HTTP response. If I call using CURL for example "curl -XGET 'https://MYURL/api/seedevents?secret=SECRET', then it doesn't do anything at all. I can see the request come in in the logs, but it just doesn't do anything. Please can someone advise me what I can do? -
property method and other methods in django models
I have been using the property method every now and then and understand its uses. It basically acts the same as the field but without actually creating a column in db, and can be easily accessed within the serializer as model fields. But how can the other methods be accessed just like this baby_boomer function of Person model here below? How can it be accessed in serializer and also in the views or queryset?? class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) birth_date = models.DateField() def baby_boomer_status(self): "Returns the person's baby-boomer status." import datetime if self.birth_date < datetime.date(1945, 8, 1): return "Pre-boomer" elif self.birth_date < datetime.date(1965, 1, 1): return "Baby boomer" else: return "Post-boomer" @property def full_name(self): "Returns the person's full name." return '%s %s' % (self.first_name, self.last_name) -
My Models info wont appear on new page but it does on the previous one
Within my Django implementation I created a model that would show my information that I stored on the admin in the website. I managed to create the public page to have links of name attribute within the model but when I try to do the same on the viewpara page after going to it from the links I can't manage to get any of the attributes of the model to appear on this page and I am confused as to why. models.py class Parasite(models.Model): name = models.CharField(max_length=128, unique=True) slug = models.SlugField(max_length=100, unique=True) description = models.TextField(max_length=100000) image = models.ImageField(upload_to='parasite_images', default='default/default.jpg', blank=True) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Parasite, self).save(*args, **kwargs) def __str__(self): return self.name views.py def public(request): c = Parasite.objects.all() context = {'c': c} return render(request, 'parasites_app/public.html',context) def view_parasite(request,parasite_name_slug): context_dict = {} try: parasite = Parasite.objects.get(slug=parasite_name_slug) context_dict['parasites'] = parasite except Parasite.DoesNotExist: context_dict['parasites'] = None return render(request, 'parasites_app/viewpara.html', context = context_dict) urls.py path('login/', views.user_login, name='login'), path('logout/', views.user_logout, name='logout'), path('admin/', admin.site.urls), path('', views.public, name='public'), path('public/', views.public, name='public'), path('private/', views.logged_in_content, name='private'), path('viewpara/',views.public,name='viewpara'), path('public/<slug:parasite_name_slug>/',views.view_parasite, name='view_parasite'), path('<slug:post_name_slug>/', views.show_post, name='show_post'), public.html <!DOCTYPE html> {% extends 'parasites_app/base.html' %} {% load static %} {% block content_block %} <h1>Public Page</h1> <h2>Information based on series of Parasites</h2> {% for p … -
Django can't find page to redirect after adding data
I want to add data in my admin panel, but cannot find the page to redirect. The bus is working correctly when I check it with httppresponse but it doesn't redirect after adding the data My directory structure is as follows: AppName/ app/ views.py templates/ admintemplates/ adminpage/ page.html adminurls.py: app_name = "upadmin" urlpatterns = [ path(r'', views.index, name="anasayfa"), path(r'login', views.login, name="login"), path('firma', views.firma_views, name="firma"), path(r'firmaekle', views.firmaekle, name="firmaekle") ] views.py def firmaekle(request): if request.method == 'POST': form = FirmaForm(request.POST) context = { "form":form } if form.is_valid(): firmaek = form.save(commit=False) firmaek.lisanstarihi = datetime.now() firmaek.save() messages.success(request, "Kayıt Başarılı!") return redirect('upadmin:firma') -
Retrieve all data from query
I keep struggling with Django Model, Managers' relations. I have a Profile model, Product Model, and Holding model. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) products = models.ManyToManyField(Product, blank=True, through='Holding') def __str__(self): return str(self.user) class Product(models.Model): product_name = models.CharField(max_length=255, blank=False, unique=True) product_slug = models.CharField(max_length=50, blank=True,null=True) product_symbol = models.CharField(max_length=50, blank=True,null=True) product_price = models.FloatField(blank=True,null=True) def __str__(self): return str(self.product_name) class Holding(models.Model): product_name = models.ForeignKey(Product, on_delete=models.CASCADE) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) product_holding = models.FloatField(max_length=50, blank=True, null=True) def __str__(self): return str(self.product_name) I'm trying to retrieve the data from a user (Profile) for a Product within Holding Basically I want to show the amount of a product a user is currently holding. I'm doing this in my view def show_product_details(request, product_name): product = product.objects.get(Product_name=product_name) ... profile = Profile.objects.get(user = request.user) product_holding = profile.holding_set.get(product_name__product_name = product_name) return render(request, 'productdetails.html', {'product_holding':product_holding ...} But this isn't returning all the data, but instead just the product_name. What am i doing wrong.? :( -
Basic practice for throwing exception/error from function
For example I have script like this def form_valid: temp = form.save(commit=False) try: temp.contents = makecontents() except: messages.error(self.request, error) return self.render_to_response(self.get_context_data(form=form)) messages.success(self.request, self.success_message) return super().form_valid(form) def makecontents(): if (if works well): return "this is my contents" else: return "this is error!!" So, my basic idea is when makecontents() success it returns the string s and set this as member of model instance. However makecontents() failed , I want to return the error to form_valid. So, maybe ,, I should change return "this is error!!" somehow.. Is it possible? , or my idea is wrong?? -
Django Error sub-select returns 3 columns - expected 1
My problem is 2 fold What I'm trying to do I'm trying to create a profile edit form for the teachers profile I'm trying to assign query_sets to the request.POST dictionary and I'm getting this error when I try to filter I noticed that the output of request.POST['course_teaching'] is always the last item in the list instead of all the items in it e.g if request.POST['course_teaching'] = ['1','6'] it gives only 6 The model class ClassLevel(models.Model): readonly_fields = ('id',) level = models.CharField(max_length=100) def __str__(self): return str("{} - {}" .format(self.id, self.level)) # School profile class SchoolProfile(models.Model): school = models.OneToOneField(School, default=1, on_delete=models.CASCADE) classLevel = models.ManyToManyField(ClassLevel) def __str__(self): return "{}" .format(self.school) # Course is list of courses class Course(models.Model): course_name = models.CharField(max_length=100) class_level = models.ForeignKey(ClassLevel, on_delete=CASCADE) def __str__(self): name_level = "{}, {}" .format(self.course_name, self.class_level) return name_level # Teacher Profile class Teacher(models.Model): readonly_fields = ('id', 'course_taught') user = models.OneToOneField(User, default=1, on_delete=models.CASCADE) class_teaching = models.ForeignKey(ClassLevel, null=True, on_delete=models.CASCADE) course_teaching = models.ForeignKey(Course, null=True, on_delete=models.CASCADE) school = models.OneToOneField(School, null=True, max_length=200, on_delete=models.CASCADE) status = models.BooleanField(default=True) The form class profileForm(forms.ModelForm): school = forms.ModelChoiceField(queryset=models.SchoolProfile.objects.all()) class_teaching = forms.ModelMultipleChoiceField(queryset=models.ClassLevel.objects.all()) course_teaching = forms.ModelMultipleChoiceField(queryset=models.Course.objects.all()) class Meta: model = Teacher fields = ['school', 'class_teaching', 'course_teaching',] labels = {'class_teaching':'class_teaching', 'course_teaching':'course_teaching', 'school':'school',} The view def profile_edit(request): form = … -
How to generate a Django one-time download link with expire time
I am uploading files using the filefield model on media-root. Well, now I have a link like this : domain.com/media/file_name.file_extension.I'm asking about the best way to generate a one-time link with expire time from this main link for each user who clicks on file to download it. class files(models.Model): title = models.CharField(max_length=50) picture = models.ImageField(upload_to='imges') desc = models.TextField() created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) download = models.FileField(upload_to='files') def __str__(self): return self.title this is my views: def download(requset ,title): file = get_object_or_404 (files , title=title) try : file = files.objects.filter(title = title) except : raise Http404 context ={ 'file' :file, } return render( requset,'download.html',context) this is my template: <div class="fix download_button"><a href="{{f.download.url}}"></a></div> this is my url: path('download/<str:title>/' , views.download , name='download'),