Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I build a simple website where the user/visitor gives some input via drop down menus and based on that input something specific is displayed?
I want to build a simple web app that has at least a few drop down menus all populated with lists of items. The user selects all the according to his/her preferences and then based on that selection something specific is displayed. Each combination of selections will have to be mapped to a certain result that will be displayed to the user after submitting the selections. I tried googling, but I did not find what I was looking for. I would be grateful if the answer/solution came in Python/Django, but I would welcome it in any other language/framework as long as the end result is the web app I am looking for. Cheers. -
How Do I Make Python Django HTMLCalendar Clickable Based On The Date That Is Clicked?
I'm using a tutorial I found online...and it's working. I'm trying to enhance it so that if the user clicks on the cell of the calendar I pass it a URL to go to another view. Conceptually I get it, but I can't seem to work out the specifics.... Here's my utils.py class Calendar(HTMLCalendar): def __init__(self, year=None, month=None, dropdown=None): self.dropdown = dropdown self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, requests): requests_per_day = requests.filter(Q(start_time__day=day,end_time__day=day) ).order_by('start_time').distinct() d = '' for request in requests_per_day: d += f'<li> {request.get_html_url} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek, requests): week = '' for d, weekday in theweek: week += self.formatday(d, requests) return f'<tr> {week} </tr>' # formats a month as a table # filter events by year and month def formatmonth(self, withyear=True): requests = OncallRequest.objects.filter(Q(oncall_calendar=self.dropdown)).distinct() cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar">\n' cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n' cal += f'{self.formatweekheader()}\n' for week in self.monthdays2calendar(self.year, self.month): cal += f'{self.formatweek(week, requests)}\n' cal += f'</table>\n' cal += f'<h1 class="title107">Oncall Schedule For {self.formatmonthname(self.year, self.month, withyear=withyear)}</h1>\n' return cal Here's the … -
converting dynamic HTML file to PDF
i have question, i try resolve solution more then one week. Now in my project i have dynamic HTML file (receipt), and when client payd for service i send him email, and in this email i put this HTML file. service_email.send_email( RECEIPT, { "address": client_adddress, "nett": nett, "gross": gross, "tax": tax, "tax_rate": tax_rate, }, [client.email], ) And now i need add pdf file to email, and thats no problem, problem in putting data in HTML file and from this file generate PDF. I tryed to use fpdf, pyqt, jinja and other libary, but still noting. -
Django UpdateView - Prevent URL tampering
I have a Contact model. The url.py has: path('contact/update/<int:id>/', views.ContactUpdate.as_view(), name='contact-update'), The UpdateView looks like: class ContactUpdate(UpdateView): model = Contacts form_class = ContactForm template_name = 'contact_detail.html' success_url = reverse_lazy('test:contacts-list') The pk is not included in the fields of the form. class ContactForm(ModelForm): class Meta: model = Contacts fields = ['name', 'company', 'addr1', 'addr2', 'city', 'state', 'zip'] But the pk is sent in the url. The form works in the template and contacts are stored and edited with the above view without issue. However, if a malicious (logged in user) changes the post url to reflect a different pk, Django will happily edit the hacked record. ORIGINAL GET URL: http://test.com/test/contact/update/2/ HACKED POST URL: http://test.com/test/contact/update/3/ Django will update the record with a pk of 3. The session and csrf tokens are all valid, so nothing flags as an error. Is there a way to prevent this besides using a session variable with a uuid that is sent into the form and used on return to get the original pk? Thanks for any advice. -
Django on Google App Engine connection to Cloud SQL, cannot connect
I have a Django app deployed on App Engine. Inside the same project, I've set up a MySQL instance set up with a Private IP. Side Note: I've been using this DB to do local development, and can connect to it via my laptop as I whitelisted the IP address, so I know I can at least connect to it. Per the instructions on the instruction guide found here: https://cloud.google.com/sql/docs/mysql/connect-app-engine-standard I have done the following: Set up my Cloud SQL Instance with a Private IP Set up a Serverless VPC Access connector (this is where I think I'm going wrong) with IP Address Range 10.8.0.0/20 Set my DATABASES dictionary in settings.py to try to connect to each of the following IP addresses with all failing: The private IP (x.x.x.x) listed on the SQL server page, on port 3306. 127.0.0.1 as per the instructions on the google web page. I tried 10.174.0.0 because that's listed as the "Internal IP Range" in the VPC networks area. And finally, out of desperation, 10.8.0.0, because that's the example given as the textbox hint. In the Cloud SQL GUI, I set the "Network" to Default. All failed, but in different ways. The Private IP at … -
Django generic DetailView I want to create and display multiple objects, but what should I do?
model.py class Kcal(models.Model): height = models.PositiveIntegerField(default='', null=False , verbose_name='height') weight = models.PositiveIntegerField(default='', null=False, verbose_name='weight') age = models.PositiveIntegerField(default='', null=False, verbose_name='age') sex = models.CharField(max_length=200, choices=SEX_CHOICE, null=False, verbose_name='sex') view.py class KcalDetailView(DetailView): model = User context_object_name = 'target_kcal' template_name = 'kcalculatorapp/detail.html' def get_context_data(self, **kwargs): try: kcl = self.request.user.kcal men_kcal = round((66 + (13.8 * kcl.weight + (5 * kcl.height)) - (6.8 * kcl.age)) * (kcl.actv)) women_kcal = round((655 + (9.6 * kcl.weight + (1.8 * kcl.height)) - (4.7 * kcl.age)) * (kcl.actv)) if kcl.goal == 'diet': if kcl.sex == 'male': bmr = men_kcal - 500 else: bmr = women_kcal - 500 return bmr else: if kcl.sex == 'male': bmr = men_kcal + 500 else: bmr = women_kcal + 500 return bmr if kcl: context = super().get_context_data(**kwargs) context['bmr'] = bmr context['carb_kcal'] = bmr * (2/3) context['prt_kcal'] = bmr * (1/6) context['fat_kcal'] = bmr - (carb_kcal + prt_kcal) return context except: HttpResponseRedirect(reverse('kcalculatorapp:create')) with the kcal model. Making body information an object. In generic view detail view I used def get_context_date() method. After importing the model object and processing it to templates {{ carb_kcal }} {{ prt_kcal }} I want to put it like this. What should I do? -
Accessing django database from another python script
I have a Django project, and I need to access the information inside that database(model). This is my directory hierarchy- I've seen a lot of questions on this subject, but everything I tried didn't work. For example- import models # gives me this 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. If I try to do this I get another error- import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "OrAvivi.OrAvivi.settings") import models # gives me this error- django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. and it just continues... I'm quite a newbie, spent most of my day on this so I would appreciate some help! -
Costum schema generator drf-yasg to support nested serializers
I built nested serializer where ModelSerializer include another serializer as field. Everything works well but in swagger docs in example body parameters I don't see openning_time field. What can I change to obtain openning_time field in docs? I tried with swagger_auto_schema but got error: drf_yasg.errors.SwaggerGenerationError: specify the body parameter as a Schema or Serializer in request_body serializers.py class WarehouseSerializer(serializers.ModelSerializer): openning_time = OpenningTimeSerializer(many=True, read_only=True) class Meta: model = Warehouse fields = ['pk', 'name', 'action_available', 'openning_time', 'workers'] views.py class WarehouseApi(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet): queryset = Warehouse.objects.all() serializer_class = WarehouseSerializer permission_classes = [IsAuthenticated, ] warehouse_param_config = openapi.Parameter( 'openning_time', in_=openapi.IN_BODY, description='Description', type=openapi.TYPE_OBJECT) @swagger_auto_schema(manual_parameters=[warehouse_param_config]) def update(self, request, *args, **kwargs): return super().update(request, *args, **kwargs) There is screen from swagger docs and i wanted add information about openning_time which is represented as list of dictionaries as below: [ { "weekday": 4, "from_hour": "12:22:00", "to_hour": "13:13:00" }, { "weekday": 5, "from_hour": "16:00:00", "to_hour": "23:00:00" } ] -
what is the best way to use prefetch_related with multitable inheritance and multiple types of discounts for an ecommerce website
i have the following models: class Theme(models.Model): name = mode.charfield() class Category(mdoesl): name = models.charfield() class Product(models.Model): title = models.charfield() class Course(Product): .......... class LtProduct(Product): category = models.ForeignKey(Category) theme = models.ForeginKey(Theme) class CouponCode(models.Model): code = models.Charfield(unique = True) ......... class ProductDiscount(models.Model): product = models.ForeignKey(Product) codes = models.ManyToManyField(CouponCode) class CategoryDiscount(models.Model): category = models.ForeignKey(Category) class ThemeDiscount(models.Model): theme = models.ForeignKey(Theme) class UserCoupon(models.Model): user = models.OneToOneField(User) code = models.ForeignKey(CouonCode) is_used = models.BooleanField(default = False) what I want to do here is first to get the user code and check if that code can be applied to add this product to the user cart, and also fetch the category and theme related to this product and with their discounts and codes too, here's what I was trying to solve this product = Product.objects.prefetch_related('course', 'lvproduct__category__categorydiscount_set__codes', 'lvproduct__theme__theme_discount_set__codes','productdiscount_set__codes').get(id = product_id) and then I would fetch the user redeemed code by this: user_code = UserCoupon.objects.filter(user = user, is_used = False) and then I check by each type of discount to check if the codes belong to these discounts codes = product.productdiscount_set.codes.all() for code in codes: if code == user_code: #do the necessary calculation user_code.is_used = True if the code is not in the product discount codes then I will … -
Oscar Django many categories slow down the site
I've created a site ( Clothing Shop ) which has 426 categories . The site is really slow due to having many categories . ( Even when creating a child category it is saved in Category at the database as seen from shell (oscar category creation)) . I've tried many methods to optimize the queries that are made when a page is loading but still too slow . I've followed the django doc for optimized categories (https://docs.djangoproject.com/en/4.0/topics/db/optimization/) . I've also tried to cache some queries . Moreover the fact that I think the slowness comes from categories is because I've seen that the category queries take the most time through django toolbar .Any help would be great ! . -
django import-export plugin return only 1 row in excel
I have a formset in my DetailView where I am allowing a user to put a number of units in the form and after submission it returns an excel file with exported data. My problem is that I get only 1 row in my exported Excel file and I have no idea why. Could you please take a look at my code and let me know where is the issue? I believe that something is wrong with my loop in the form_valid method but I am not sure what it is. views.py class ProductDetailView(FormMixin, DetailView): template_name = 'hubble/ProductDetailView.html' model = Product form_class = CalculatorFormsetProduct def get_context_data(self, **kwargs): context = super(ProductDetailView, self).get_context_data(**kwargs) get_components = CostCalculator.objects.filter(related_product__slug=self.kwargs['slug']) form = CalculatorFormsetProduct(initial=[{ 'author': self.request.user.email, 'related_product': x.related_product, 'related_component': x.id, 'created': timezone.now, 'number_of_units': 0 } for x in get_components]) context['ce_form'] = form return context def get_success_url(self): return reverse('product', kwargs={'slug': self.kwargs['slug']}) def post(self, request, *args, **kwargs): form = self.get_form() self.object = self.get_object() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): for f in form: related_product = f.cleaned_data.get('related_product') created = f.cleaned_data.get('created') f.save() qs = CERequest.objects.filter(related_product__title=related_product, author=self.request.user, created=created) dataset = CERequestResource().export(qs) response = HttpResponse(dataset.xlsx, content_type="xlsx") response['Content-Disposition'] = 'attachment; filename=cost_estimation.xlsx' return response resources.py class CERequestResource(resources.ModelResource): related_component__service = Field(attribute='related_component__service', column_name='Service') … -
Django : transform a function download view into a class view
I am trying to rewrite a function view that download files into a classview. However I do not see how I can do it, since I have an argument from the url. Then I do not which on of the class view I should be using. Here is my function view that is working : def download(request, fileUUID): file = UploadFilesBlobStorage.objects.get(Uuid=fileUUID) filename = file.Filename file_type, _ = mimetypes.guess_type(filename) url = file.Url blob_name = url.split("/")[-1] blob_content = download_from_blob(blob_name) if blob_content: response = HttpResponse(blob_content.readall(), content_type=file_type) response['Content-Disposition'] = f'attachment; filename={filename}' messages.success(request, f"{filename} was successfully downloaded") return response return Http404 -
Django force commit in drf view
I am trying to force django to commit whenever I call .save() for an object. Because currently, django waits until the end of transaction then commits changes to database which doesn't work for me, because I am trying to update the status of cron on database. I tried to disable atomic transactions using this (https://stackoverflow.com/a/49903525/4087794); @method_decorator(transaction.non_atomic_requests, name='dispatch') class CronAPIView(APIView): ... Then I used transaction.set_autocommit(False) and transaction.commit() to force commit whenever I want but I keep getting this error for set_autocommit; TransactionManagementError: This is forbidden when an 'atomic' block is active. I stuck at this point. Is this even possible ? -
Django export env error : not a valid identifier
I'm coding in Django ,and want to export the env in build.sh ,the env is an email attachment file type list,I have put it in a python list in the build.sh like this: export PROJECT_EMAIL_FILE_TYPE = [".txt", ".doc",".docx","xls","xlsx","csv",".pdf", ".jpg",".png", ".jpeg",".html",".ppt",".1010xml",".1010log",".1010err",".1010zip"] Then I plan to call it from the settings.py PROJECT_EMAIL_FILE_TYPE = os.environ.get('PROJECT_EMAIL_FILE_TYPE ') And then called it any place I want by : settings.AEGIS_EMAIL_FILE_TYPE However when I export it by directly copy that line and enter in Linux there was an Error: -bash: export: `=': not a valid identifier -bash: export: `[.txt,': not a valid identifier -bash: export: `.doc,.docx,xls,xlsx,csv,.pdf,': not a valid identifier -bash: export: `.jpg,.png,': not a valid identifier -bash: export: `.jpeg,.html,.ppt,.1010xml,.1010log,.1010err,.1010zip]': not a valid identifier Any friend can help ? How should I do this properly ? -
Postgres database empty when deploy updates using caprover and wagtail
I'm having an issue that whenever I deploy an update I find my database is empty. I'm using wagtail and any post I created is gone when I deploy an update. I'm running caprover on a VPS on which I deploy my django/wagtail project and have a hosted postgres database that the django project connects to. Also using S3 for static and media storage. I'm finding when I deploy an update every change I have made to the site is gone. I cant quite figure out why. Caprover uses my dockerfile to rebuild the container, perhaps this flushes and rebuilds the datbase? When I connect my dev environment to the same database I don't see the same database items (blog posts) that I created on the production environment side. Obviously I'd like to keep the database entries I create and for them not to get erased when I deploy. I also don't understand why the dev & production environments have their own data, I would have thought if I create a post on one then it'd show on the other. What's gone wrong? -
What is the problem if str:slug is used in django urls?
Hey guys I am building a website with django and I have to use slugs. Model and URL look like this Model slug = models.SlugField(null=False, allow_unicode=True, unique=True) URL urlpatterns = [ path('selectlanguage', views.selectlanguage, name='selectlanguage'), path('i18n/', include('django.conf.urls.i18n')), ] urlpatterns += i18n_patterns( path(_('product/<str:slug>/'), views.product_detail, name='product_detail'), prefix_default_language=False, )+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) When I used slug:slug in urls it doesn't let me change language between slugs it gives me "Reverse" error. But str:slug gives me no problem. My question is, is there any problem of using str:slug over slug:slug that can cause SEO or other problem to the website? I want to know if it causes any issue. Thank you in advance! -
Commit SQL even inside atomic transaction (django)
How can I always commit a insert even inside an atomic transaction? In this case I need just one point to be committed and everything else rolled back. For example, my view, decorator contains with transaction.atomic() and other stuffs: @my_custom_decorator_with_transaction_atomic def my_view(request): my_core_function() return ... def my_core_function(): # many sql operations that need to rollback in case of error try: another_operation() except MyException: insert_activity_register_on_db() # This needs to be in DB, and not rolled back raise MyException() I would not like to make another decorator for my view without transaction atomic and do it manually on core. Is there a way? -
"GET /store/hello/ HTTP/1.1" 405 0 with Class-Based-Views (Django)
I use Class-Based-Views with "post" method as shown below: # "store/views.py" from django.shortcuts import render from django.views import View class Hello(View): # Here def post(self, request): return render(request, 'store/index.html') Then, this is "urls.py" below: # "store/urls.py" from django.urls import path from . import views app_name = "store" urlpatterns = [ path("hello/", views.Hello.as_view(), name="hello"), ] Then, I got this error below: Method Not Allowed (GET): /store/hello/ Method Not Allowed (GET): /store/hello/ Method Not Allowed: /store/hello/ Method Not Allowed: /store/hello/ [03/Aug/2022 22:18:45] "GET /store/hello/ HTTP/1.1" 405 0 So, are there any ways to solve this error? -
How to close connection websocket where user going to another url
So, I Have django app with traffic.py to send data to client (traffic.html) class ClientTraffic(WebsocketConsumer): def connect(self): self.accept() # LOOP here for send traffic when current url is x output = item.generateTraffic() u = float(output['tx-bits-per-second'])/1000000, d = float(output['rx-bits-per-second'])/1000000, self.send(json.dumps({ 'upload': '{:.2f}'.format(u[0]), 'download': '{:.2f}'.format(d[0]), })) sleep(1) My Question is, how I can loop send message to client while the client is in that current url (ex: /traffic/), so when client is change current page (close or go to another path) the websocket connection is close. -
Unable to retrieve Category name using templates in Django
I am working on a Django project and I want to retrieve the category name in my template like Adventure, Hiking.. but instead, it's displaying ids of the category like 1,2,3. Instead of displaying the name of the category, it's displaying me the id of that category. Can someone help me out with this? {% for data in tourData %} {{data.category}} {% endfor %} models.py class Tour(models.Model): category_choices=[('1','Adventure'),('2','Trekking'),('3','Hiking')] category=models.CharField(max_length=1,choices=category_choices,default='1') view.py def recommendations(request): if request.method=='POST': contents=Tour.objects.all() category1= request.POST['category'] #Retrieves the category entered by the user category2=request.POST['place'] tourData = Tour.objects.all().filter(category=category1,place=category2).order_by('-rating').values() context={ 'tourData':tourData } return render(request,"base/recommendations.html",context) else: tourData=Tour.objects.all().order_by('-rating').values() context={'tourData':tourData } return render(request,"base/recommendations.html",context) -
How do I read file data from a method of a FileField subclass in Django?
I'm making a custom field in Django: from mysite.data_parsers import get_csv_data_as_dict from mysite.validators import csv_file_validator from django.db import models class CSVFileField(models.FileField): default_validators = [csv_file_validator] def get_data_as_dict(self): # How do I read the file data here? data = self.? return get_csv_data_as_dict(data) How do I read the filedata in the method? -
unexpected keyword argument 'timeout' on Celery/Redis run on Django
I'm trying to set a environment on AWS (identical to another env I have that runs Celery perfectly) but I'm having this issue when I run celery -A core worker --loglevel=INFO [2022-08-03 12:59:06,633: CRITICAL/MainProcess] Unrecoverable error: TypeError("wrapped_func() got an unexpected keyword argument 'timeout'") I've already tried to upgrade and downgrade celery/redis/kumbu versions and nothing works. I oppened a python shell on this EC2 and tested the Redis connection and its working redis_client = redis.Redis(host=settings.REDIS_URL, port=6379) redis_client.set('key', 'value', nx=True, ex=5) I don't know what am I missing here.. My versions are celery==5.2.7 Django==3.1 django-celery-beat==2.3.0 kombu==5.2.4 redis==4.3.4 pip==22.1.2 setuptools==58.0.0 -
django - track data in formset which haven't been changed
I've created UpdateView with formset. The point is one of field in each formset should be filled after post. this field is calculated in function based on values from main form and some from formset but only when user clicks specific button in template. The user doesn't have to change anything in formset. It's not allowed. I've got code as folows: class DocUpdateView(UpdateView): model = Doc form_class = NewDocForm template_name = 'addatts.html' def get_success_url(self): return reverse('doc_detail', kwargs={'pk': self.object.doc_pk}) def get_context_data(self, **kwargs): context = super(DocUpdateView, self).get_context_data(**kwargs) if self.request.POST: context['form'] = NewDocForm(self.request.POST, instance=self.object) context['formset'] = MyModelFormSet(self.request.POST, instance=self.object) else: context['form'] = NewDocForm(instance=self.object) context['formset'] = MyModelFormSet(instance=self.object) return context def post(self, request, *args, **kwargs): self.object = self.get_object() form_class = self.get_form_class() form = self.get_form(form_class) formset = MyModelFormSet(self.request.POST, instance=self.object) print(f'formset valid: {formset.is_valid()}') if form.is_valid() and formset.is_valid(): return self.form_valid(form, formset) else: return self.form_invalid(form, formset) def form_valid(self, form, formset): self.object = form.save(commit=False) self.object.save() instances = formset.save(commit=False) print(instances) if 'sub_butt_1' in self.request.POST: for instance in instances: # here I wanted do logic with calculations instance.save() return HttpResponseRedirect(self.get_success_url()) def form_invalid(self, form, formset): return self.render_to_response(self.get_context_data(form=form,formset=formset)) Howewer every time I print 'intances' there is only emply list. What am Idoing wrong? -
Redis SADD multiple workers
I am using Redis server version 7.0.0 with Django-Redis. I have multiple workers in production and plan to use Django Redis's get_redis_connection.sadd to add values to a Set() in Redis. When multiple workers do that in Production, will data be lost due to two workers executing simultaneously? I read that Redis's I/O is single-threaded before version 6.0; since I am using 7.0 (I/O multi-threaded), can concurrency issues/race conditions exist? -
Access Django ModelChoiceField form field value inside __init__
I would like to make the certain field in my formset read-only once the value has been chosen. Kind of like this: class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.fields["my_field"].value is not None: self.fields["my_field"].disabled == True Except ModelChoiceField object doesn't have an arguement value and I am not even sure __init__ it is the right place to try access value of a formmset form's field.