Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing JSON from custom view to template
So I have worked with a Django program that was working before, got some code got lost and I managed to recover the most, but have some issues left. I have a class that's building different dictionaries that are supposed to be passed on to the frontend, where there are some Javascript function that's work with that data. My problem is I can't get the pass the data from the view to the template. I have tried to use HttpResponse, but then it just displays the data on a blank screen. I just want to pass it to the template and let the JavaScript functions there work with it. class ReportDashboardView(AuthMixinLineManager, ReportDashboard, generic.TemplateView): """Team report view, build data required for graphs and tables.""" template_name = 'index.html' http_method_names = ['get'] def get(self, request): data_left, data_joined, data_changed_team = self.init_report() data_left = json.dumps(data_left) return HttpResponse(json.dumps(data_left), content_type="application/json") Looks like this I instead just want to "feed" the data to the already existing HTML-template and use the escapejs to access the data that comes from the view. I know the URL-patterns is correct. And here is a example of how the JavaScript functions looks. So my questions is, does anyone have any suggestion on how … -
How to filter many2many field with another many2many?
I have following model in my Django: class Filter(models.Model): min_price = models.PositiveIntegerField(null=False, blank=False) max_price = models.PositiveIntegerField(null=False, blank=False) trait = models.ManyToManyField(Trait, null=True, blank=True) class Flat(models.Model): living_area = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True, db_index=True) trait = models.ManyToManyField(Trait) class Trait(models.Model): name = models.CharField(max_length=255, blank=False, null=False, db_index=True) In my case trait can be for example: elevator. If there is connection between Flat and Trait(name="Elevator") then I can assume that Flat has elevator. What I want to do is to searching flats based on traits - traits from Flat and traits from Filter should be the same. I did somethink like this: filte_obj = Filter.objects.get(pk=pk) flat = Flat.objects.filter(trait__id__in=[x.id for x in filter_obj.trait.all()]) Unfortunately I does not work as I want. I want to see only Flats which Traits QuerySet is the same as Filter's traits QuerySet. How can I do that? -
How can I filter out static logs on Heroku Papertrail for a Django App?
I am trying to filter out logs related to static files on a Heroku/Django App. Based on this answer django - how to filter out GET static and media messages with logging? I added the following code snippet in settings.py def skip_static_requests(record): if record.args[0].startswith('GET /static/'): # filter whatever you want return False return True LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { # use Django's built in CallbackFilter to point to your filter 'skip_static_requests': { '()': 'django.utils.log.CallbackFilter', 'callback': skip_static_requests } }, 'formatters': { # django's default formatter 'django.server': { '()': 'django.utils.log.ServerFormatter', 'format': '[%(server_time)s] %(message)s', } }, 'handlers': { # django's default handler... 'django.server': { 'level': 'INFO', 'filters': ['skip_static_requests'], # <- ...with one change 'class': 'logging.StreamHandler', 'formatter': 'django.server', }, }, 'loggers': { # django's default logger 'django.server': { 'handlers': ['django.server'], 'level': 'INFO', 'propagate': False, }, } } I was able to filter out static logs, but it only works on localhost. How can I get this to work for Heroku Logs and for a logging service like papertrail? -
Django+Twilio: How can I display inside my django app the sms I sent/received using twilio? (Architecture question)
I have a high level architecture question: I built a django app and I integrated with Twilio so that I can send SMS from my django app. Now I am trying to understand if there is a way for me to display the sms I send and receive almost as a chat inside my application. I know this is very high level but I am mostly looking for architecture suggestions, not specific code. Any suggestion? -
How to get field : Django RestFramework
How to get duration field from the table video, In my project there are two tables related to video models.py class Video(BaseModel, Timestamps, SoftDelete): video_name = models.CharField(max_length=254, null=True, blank=True) description = models.TextField(null=True, blank=True) duration = models.DurationField(null=True, blank=True) class VideoDetails(BaseModel, Timestamps, SoftDelete): max_attempt_allowed = models.PositiveSmallIntegerField() amount = models.DecimalField(max_digits=19, decimal_places=2) video = models.OneToOneField(Video, on_delete=models.CASCADE) Here I want to calculate total duration of a course, for that created a function: def get_duration(course_id): print('course', course_id) hour = VideoDetails.objects.filter(video__coursemodulevideos__module_id__coursesectionmodule__section_id__coursesectiondetails__course=course_id).aggregate(Sum('duration')) print('h', hour) "hour = VideoDetails.objects.filter(video__coursemodulevideos__module_id__coursesectionmodule__section_id__coursesectiondetails__course=course_id).aggregate(Sum('duration'))" through the above line how to get duration from video model, give me a solution to fix this situation -
Why is Django giving me a ValueError when I reference a class within the same model?
I'm building a simple recipe app, and so far I have two models: Ingredient and Recipe. Each recipe should have multiple ingredients, so I laid out my model like this: class Ingredient(models.Model): name = models.CharField(max_length=50) class Recipe(models.Model): title = models.CharField(max_length=100) ingredients = models.ForeignKey(Ingredient, on_delete=CASCADE) instructions = JSONField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=SET_DEFAULT, default='Chef Anon') When I makemigrations, I get nothing, but when I migrate, I get this ValueError: ValueError: Cannot alter field cookbook.Recipe.ingredients into cookbook.Recipe.ingredients - they do not properly define db_type (are you using a badly-written custom field?) Following the example here (Django: Add foreign key in same model but different class), I've tried setting ingredients=models.ForeignKey(Ingredient, on_delete=CASCADE) as well as using lazy syntax ingredients=models.ForeignKey("Ingredient", on_delete=CASCADE), but each time, makemigrations shows no changes, and migrate gives me the same ValueError. -
Django Multilanguage - allow users to translate their own input
I'm writing a multilanguage application for renting out property. I've succesfully translated all of the static content inside my application, but the input that the user gives is dynamic and needs to be translated by them. Example: The user needs to create all the different rental types that are available for a client to choose from. However, for each language this type has a different name because it needs to be translated. Ideally, when creating a rental type, the user should see multiple input fields for the name: one for each language. Django should then determine by the client's language which name to show. I've tried using django-modeltranslation and that created some extra columns on my database, but I cannot find a way for a user to edit all of these columns from one view. This is my translation.py # translation.py from modeltranslation.translator import register, TranslationOptions from .models import RentalType, Costs @register(RentalType) class RentalTypeTranslationOptions(TranslationOptions): fields = ('type', 'slug') @register(Costs) class CostTranslationOptions(TranslationOptions): fields = ('name',) Which were succesfully migrated to my database: Migrations for 'main': main\migrations\0014_auto_20211202_1559.py - Add field name_en to costs - Add field name_fr to costs - Add field name_nl to costs - Add field slug_en to rentaltype - … -
How to sort items in template with <select>/<option> tag in Django based app?
Actually, I`m working on E-commerce App using Django Framework. Here I integrated 'blog' app. But I faced an issue with sorting my Posts. #views.py class PostListView(ListView): model = Post template_name = 'article.html' paginate_by = 3 def get_queryset(self): return Post.objects.order_by('-created_at') -
The platform 'undefined' is not currently supported for Docker debugging
I'm following this blog post to debug a containerized Django application with VSCode but it seems I'm getting something wrong. I tried changing some values (ports) but then it says that an error occurred while using the Docker extension. My files looks like this: /docker-compose.yml version: '3.8' services: piola-server: build: context: ./server command: python manage.py runserver 0.0.0.0:8000 volumes: - ./server/:/usr/src/app/ ports: - 8009:8000 - 3002:3002 env_file: - ./server/.env.dev depends_on: - piola-db piola-db: image: postgres:13-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=piola - POSTGRES_PASSWORD=piola - POSTGRES_DB=piola_dev volumes: postgres_data: server/manage.py #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'src.settings') from django.conf import settings if settings.DEBUG: if os.environ.get('RUN_MAIN') or os.environ.get('WERKZEUG_RUN_MAIN'): import debugpy debugpy.listen(("0.0.0.0", 3002)) print('Attached!') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() .VSCode/launch.json: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python: Django", "type": "docker", … -
Admin - do not display "reset" and link to ressource
I created an TabularInline to upload fonts and images I need for a model entry. This comes with django's usual methods: Is there any non-template-hacky way to remove the ressource link (red) and reset (blue) option? -
Django rest framework upload nested form data
I have a front end react.js app that send a form data to a django rest framework end point. Basically, I want to create an order that consists of multiple ads, for now I am testing it using one ad. I am using a function that converts a javascript object to a FormData object from here https://gist.github.com/ghinda/8442a57f22099bdb2e34. As I understood from this function, the FormData object is just a text with a certain syntax, below are some object examples. JavaScript object from browser console {user_id: 'google-oauth2|117955176430010920035', fullname: 'Full Name', email: 'gmail@gmail.com', phone: '', ordertotalprice: 1950, …} ads: Array(1) 0: {display: 1, firstday: '2021-12-2', lastday: '2021-12-15', duration: 13, image: File, …} length: 1 lastIndex: (...) lastItem: (...) [[Prototype]]: Array(0) email: "gmail@gmail.com" fullname: "Full Name" ordertotalprice: 1950 phone: "0000000" user_id: "google-oauth2|11795517643001" [[Prototype]]: Object FormData Object from browser console using the gist.github link from above user_id google-oauth2|117955176430010920035 index.js:25 fullname Full Name index.js:25 email mail@gmail.com index.js:25 phone 00000000 index.js:25 ordertotalprice 1950 index.js:25 ads[0][display] 1 index.js:25 ads[0][firstday] 2021-12-2 index.js:25 ads[0][lastday] 2021-12-15 index.js:25 ads[0][duration] 13 index.js:25 ads[0][image] File {name: 'Picture1.png', lastModified: 1637958641422, lastModifiedDate: Fri Nov 26 2021 22:30:41 GMT+0200 (Eastern European Standard Time), webkitRelativePath: '', size: 1094958, …} index.js:25 ads[0][filetype] image/png index.js:25 ads[0][originalname] Picture1.png index.js:25 ads[0][price] … -
Django (v3.1) PASSWORD RESET LINK: AssertionError at line 260 of django/contrib/auth/views.py assert 'uidb64' in kwargs and 'token' in kwargs
I am having trouble getting past an Assertion error when clicking the password reset link in Django 3.1.2. I have Django running within a Docker container. The emailed link appears to be correct, as it uses the proper domain 'localhost'. However, after clicking the link, the error message replaces the domain 'localhost' with 'Django:8000'. HTML FILES password_reset_email.html {% load i18n %}{% autoescape off %} {% trans "You're receiving this e-mail because you requested a password reset" %} {% blocktrans %}for your user account at {{ site_name }}{% endblocktrans %}. {% trans "Please go to the following page and choose a new password:" %} {% block reset_link %} {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb36=uid token=token %} {% endblock %} {% trans "Your username, in case you've forgotten:" %} {{ user.username }} {% trans "Thanks for using our site!" %} {% blocktrans %}The Super Awesome team{% endblocktrans %} {% endautoescape %} password_reset_confirm.html {% extends "admin/base_site.html" %} {% load i18n %} {% block breadcrumbs %}<div class="breadcrumbs"><a href="/">{% trans 'Home' %}</a> &rsaquo; {% trans 'Password reset confirmation' %}</div>{% endblock %} {% block title %}{% trans 'Password reset' %}{% endblock %} {% block content %} {% if validlink %} <h1>{% trans 'Enter new … -
How to add a class to a field tag in a Django form
I would like to add a bootstrap class to a label of the input field of my form, I can add classes to the input field but I could not find a guide on how to add a class to the label in the form declaration, can you help me? Thanks class MyForm(forms.Form): file = forms.FileField (label="Choose File", widget=forms.ClearableFileInput(attrs={'multiple': True, 'class': 'custom-file-input'})) -
Cannot query "vendor@gmail.com": Must be "CustomUser" instance in Django
views.py @login_required def become_vendor(request): # vendorform = VendorCreationForm() vendordetailform = VendorAdminDetailsForm() if request.method == 'POST': # vendorform = VendorCreationForm(request.POST) vendordetailform = VendorAdminDetailsForm(request.POST, request.FILES) if vendordetailform.is_valid(): # if vendorform.is_valid(): # new_user = vendorform.save() vendordetailform.instance.vendoruser = request.user request.user=vendordetailform.save() print(request.user)-#vendor@gmail.com vendordetails = VendorDetails.objects.get(vendoruser_id=request.user) print(vendordetails) user = CustomUser.objects.filter(id=request.user.id) vendordetails = VendorDetails.objects.filter(vendoruser_id=user.id) vendor_details = vendordetails[0].vendor_details.all() print(vendor_details) # vendor_user = VendorDetails.objects.filter(vendoruser_id=user) user.is_active = False user.save() return render(request,'vendor/preview.html', {'user_details':user_details, 'vendor_details':vendor_details}) else: # vendorform = VendorCreationForm() vendordetailform = VendorAdminDetailsForm() return render(request, 'vendor/become_vendor.html', {'vendordetailform':vendordetailform}) I want to false the logged in user that the user has related field with the User model. Querying the user id that related with this email id in another model causes issue. -
How to customize the admin form for a custom image model in Wagtail CMS?
I need to add a string based unique ID to Wagtail’s image model. These IDs are a relatively short combination of letters, numbers and punctuation, e.g. "AS.M-1.001". So I am using a custom image model with Django’s standard CharField for that with the argument unique=True. But the editing form unfortunately does not check if the ID is unique. So I can use the same ID for multiple images. This check for uniqueness does work in any other standard form in Wagtail, e.g. the Page model. But not for the image model. from django.db import models from wagtail.images.models import Image, AbstractImage class CustomImage(AbstractImage): custom_id = models.CharField(max_length=32, unique=True, null=True, blank=True) admin_form_fields = ( 'custom_id', ) + Image.admin_form_fields My approach would be to override the editing form with a custom one to display more warnings and errors, like you can do with base_form_class for Wagtail’s Page model etc., as documented here. I tried both wagtail.admin.forms.WagtailAdminModelForm as well as wagtail.images.forms.BaseImageForm. from wagtail.images.forms import BaseImageForm from wagtail.admin.forms import WagtailAdminModelForm class CustomImageForm(WagtailAdminModelForm): # add more logic here pass class CustomImage(ArtButlerIDMixin, AbstractImage): ... base_form_class = CustomImageForm Both lead to the same exception: raise AppRegistryNotReady("Models aren't loaded yet.") So a tried to resort the apps in my settings … -
how to realise redirect to same page in Django views?
I am writing an online store in Django. How do I redirect to the same page? This is needed to remove an item from the popup cart. The delete from cart function: def cart_remove_retail(request, slug): cart = Cart(request) product = get_object_or_404(Product, slug=slug) cart.remove(product) return #??? when i try: return HttpResponseRedirect(request.path_info) I get round-robin query. Thanks! -
How to connect MYSQL Data Base to my Django app via an ssh
How to connect my Django app to MySQL DB via ssh. I have a MySQL DB hosted in Namecheap. I can connect to it via ssh using a terminal, is there any way I can do that?? -
HTTPS with Django Gunicorn in AWS ECS Container with Load Balancer
i have a running Docker Container with Django and Gunicorn in ECS with a Load Balancer in front. Everything was working fine until I tried to switch to https. The result is a 504 Gateway Time-out Error. Question is, do I need Nginx with self certificate to handle https or can I do it with AWS Load Balancer ? Thanks, Christian -
Django raw function security (SQLi)
I have been reading through the Django docs & am not sure I am clear whether the below is safe from SQLi. I can see we can also use the cursor Does anyone have any view on this? distinct_skills = skills.objects.raw(''' SELECT distinct category as id from voxi_skills where creator = %s ''', [request.user.username]) -
How to path absolute path for img attribute in html
sorry for this dummy question but i am having a trouble in my django and react app. i have an endpoint which serves the image name but the image is saved in my local directory and in my react app i just want to append the file name like this function Condition(props) { let src = C:/Users/25191/Desktop/python_projects/doctorsolve/Drsove/media/media/images/HealthCondition/${props.meddata.image} return ( <> <div className="item"> <a href="#"> <img src={src} alt="medicine item image" /> <div className="desc"> <p className="medicinename">{props.meddata.title}</p> </div> </a> </div> </> ); } -
AttributeError: 'AnonymousUser' object has no attribute 'profile'
I have built a Django app and it worked well. When I had run an another django app in a port(localhost:8000) and tried the app I built on the port, it says error like this. AttributeError: 'AnonymousUser' object has no attribute 'profile' Here is my code: class DashboardView(auth_views.LoginView): template_name = "dashboard/home.html" verify_email_required = 'registration/verify_email_required.html' form_class = ProfiledAuthenticationForm def get(self, request, *args, **kwargs): # context = {'form': self.form_class()} context = self.get_context_data() context['form'] = self.form_class() if request.user.profile.is_verified: return render(request, self.template_name, context) else: return render(request, self.verify_email_required, context) Note: Initial when I built the app, it worked well, but for now it takes error. when user does not log in, the homepage was redirected to login page. -
How to get Client's IP in Django Views
I have piece of code to extract client IP in Django views. However my code is executing only this ip = request.META.get('REMOTE_ADDR') and I am always getting 127.0.0.1 as IP. Most of the solutions I have searched used below mentioned code. Any other way to do it?? def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[-1].strip() else: ip = request.META.get('REMOTE_ADDR') return ip -
Upload XML Files in Django, Parse XML & Compare with existing models dataset
Can someone give me a better approach for below use case please ? upload XML file Scan XML file with specific tags Store required data in which format ? (I thought of building JSON dump ?) I have data in different models for different components. How can i compare data that i have in step3 with django models and produce some output ? ( Sort of data comparison ) Note : JSON Dump which i get at step 3 is full dump of required data and data at step 4 is being referred to small small chunks of data which has to be combined and compared against recently uploaded file JSON Dump -
Using a GIN index in Django which was created in postgreSQL
I have created a model in Django. class MyModel(models.Model): features = TextField(blank=True, default='') There are several possible ways to store the data in the feature field. Some examples below. feature1;feature2 feature1, feature2 feature1,feature2 And so on. I created a GIN index for that field. That's postgreSQL code I used inside migrations.RunSQL. CREATE INDEX features_search_idx ON "mymodel" USING gin (regexp_split_to_array("mymodel"."features", E'[,;\\s]+')); The migration worked and I managed to find that index using, for example, \di+ mymodel_features_search_idx. Now I would like to use that created index to filter my queryset. I thought something like the code below would work MyModel.objects.annotate(F('features_search_idx')).filter(features_search_idx__in=['Feature1', 'Feature2', 'Feature3'].count() Unfortunately an error occurred django.core.exceptions.FieldError: Cannot resolve keyword 'feature_search_idx' into field.. How can I use my created index? -
how to access an api in react js with axios on same server like django + react js
I have connected the frontend(ReactJS) with backend(python) using Django and axios. How can i post an Api on the Django app using axios from React JS?