Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.db.utils.ProgrammingError: relation "..." does not exist
I want my User objects in Django to be linked to a Client object (which I create). To do so I extend the User model with a one-to-one link with a Profile class (which I create) class Profile that links User & Client. I followed the instructions from https://simpleisbetterthancomplex.com/tutorial/2016/07/22/how-to-extend-django-user-model.html So far so good. However when I create a User object I dont have access by default to I want my User objects My models.py: from django.contrib.auth.models import User [...] class Client(models.Model): name = models.CharField(max_length=255) address = models.CharField(max_length=255) [...] class Profile(models.Model): need_setup = Client.objects.get(name='NEED TO ADD CLIENT IN ADMIN > PROFILES') user = models.OneToOneField(User, on_delete=models.CASCADE) client = models.ForeignKey(Client, on_delete=models.DO_NOTHING) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() The problem comes when I make my migrations / runserver (my app is called 'dashboard'): django.db.utils.ProgrammingError: relation "dashboard_client" does not exist LINE 1: ...nque_id", "dashboard_client"."date_creation" FROM "dashboard... because of the need_setup = Client.objects.get(name='NEED TO ADD CLIENT IN ADMIN > PROFILES') (no problems if I comment it out). I can work around the problem by manually creating a client in the db called 'NEED TO ADD CLIENT IN ADMIN > PROFILES' and then run my migrations … -
here the after the user is logged in then he can rate the movie and he can rate it only once
here i want to join the two tables and i want that once the user is logged in then he/she can rate a movie and only one user can rate the movie and if the same user tries to rate it again then it should show an error message i have used knox for 3rd party authentication and i want to join the movie and rating table models.py from django.db import models from django.contrib.auth.models import User from django.core.validators import MinValueValidator, MaxValueValidator class Movie(models.Model): title = models.CharField(max_length=128) director = models.CharField(max_length=128) added_by = models.ForeignKey(User, related_name="movies", on_delete=models.CASCADE, null=True) added_at = models.DateTimeField(auto_now_add=True) # rating=models.IntegerField() class Meta: db_table = "Movie" class Rating(models.Model): movies=models.CharField(max_length=128) rating = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(5)]) class Meta: db_table = "Rating" Views.py from rest_framework.response import Response from rest_framework.decorators import permission_classes from rest_framework.permissions import IsAuthenticated from knox.models import AuthToken from TestApp.models import Movie, Rating from TestApp.serializer import UserSerializer, RegisterSerializer, LoginSerializer, MovieSerializer, RatingSerializer from django.shortcuts import render # , RegisterSerializer, LoginSerializer, MovieSerializer class UserAPIView(generics.RetrieveAPIView): permission_classes = [ permissions.IsAuthenticated, ] serializer_class = UserSerializer def get_object(self): return self.request.user class RegisterAPIView(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) class LoginAPIView(generics.GenericAPIView): serializer_class = LoginSerializer … -
For Loop in Object_list where BooleanField value is true
Suppose I have an Announcement model that contains is_important = models.BooleanField() How do I select rows with is_important = True only in for loop? As I want to do a bootstrap carousel for all important announcements. Or is there another way of doing it aside from for loop in object_list? -
Apple's MusicKit JS library example runs fine when rendered by Node.js, fails with Django
For three hours, I've been scratching my head over this. Apple's MusicKit uses JWT tokens to authenticate. When I npm start this Node.js example project, I can generate the JWT token, and then authorize Apple Music and collect the user token in response. This works when executing from localhost:8080. Here is a successful pop-up window. When I launch my Django server locally which also generates valid JWT tokens, running the same exact HTML code with a fresh JWT token, I receive this from Apple: "Problem Connecting: There may be a network issue." The only error on Apple.com's authorization page, is this: vendor-2c0b12a9762d9af673e21ccd8faf615e.js:2325 Error while processing route: woa Failed to construct 'URL': Invalid URL TypeError: Failed to construct 'URL': Invalid URL I have confirmed that both applications are generating valid JWT tokens. I can use the tokens generated in my Django application with Postman directly with Apple API, as well as my token from the Node.js app. I have tried: Using JWT token from Django in the Node.js app -- works Using JWT token from Node.js app in Django -- fails still Allowing all hosts to Django Allowing all CORS traffic to Django Hosting page on an HTTPS valid cert. domain … -
Django removes "@" and other special character from file name
I want to upload a file with filename as email of the uploader. I know this is not a OS file system issue, nor a unsupported python operation because I did save images with this format in python. Now I want to save the images in model(Specifically ImageField). I'm using OverwriteStorage to overwrite images if there is some existing image with same name. Saving the image model = Model.objects.create(email=email) # Blob to image tempfile_io = io.BytesIO() img.save(tempfile_io, 'JPEG') image_file = InMemoryUploadedFile(tempfile_io, None, email + ".jpeg",'image/jpeg',tempfile_io.getbuffer().nbytes, None) print("email is", email) model.pic.save(email + ".jpg",image_file) Model class Model(models.Model): email = models.EmailField() pic = models.ImageField(upload_to="pics", storage=OverwriteStorage()) OverwriteStorage class OverwriteStorage(FileSystemStorage): def get_available_name(self, name, *args, **kwargs): print("name is", name) if self.exists(name): self.delete(name) return name But for some reason, I don't get the exact name in OverwriteStorage-get_available_name. email is xyz@example.com name is xyzexamle.com.jpg Notice how the @ sign is brutally removed. Is there any file name string check i need to disable. How can I make Django use the exact file name given(whenever possible)? -
Pip Install Local v.s Remote Repository Confusion
I am confused as to what exactly pip install (package) does. In my django project, I wanted to install a package and thought that I only needed to include it in the settings.py INSTALLED_APPS. However I also needed to run the command pip install (package) as well. Why is this the case? I thought that pip install only installed packages locally? The package seems to also work through my remote repository from another user as well which is why I am confused -
Fetch specific column in Django using JsonResponse
I have a problem on how can I filter specific column using Jsonresponse in html. I just want to filter specific column Paid_by. It is possible to filter in Jsonresponse just like this response.data.paid_by in my script? I tried response.datas.paid_by but it returns undefined Views.py def sample(): with connection.cursor() as cursor: cursor.execute("SELECT * FROM app_person WHERE paid_by != %s GROUP BY paid_by, paid, category, category_status ORDER BY paid_by,paid", [blank]) row = dictfetchall(cursor) result = {'data':row} return JsonResponse(result) JsonResponse Success html success: function(response){ console.log(response.data) #fetch all data console.log(response.data.paid_by) #Undefined $("#rports").modal('show'); $("#rports").val(null).trigger("change"); } -
Nginx Gunicorn won't redirect to custom error page
I have Nginx -> Gunicorn -> Django web server, where my nginx config looks like this server { listen 8080; server_name mediadbin.n-media.co.jp; client_max_body_size 500M; access_log /home/mediaroot/mediadbin/logs/nginx-access.log; error_log /home/mediaroot/mediadbin/logs/nginx-error.log; server_tokens off; location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Server $host; proxy_set_header X-Real-IP $remote_addr; } location /static { alias /home/mediaroot/mediadbin/mediadbin/static; } location /media { alias /home/mediaroot/mediadbin/mediadbin/media; } error_page 404 500 502 503 504 /500.html; location = /500.html { root /var/www/html/; internal; } } I have 500.html in my /var/www/html/ with chmod 777 for this file. When I trying to access something like www.mediadbin.n-media.co.jp:8080/asfgbdtDbggsfzsd <- it shows default Not Found Page not my 500.html. When I try to access www.mediadbin.n-media.co.jp:8080/500.html it shows this page. What I'm doing wrong? -
Are there security/performance issues if I connect a dockerized web app to an Amazon RDS DB?
I'm developing an app in Django. During the development process, I've used an Amazon PostgreSQL DB (using a free Dev/Test template). The database configuration for the app is straightforward: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'db_name', 'USER': 'postgres', 'PASSWORD': 'db_password', 'HOST': 'AWS_endpoint', 'PORT': '5432' } } I've decided to create a docker image and use Amazon ECS to deploy the app. When I run the app as a docker container, it works just fine with the current database configurations; however, I've not seen any tutorials that discuss this solution to deploying a docker container and a database (i.e. creating an image of the app and using a hosted db solution). As an aside, most of the tutorials show the image being constructed with both the database and Django site on the same image, but that seems like a bad idea. My question: In a production environment, is it acceptable for me to connect my docker container (Django) to my database (Amazon PostgreSQL) in the manner I've described above, only using a new production db instance? At this point, I'm convinced that the answer to my question is obviously stupid (i.e., "of course, why would you ask such a … -
CORS Headers not Working ony With One Specific Endpoint on Django Rest
I have a django 1.10 app with django-cors-headers version 2.0.2. I have set up the settings like this: ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALLOW_ALL = True INSTALLED_APPS = [ ... 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] I have a frontend server on localhost:8080. When I use my local server everything works fine. But when I try to hit my staging server on AWS I get: Access to fetch at 'MY SERVER URL' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. However, the weird thing is that it only happens on one specific endpoint. All the other endpoints work fine on staging server. The endpoint is a basic put() method from a ModelViewSet from the Django Rest Framework. I've tried tweaking the settings in every possbile way I can imagine but I cannot make it work with this endpoint. The endpoint is this one, specifcally the PUT methods is what's throwing the CORS error: class StudentProfileModelViewSet(viewsets.ModelViewSet): queryset = StudentProfile.objects.all() serializer_class = StudentProfileSerializer filter_backends = ( … -
Django rendering context to a header template?
Here is my main.html, i am currently including the header and the footer {% include "store/header.html" %} {% block content %} {% endblock content %} {% include "store/footer.html" %}``` my header.html sample: this is where I am trying to render my cart <div class="shopping__cart"> <div class="shopping__cart__inner"> <div class="offsetmenu__close__btn"> <a href="#"><i class="zmdi zmdi-close"></i></a> </div> <div class="shp__cart__wrap"> {% for item in items %} <div class="shp__single__product"> <div class="shp__pro__thumb"> <a href="#"> <img src="{{item.product.imageURL}}" alt="product images"> </a> </div> <div class="shp__pro__details"> <h2><a href="product-details.html">{{item.product.title}}</a></h2> <span class="quantity">QTY: {{item.quantity}}</span> <span class="shp__price">${{item.product.price|floatformat:2}}</span> </div> <div class="remove__btn"> <a href="#" title="Remove this item"><i class="zmdi zmdi-close"></i></a> </div> </div> {% endfor %} </div> <ul class="shoping__total"> <li class="subtotal">Subtotal:</li> <li class="total__price">${{order.get_cart_total|floatformat:2}}</li> </ul> <ul class="shopping__btn"> <li><a href="cart.html">View Cart</a></li> <li class="shp__checkout"><a href="checkout.html">Checkout</a></li> </ul> </div> </div> I'm trying to render the items to my cart. here is my view: def header(request): category = None categories = Category.objects.all() products = Product.objects.all() if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = {'items':items, 'order':order, 'cartItems':cartItems, 'categories':categories, 'products':products, 'category': category} return render(request, 'store/header.html', context) but I'm not sure how to render it since it's just a header. perhaps I should approach it differently in views. -
Django MFA query
I have a button within my application which is visible to authenticated users (not general public). That button is used to download data to excel. I want to apply extra authentication on that button so that my superuser gets notification before download. I thought of implementing Django MFA so that that authentication code will go to my superuser. But I am stuck at a logic as to how to tie my MFA to this specific button click as oppose to general site authentication. Can you please guide? -
Django - [Errno 13] Permission denied - Win10
I am currently trying to install and set-up Django. I am using windows 10 and python 3.9. When i run pip install django I get the following error: ERROR: Could not install packages due to an EnvironmentError: [Errno13] Permission denied: 'c:\\python39\\Scripts\\django-admin.py'. From reading other questions, adding --user to the command works. However, the command django-admin is still not recognised. Any ideas on how to fix the error? -
inline forms validation errors not in template
I have this model: class dateEvent(models.Model): link = models.URLField(null=True, blank=True) link_description = models.CharField(max_length=30, null=True, blank=True) event = models.ForeignKey('Event', on_delete=models.CASCADE) class Event(models.Model): title = models.CharField(max_length=200) [...] views.py: def event_edit_view(request, id): event = get_object_or_404(Event, id=id) form_event = EventForm(request.POST or None), instance=event) DateEventFormSet = inlineformset_factory(Event, dateEvent, extra=5, can_delete=True, fields=('event', 'start_date_time', 'venue', 'link', 'link_description'), widgets={ 'venue': s2forms.Select2Widget(), 'link': forms.TextInput(attrs={'placeholder': 'http://'}), 'start_date_time': CalendarWidget(), 'description_link': forms.TextInput(attrs={'placeholder': 'Link description'}), }) form_date_event = DateEventFormSet(request.POST or None, instance=Event.objects.get(id=id), prefix="dateEvent", queryset=dateEvent.objects.filter(event__id=id)) if request.method == "POST": if form_event.is_valid() and request.POST['action'] == 'submit': if form_date_event.is_valid(): form_event.save() form_date_event.save() messages.success(request, 'Event updated successfully. See the <a href="/event-detail/' + str(id) + '">detail page</a>') return redirect('my-events') else: raise forms.ValidationError(form_date_event.errors) elif form_event.is_valid() and form_date_event.is_valid() and request.POST['action'] == 'update': form_event.save() form_date_event.save() else: raise forms.ValidationError([form_event.errors, form_date_event.errors]) context = { 'event': event, 'id': event.id, 'form_event': form_event, 'form_date_event': form_date_event, } return render(request, "events/event-edit.html", context) And template: <tbody id='date_body'> {{ form_date_event.management_form }} {{form_date_event}} </tbody> When on the template I input illegal data (say, a non-URL in the URL field) Django throws an error via the ugly debug interface: ValidationError at myurl... ['Enter a valid URL.'] Request Method: POST Or a server error 500 if debug is turned off. Why am I not displaying the error on the template? -
migrations.exceptions.NodeNotFoundError When trying to migrate for production
I have a project which works perfectly locally, but I just deployed to Heroku and whenever i try to migrate it keeps saying django.db.migrations.exceptions.NodeNotFoundError: Migration blog.0002_auto_20210105_0051 dependencies reference nonexistent parent node ('blog', '0001_initial') So I have article if not all the articles concerning this error but not luck, I have deleted all migrations folder content (except init), I used makemigrations (locally) and try to migrate on heroku, Please note, im using a custom user model. SOmehome i know this is the cause of the error. Please help im desperate. -
How to get requested user in clean function in django forms?
Well i want to get requested user in clean function of django forms but i'm unable to do that. I'm trying to get that by simply saying self.request.user , it works in views but not working in forms.py, anybody have an idea how to get requested user in djnago forms ? forms.py class KycModelForm(forms.ModelForm): class Meta: model = KycModel fields = '__all__' def __init__(self, *args, **kwargs): self.request = kwargs.pop('request', None) super(KycModelForm, self).__init__(*args, **kwargs) def clean(self): cleaned_data = super().clean() user = User.objects.get(username=self.request.user) print(user) views.py class KycFormCreateView(CreateView): form_class = KycModelForm model = KycModel template_name = "accounts/kyc/new_kyc.html" def form_valid(self, form): user_kyc = form.save(commit=False) user_kyc.owner = self.request.user user_kyc.save() return super().form_valid(form) -
Django easy-thumbnails getting weird naming with duplicate extensions
I'm using easy-thumbnails, the original file is saved correctly but the thumbnails are being saved with a duplicate file extension: File.jpg File.jpg.100x100_q85.jpg I would like the thumbnails to be named like this: File.100x100_q85.jpg My model looks like this: def image_filename(instance, filename): folder = 'posts/image' _, ext = os.path.splitext(filename) new_name = str(instance.id) + ext return os.path.join(folder, new_name) class Post(models.Model): name = models.CharField(max_length=255, unique=True) image = ThumbnailerImageField(upload_to=image_filename, null=True, blank=True) Since im using Django Rest Framework I created a serializer following this post: Django easy-thumbnails serialize with Django Rest Framework class ThumbnailSerializer(serializers.ImageField): def __init__(self, alias, *args, **kwargs): super().__init__(*args, **kwargs) self.read_only = True self.alias = alias def to_representation(self, value): if not value: return None url = thumbnail_url(value, self.alias) request = self.context.get('request', None) if request is not None: return request.build_absolute_uri(url) return url Does anyone know how I can get the correct naming on my thumbnails? Thanks! -
How can I add an auto increment field in a model based on total count of objects with same field value?
I'm new to the whole Django thing and a bit lost. Sorry if the title is a bit confusing I'll try to clear things out. So basically I have two models (Folder and Document). A Document can have a single Folder as one of its fields using a Foreign Key. Now I have another field in Document that needs to get the value of the total Document objects that share the same Folder and increase by one. I've tried things I read on the docs (aggregation, F() objects, overriding model's save() function) as well as some answers is read here but didn't manage to get it right so I'm posting to get some help. Below is my models.py file with the two models and some comments for better understanding. class Folder(models.Model): category = models.IntegerField() subCategory = models.IntegerField() name = models.CharField(max_length= 50) desc = models.TextField() class Document(models.Model): folder = models.ForeignKey(Folder, on_delete=models.CASCADE) date_created = models.DateField() date_added = models.DateTimeField() #The field below needs to sum all Document objects that share #the same folder value in the database + 1 and set it as its default value f_no = models.IntegerField(default=lambda: Document.objects.aggegate(Count('folder')) + 1) Thank you in advance, any leads or clues are most welcome -
Django - Can't Disable CORS
I'm trying to send a post request to an API using ajax, but when I do it, the error: Access to XMLHttpRequest at 'url' from origin 'http://192.168.0.9:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Searching, I've found this question, and tried literally all solutions in there, but got no success. So, I started thinking that this should be a problem from the API. But I made the request with Postman Desktop and got success. I'll leave my code here: settings.py ALLOWED_HOSTS = ["*"] INSTALLED_APPS = [ "corsheaders", "administrator", "authentication", "oticket", "clients", "crispy_forms", "django.contrib.postgres", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = False Of course there are more settings, but there's no need for it. views.py [...] response = render(request, "payment/finish.html", context) response[ACCESS_CONTROL_ALLOW_ORIGIN] = ( "*" if (settings.CORS_ORIGIN_ALLOW_ALL and not settings.CORS_ALLOW_CREDENTIALS) else origin ) return response view.js $.ajax({ type: "post", url: sessionUrl, crossDomain: true, dataType: "xml", headers: { "Access-Control-Allow-Origin": "*", }, complete: (data, status) => { sessionId = $(data.responseXML).find("id").text(); }, }); -
Django 1.10 ./manage.py shell imports different than virtual env imports
Not quite sure how to word this better, however let me provide an example. I am trying to work with a library called django_nested_admin and am getting an inconsistent error. I am currently using Django 1.10 installed via pip. After reading the django-nested-admin release log, I've decided to use a compatible version of the library (3.0.21). pip install Django==1.10 pip install django-nested-admin==3.0.21 When I navigate in my browser to my admin panel, I receive the follow error: ImportError: no module named admin. A template debug traceback gives me further clues: from django.contrib.contenttypes.admin import GenericInlineModelAdmin /env/lib/python2.7/site-packages/nested_admin/nested.py Immediately, I begin to think that the version of Django I am using does not support the attribute access that is being used for import in the venv filesystem. I decide to verify this hypothesis by using the Django shell. ./manage.py shell from django.contrib.contenttypes.admin import * To my astonishment, everything imports just fine. What exactly is going on here? -
In Wagtail v2 API, how do I filter by a foreign key's string (provided by the __str__ method)
So I have a blog type of website where I'm trying to use the API to get a list of articles filtered by their topic. Here is the relevant portion of my ArticleDetailPage() class with the API field: class ArticleDetailPage(Page): """Article detail page.""" ... topic = models.ForeignKey('articles.ArticleTopic', null=True, blank=True, on_delete=models.SET_NULL) ... api_fields = [ ... APIField('topic', serializer=serializers.StringRelatedField(many=False)), ... ] And here's my ArticleTopic() class: @register_snippet class ArticleTopic(models.Model): """ Article topics that resides in Snippets. """ name = models.CharField(max_length=100) slug = AutoSlugField( populate_from='name', editable=True, max_length=100, verbose_name='slug', allow_unicode=True, help_text='A slug to identify articles by this topic.' ) panels = [ FieldPanel('name'), FieldPanel('slug') ] class Meta: verbose_name = 'Article Topic' verbose_name_plural = 'Article Topics' ordering = ['name'] # Alphabetial ordering def __str__(self): return self.name So far so good, when I take a look at the API list of posts, instead of showing the topic attribute as its ID and other data, it's represented as its string representation (i.e. a topic like space or comets). However, when I try to filter the API by appending: &topic=space to the HTML, I get an error saying: Field 'id' expected a number but got 'space'. Instead of using the StringRelatedField(many=False) serializer, I switched to APIField('topic', serializer=serializers.PrimaryKeyRelatedField(many=False, read_only=True)) … -
how do I use a button to display <div> in django template?
results.html {%if searched_user %} <a href= "{{ searched_user }}">{{searched_user}}</a> <button id=likedsongsbutton>View liked songs</button> <div> {% for each_searched_user in searched_user %} <br id="likedsongs"/>{% for liked_songs in each_searched_user.liked_songs.all %}{{liked_songs}} <br/> {% endfor %} {% endfor %} {% endif %} {% endblock %} </div> <script> document.querySelector("#likedsongsbutton").addEventListener(onclick, ) </script> views.py def results(request): if request.method == "GET": search_query = request.GET.get("username") searched_user = UserProfile.objects.filter( user__username__contains=search_query ) return render( request, "results.html", { "searched_user":searched_user }) My question is how do I make the <div> show only when the button is clicked? I do not know what function to pass in the EventListener -
Django Opening Hours With UTC Support/Timezone Issue
I have a Django application where users can setup stores. I recently added functionality to support opening hours following the advice on this thread - Business Opening hours in Django. My model is almost identical to the one given except each is attached to a "Location" object. Process goes like this - these times are put in in local time by the end user, most datetimes/times being used in my application are in UTC. Originally, I thought I could figure out the timezone of each location object, then whenever I compare something to these OpeningHours, I can just use the given time and the tz (on the associated Location object) to calculate the time in UTC and then it's just a regular datetime comparison. My problem is two fold: I'm not sure this is the best solution, it already feels like I'm overthinking it a bit. The bigger problem - I'm setting the timezones on the Location objects using pytz at the time of object creation. This is to say, it will not auto update for DST or anything like that as far as I know. I could calculate the exact timezone/DST at the time of comparison every time but … -
Django: Parse HTML (containing form) to dictionary
For testing the HTML which gets created by my Django application, I would like to extract the <form>...</form> of the response.content which I get the from the Django TestClient. response = client.get('/foo/') # response contains <form> ...</form> data = parse_form(response.content) data['my-input']='bar' response = client.post('/foo/', data) Imagine the form contains this: <form> <input type="text" name="my-input" value="initial"> </form> Then the result of parse_form(response.content) should be {'my-input': 'initial'} I read the testing responses docs but could not find something like this. -
Django Template not updating in the browser
I have the following HTMl code that have links to the following js svripts <script src="{% static 'js/jquery-3.3.1.min.js' %}"></script> <script src="{% static 'js/bootstrap.bundle.min.js' %"></script> <script src="{% static 'js/lightbox.min.js' %"></script> <script src="{% static 'js/main.js' %"></script> The problem is the files are not loading and I am sure I have the linking done right.Since i linked other stuff (not js) the same way.Here is my settings.py static rout STATICFILES_DIRS = [ Path.joinpath(BASE_DIR, 'btre/static') ] and when inspecting its showing like this What should I Do ? P.s: I tried removing files caches from chrome and tried firefox and chrome still the same issue.