Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Which is the best way to get user browsers to re-cache static files when using Django Tenants?
I am using Django Tenants and I am following the Django Tenant's file handling guide. According to this guide, I must use the following setting for managing static files in a multi-tenant environment: STATICFILES_STORAGE = "django_tenants.staticfiles.storage.TenantStaticFilesStorage" This works fine for me. However, I have the challenge of client browsers not re-caching my static files. I came across the Django's ManifestStaticFilesStorage class, which seems like a very good solution to manage changes to static files. However, very sadly, to use it, I must use this setting: STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' This seems to be incompatible with the setting I need for handling static files in my multi tenant project. I believe an option would be to have nginx/gunicorn "tell" browsers to reload static files every time they load my site but I am worried that will make my site too slow... Would anyone know a way I can manage changes to my static files without having to manually change the name of my static files nor to avoid browser caching? Any ideas will be much appreciated. -
Django Inline Formset : render parent foreign key value in template
I have looked through many suggestions but can't get this to work. models.py class TestOrder(models.Model): test_item = models.ForeignKey(TestItem, on_delete=models.CASCADE, limit_choices_to={'is_active': True}) value = models.CharField(max_length=100,null=True, blank=True) report_id = models.ForeignKey('reports.Report', on_delete=models.CASCADE) class TestItem(models.Model): name = models.CharField(max_length=64) group = models.ForeignKey(Group, related_name="test_item_group", on_delete=models.CASCADE,limit_choices_to={'is_active': True}) category = models.ForeignKey(Category, related_name="test_item_category", on_delete=models.CASCADE,limit_choices_to={'is_active': True}) views.py def create_test_result(request, pk): context={} report = Report.objects.get(pk=pk) TestOrderInlineFormSet = inlineformset_factory(Report, TestOrder, fields=('test_item','value', ), extra=0) if request.method == "POST": .... context['formset']= TestOrderInlineFormSet(instance=report) return render(request, "tests-result/test_result.html", context) test_result.html {{ formset.management_form }} {% csrf_token %} {% for form in formset %} {{form.id}} <div class="form-row"> <div class="col-md-5"> <h6>{{form.test_item}}</h6> <small>{{form.test_item.group}}{{form.test_item.category}}</small> </div> <div class="col-md-2"> {{form.value}} </div> </div> {% endfor %} form.test_item gives me select option which is basically i want to be text but i think i can figure it out with widget attribute related to readonly. but I can't find out how i would display form.test_item.group, category or other values. -
Django - get all users permissions?
Hi could anybody help me to get all the permissions for every user in my system , not just for the current logged in, that's the most frequent answer I saw My objetive is that an administrator from the template can assign to each user their permission I don't upload my code because I'm using the basic user model, I think this is generic Please could anyone help me -
Update a Status Graphic in a Web UI
I am considering writing a web ui using python and django. Part of the ui would show status of network equipment, such as turning a power led graphic red when the device turns on, or a network port the color green when it's operational. The graphic representing the network device is a single vector graphic. How do I change the colors of these parts of the graphic? Do I define some areas of the vector graphic as geometric shapes that represent the smaller area of the overall vector image that needs to be updated? This is essentially the same way network device GUIs work for devices like a Netgear switch for example. When you're logged in and using the web ui, there is a small graphic of the switch at the top of the page replicating device status for LEDs and ports and such. Are these graphics made up of multiple smaller graphics somehow so that the program can directly target those elements to change their color/status? -
convert datetime format to 'a time ago' in django
I want to change datetime format to 'a time ago'. I know there are several ways to do that. My first question is what is the best way? (using script in html template, do that in views.py or etc) I write the code in views.py, but datetime doesn't show in template. This is the code for convert datetime: date = float(models.Catalogue.objects.get()) d_str = datetime.datetime.fromtimestamp(date / 1000.0).strftime('%Y-%m-%d %H:%M:%S.%f') d_datetime = datetime.datetime.strptime(d_str, '%Y-%m-%d %H:%M:%S.%f') now = datetime.datetime.now() time_ago = timeago.format(d_datetime, now, 'fa_IR') views.py: class crawler(generic.ListView): paginate_by = 12 model = models.Catalogue template_name = 'index.html' def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) for cat in models.Catalogue.objects.all(): if models.Catalogue.source == 'kilid': date = float(models.Catalogue.objects.get()) d_str = datetime.datetime.fromtimestamp(date / 1000.0).strftime('%Y-%m-%d %H:%M:%S.%f') d_datetime = datetime.datetime.strptime(d_str, '%Y-%m-%d %H:%M:%S.%f') now = datetime.datetime.now() time_ago = timeago.format(d_datetime, now, 'fa_IR') context['time_ago'] = time_ago return context index.html: <div class="card-footer" dir="rtl" style="text-align:right"> <small id="datetime">{{ time_ago }}</small> </div> And then, if I want to write it in a script, how can I do that? -
Whats the reason for decorator returns None in Django?
I am doing a customer relation project in Django and it returns this 'ValueError at /login/' error. I can log into the admin panel and when I logout this error occurs. *ValueError at /login/ The view accounts.decorators.wrapper_func didn't return an HttpResponse object. It returned None instead.* decorators.py from django.http import HttpResponse from django.shortcuts import redirect,render def unauthenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_authenticated: return redirect('home') else: return view_func(request, *args, **kwargs) return wrapper_func def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse('You are not authorized to view this page') views.py from django.shortcuts import render,redirect from django.http import HttpResponse from django.forms import inlineformset_factory from accounts.models import * from .forms import orderForm,createUserForm from .filters import orderFilter from django.contrib.auth.forms import UserCreationForm from django.contrib import messages from django.contrib.auth import authenticate,login,logout from django.contrib.auth.decorators import login_required from django.contrib.auth.models import Group from .decorators import unauthenticated_user,allowed_users,admin_only # Create your views here. @unauthenticated_user def registerPage(request): form = createUserForm() if request.method == 'POST': form = createUserForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') group = Group.objects.get(name='customer') user.groups.add(group) messages.success(request, 'Account was created for ' + username) return redirect('login') context = {'form':form} return render(request, … -
Django : 'str' object has no attribute 'objects' in create_user
This is my registration code def registration_with_js_form(request): if request.method=='POST': first_name=request.POST.get('first_name') last_name=request.POST.get('last_name') mobile_number=request.POST.get('mobile_number') email=request.POST.get('email') password=request.POST.get('password') confirm_password=request.POST.get('confirm_password') checkbox=request.POST.get('checkbox') if checkbox==False: """Redirect with error message""" return redirect('home') if(password!=confirm_password): """Redirect with error message""" return redirect('home') code =''.join(random.choices(string.ascii_uppercase , k=3)) random_str=str(random.randint(10,99))+str(code) username_=first_name+"@"+random_str print(username_) curr_user=Account.objects.create_user(email=email,username=username_, password=password) curr_user.phone_number=mobile_number curr_user.first_name=first_name curr_user.last_name=last_name curr_user.save() """Redirect with success message""" return redirect('home') return render(request,'main/index.html') And this is my Abstract user model ANd IT shows error like this And all of the fields are field with the appropriate data that I filled in that form if I print all of these print([first_name,last_name,mobile_number,email,password,confirm_password,checkbox]) OutPut ['Samir', 'Patil', '1234567890', 'm@gmail.com', '123', '123', 'on'] Please Help.! -
Django: How can I dynamically reload assets into my web pages WITHOUT reloading the whole page?
I'm looking for a solution similar to the one described in the answers to How to force a script reload and re-execute?, but I'd preferably like to have a button on my page that does this when clicked. In other words, I'd like to have a button that when clicked, grabs the newest version of some_script.js that I just saved in VS Code, and injects it into the page. The process would also need to run $.off against all event handlers currently attached to the DOM from the old version of some_script.js, and attach the new ones dynamically. Even better would be a way that I can have the browser do this automatically when I save some_script.js in VS Code. All without having to request the entire page. Is this possible, and if so, do any VS Code extensions already exist for this? MTIA :-) -
How will I implement try or except method in this case?
I want to bring try or except method in this program, where when an invalid user is searched it should return a message "Invalid user". from django.contrib.gis.geos import Point from django.contrib.gis.measure import D from Admin_Section.models import Distance class ServiceProviderList(generics.ListAPIView): serializer_class=ProfilecompletioneSerializer filterset_class=SnippetFilter filter_backends = [DjangoFilterBackend,SearchFilter,OrderingFilter] filterset_fields = ['fullname', 'category','departments','services'] search_fields = ['fullname', 'category__name','departments__dept_name','services__service_name'] def get_queryset(self,*args, **kwargs): pk=self.kwargs.get('pk') customer = CustomerProfile.objects.get(user=pk) Dist=Distance.objects.get(id=1) rad=float(Dist.distance) radius=rad/111 query = ProfileCompletion.objects.filter(location__distance_lte=(customer.location,radius)) return query -
Why am I seeing message for Unapplied Migration(s) after Upgrading Django from 2.0 to 2.2
I upgraded Django from version 2.0 to 2.2. The upgrade completed without any issue. However trying to start the server issues the following message: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 3 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth. Run 'python manage.py migrate' to apply them. March 27, 2021 - 08:37:07 Django version 2.2.19, using settings 'lead.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. My application so far is working fine as before (i.e. prior to upgrade). I have checked the database in migrations table but fine no entry for the reference date. There are also no migration file/s in the app's "migrations" folder. My question is: What are these migrations the system is pointing to? Will it be prudent to go ahead and apply the migrations? Additionally, I am not sure I have come across the following entry at the beginning before the upgrade: Watching for file changes with StatReloader Has it something to with the upgrade? -
how to filter out data using filter if its a foreign key?
I have two models: Profile model class Profile(models.Model): idno=models.AutoField(primary_key=True) name=models.CharField(max_length=30) email=models.CharField(max_length=40) username=models.CharField(max_length=30) def __str__(self): return self.username Connection Request model class ConnectRequest(models.Model): idno = models.AutoField(primary_key=True) sender = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name="sender") receiver = models.ForeignKey(Profile,on_delete=models.CASCADE, related_name="receiver") def __str__(self): return f"{self.sender} to {self.receiver} " when I am trying to filter out all the data where sender is suppose "XYZ" then its giving me an error on the shell obj=ConnectRequest.objects.filter(sender="XYZ") "idno expected a number but got "xyz" i have tried all these things but it still didn't work and gave errors obj=ConnectRequest.objects.filter(sender.name="XYZ") obj=ConnectRequest.objects.filter(Profile.name="XYZ") -
Djano Array agregate on multiple fields
I am using postgres as my backedn in django Application I have 4 models in my app class sprint(models.model): sprintname = models.CharField(max_length=100) ..... class testcases(models.model): testcasename = models.CharField(max_length=100) sprint = models.ForiegnKeyField(sprint) ....... class tags(models.model) tagname = models.CharField(max_length=100) testcase = models.ForiegnKeyField(testcases) class sprinttestcases(models.Model): sprint = models.Foriegnkey(sprint) testcase = model.Foriegnkey(testcase) tag = models.ForiegnKey(tags) Using django templates , I am outputing these values in Ui on a sprint basis like below . Here thhe testcases and tags will be in drop downs How to write django query to get data like this Tried till these , but not sure on how to proceed q= SprintTestcases.objects.filter(something).\ values('sprint_id','testcase_id').annotate(tmlist = ArrayAgg('tag')) -
Render SVG in python Django template
I am trying to render dynamically made SVGs in Django's templates. I am using this svgwrite library to generate a SVG that is returned as an object. What I get in the browser is the object name, but not actual SVG rendered, not getting actual XML os the SVG. How to fix that? In views: import svgwrite def makesvg(): dwg = svgwrite.Drawing('test.svg', profile='tiny') dwg.add(dwg.line((0, 0), (10, 0), stroke=svgwrite.rgb(10, 10, 16, '%'))) dwg.add(dwg.text('Test', insert=(0, 0.2), fill='red')) dwg.save() return dwg In template: <div id="main-div"> <image>{{svg}}<image> </div> Output: <div id="main-div"> <img>&lt;svgwrite.drawing.Drawing object at 0x7f766dcc0b90&gt;<img> </div> -
Django: static file: How make it downloadable
Django, I have a file in static folder and i want to have a download button in my html, onclicking it should download that file I think the headers have to be changed to attachment instead of inline. Something like the specific static file response ["Content-Disposition"]= "attachment; filename=something.someext" So how can i do this in Django. Or what is the best way to do this. Its a fixed file and no need for me to get any information from user or database. -
Django not creating other field, only the date field is created
I have a model but its not creating the other fields except for datefield whenever i do makemigrations from django.db import models from datetime import datetime from django.utils import timezone now = timezone.now() class User(models.Model): user_fname = models.CharField(verbose_name='First Name', max_length=200), user_lname = models.CharField(verbose_name='Last Name', max_length=200), user_email = models.EmailField(unique=True, max_length=200, verbose_name='Email'), user_position = models.CharField(verbose_name='Position', max_length=200), pub_date = models.DateField(default=now) def __str__(self): return self.user_email -
Django - How to prevent rename of filenames for FileFields
I'm trying to make an application with Django that stores fitness exercises with two fields for uploading images. The problem I have is that everytime I change, update, overwrite one of this two image file, the other is renamed by Django itself. Not only, the field that get renamed duplicate the image with another filename. I searched for similar problem but I wasn't able to find the solution. Here my files: models.py from django.core.files.storage import FileSystemStorage from django.db import models from io import BytesIO from PIL import Image import os from django.core.files import File from django.urls import reverse from django.db.models.signals import post_delete, pre_save from django.dispatch import receiver from django.db import models def compress(image): im = Image.open(image) # create a BytesIO object im_io = BytesIO() # save image to BytesIO object im.save(im_io, 'JPEG', quality=70) # create a django-friendly Files object new_image = File(im_io, name=image.name) return new_image def content_file_name1(instance, filename): ext = filename.split('.')[-1] filename = "A_%s.%s" % (instance.id, ext) return os.path.join('exercises', filename) def content_file_name2(instance, filename): ext = filename.split('.')[-1] filename = "B_%s.%s" % (instance.id, ext) return os.path.join('exercises', filename) # Create your models here. .... class Exercise(models.Model): id = models.AutoField(primary_key=True) exercise_name_eng = models.CharField(max_length=255, blank=False) exercise_name_it = models.CharField(max_length=255, blank=False) primary_muscle_group = models.ForeignKey(MusclesGroup, on_delete=models.CASCADE, related_name='primary_muscle', blank=True, … -
How can I get a pk value from ListView and use it?
My code status is Current. If you look at the code, the status is ListView = > DetailView = > DetailView. I want ListView => ListView => DetailView. I want to show only the objects that are referenced by Forey key, not DeatilView. I'm sorry that I can't speak English. models.py class Study(models.Model): study_title = models.CharField(max_length=50, null=False) study_image = models.ImageField(upload_to='images/', blank=True, null=True) def __str__(self): return self.study_title class Studylist(models.Model): post = models.ForeignKey(Study, on_delete=models.CASCADE, related_name='post_name') user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) profile_image = models.ImageField(upload_to='profile/', blank=True, null=True) post_title = models.CharField(max_length=50, null=False) post_content = models.TextField(null=False) content_image = models.ImageField(upload_to='content_image/', blank=True, null=True) created_date = models.DateTimeField(auto_now=True) updated_date = models.DateTimeField(auto_now=True) def __str__(self): return self.post_title views.py class StudyView(ListView): model = Study context_object_name = 'study_list' template_name = 'studyapp/list.html' paginate_by = 6 def get_context_data(self, **kwargs): context = super(StudyView, self).get_context_data(**kwargs) paginator = context['paginator'] page_numbers_range = 5 # Display only 5 page numbers max_index = len(paginator.page_range) page = self.request.GET.get('page') current_page = int(page) if page else 1 start_index = int((current_page - 1) / page_numbers_range) * page_numbers_range end_index = start_index + page_numbers_range if end_index >= max_index: end_index = max_index page_range = paginator.page_range[start_index:end_index] context['page_range'] = page_range return context class StudyListView(DetailView): model = Study context_object_name = 'target_study_list' template_name = 'studyapp/studylist.html' class StudyDetailView(DetailView): model = Studylist context_object_name = 'target_study_detail' … -
DJANGO : Type Error 'an integer is required' AND Type Error 'bool' object is not callable
I am new to DJANGO and have limited experience in coding. I am working through a DJANGO tutorial which involves building a cart. I receive: a type error integer is required on the front end; and a type error bool object no callable in the admin portal when I attempt to manually create the cart. I think the code is a little out of date from the tutorial, but my limited experience means any change I have attempted leads to further errors. The code is as follows: cart/models.py from django.db import models from django.conf import settings from store.models import product, customer from django.contrib.auth.models import User #User = settings.AUTH_USER.MODEL# if included it throws an error 'settings not defined' class CartManager(models.Manager): def new_or_get(self, request): cart_id = request.session.get("cart_id", None) qs = self.getqueryset().filter(id=cart_id) if qs.count()==1: new_obj = False cart_obj = qs.first() if request.user.is_authenticated() and cart_obj.user is None: cart_obj-save() else: cart_obj = cart.objects.new(user=request.user) new_obj = True request.session['cart_id'] = cart_obj.id return cart_obj, new_obj def new(self, user = None): user_obj = None if user is not None: if user is authenticated(): user_obj = user return self.model.objects.create(user=user_obj) class cart(models.Model): user = models.ForeignKey(User, related_name = "user", blank = True, null=True, on_delete=models.CASCADE) product = models.ManyToManyField('store.product') total = models.DecimalField(default = 0.0, … -
Django error when trying to access contact form
Can somebody please prevent me from imploding?!!! I'm trying to create a contact form for my school project, but get this error and have no idea what it means. I've tried googling and couldn't make sense of what the problem is. Error: Traceback (most recent call last): File "C:\Users\01\Desktop\TUD Y2\Sem4\bsp\store\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\01\Desktop\TUD Y2\Sem4\bsp\store\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) Exception Type: TypeError at /contact/ Exception Value: init() takes 1 positional argument but 2 were given admin.py from django.contrib import admin from .models import Contact class ContactAdmin(admin.ModelAdmin): list_display = ['firstname', 'lastname', 'email', 'subject'] list_per_page = 20 admin.site.register(Contact, ContactAdmin) forms.py from django import forms class ContactForm(forms.Form): firstname=forms.CharField() lastname=forms.CharField() email = forms.EmailField() subject = forms.Textarea() models.py from django.db import models class Contact(models.Model): firstname=models.CharField(max_length=200) lastname=models.CharField(max_length=200) email=models.EmailField(null=False) subject=models.TextField() def __str__(self): return f'{self.lastname}, {self.firstname}, {self.email}' urls.py from django.urls import path from .views import ContactView urlpatterns = [ path('', ContactView, name='contact'), ] views.py from django.shortcuts import render from .models import Contact from django.views.generic import View from .forms import ContactForm from django.contrib import messages class ContactView(View): def get(self, *args, **kwargs): form = ContactForm() context = {'form': form} return render("contact.html", context) def post(self, *args, **kwargs): form = ContactForm(self.request.POST) if … -
Django - How to pass data (arguments?) with redirect function
I have a django view where a user uploads a large file. I scrape a ton of information from this file and hold it in memory. I don't want to save this information to the database because it takes too long and I don't need to save it. But I want to continue to use this data in the next view. How do I send along this data using redirect? def view_one(request): if request.method == 'GET': return render(request, 'view_one.html') if request.method == 'POST': uploaded_file = request.FILES['my_file'] info, data = scrape_my_file_for_info_and_data(uploaded_file) return redirect('path_to_view_two', info, data) def view_two(request, info, data): do_stuff_with_info(info) do_stuff_with_data(data) I keep getting errors that I am missing positional arguments 'info' and 'data'. I've tried doing: return redirect('path_to_view_two', info=info, data=data) return redirect(view_two(info, data)) But this doesn't work either. I can't find an example online of how to properly do this and I can't make heads or tails out of the django documentation. Seems there should be an easy way to do this, I just haven't landed on it. Thanks for reading my question! -
Django ModelMultipleChoiceField iterate over elements and check if initialy selected
I have a Django Form with ModelMultipleChoiceField that has some initial vales set. Everything works fine. Then in the template, instead of just printing {{ my_form.multiple_field }}, I iterate over the elements so I can style the whole form as a button group. <div class="btn-group-vertical" data-toggle="buttons" style="width: 90%"> {% for checkbox in filter_opts.categorias_producto %} <div class="btn btn-light btn-sm"> <a style="text-align: left; font-size: 12px;"><span style="display: none;">{{ checkbox.tag }}</span> {{ checkbox.choice_label }}</a> </div> {% endfor %} </div> I want to know how to detect if the element is selected and show the button as selected but I can´t find the way. Any clues welcome. Thanks in advance. -
How to change CSS that Django template uses with a button?
I am trying to implement accessibility option on my page that would change CSS to different file when accessibility button would be clicked. For now, all my templates extends base_generic.html, where style.css is loaded. When accessibility button would be clicked, I wish for it to change to use style_access.css for that user. How can I accomplish that? -
Django migrations applied mid async celery process
I'm not sure this is the correct format for such a question, but worth a shot. Let's assume the following scenario: Django web application with multiple celery workers (running as docker images) Shared DB Once new code is deployed (with migrations applied) - if a worker is executing, it is allowed to finish the task (but no longer receiving any new workload) and then terminated; idle workers are terminated and recreated with new code The running worker is often out of sync with new DB schema - leading to task failures Question is: What would be the right approach to tackle this workflow? Letting running tasks finish is preferred since tasks may be long and painful to restart a couple of times a day... Any thoughts or existing resources would be appreciated. -
Django updates model instead of inserting when calling save()
Im trying to make a web app that has per user models. When logging in as a user with no current models it creates a new model for that user. The problem is that instead of inserting a new model it updates the existing model. The model has 3 fields, user, name and value. upon logging in the logic checks to see if there is model values with the users name in it and if there isn't then it creates a new model, or should. But currently it just updates all rows to associate them with the user that just logged in. This is my code for creation of a new model which is called when a user that has no model associated with it logs in and when a user wants to reset there model. #if there is no models associated with user/ recreate the model is called Board.object.filter(user=user).delete(); #create the new model for row in page_data.get("rows"): for name, value in row.items(): Board(user=user, name=name, value=value).save() -
Why is my Django project getting " An appropriate representation..." error?
I have a Django project where I'm trying to get a request and get data from it. When I do: request_text = 'http://asdfasdf.mx/api/rol/?blabla=2' r = requests.get(request_text) dict = json.loads(r.text) I get the An appropriate representation of the requested resource could not be found on this server. This error was generated by Mod_Security. error. If I access the request through my web browser, I see the results with no problem, however. I have used this code with many other requests, and I had never seen this error until today.