Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to only submit form if reCAPTCHA Enterprise was successful with django?
I know that the Google guides for reCAPTCHA are quiet good, but I cannot get past a certain hurdle to make reCAPTCHA work for me on my django website. I thought it was as simple as registering with reCAPTCHA pasting some code into my views.py file or somewhere and that's it, but it seems a lot more complicated on first (and second) glance. :) What I try to achieve is that someone visiting my site can fill in a contact form but only submit it if he or she is not a robot. I registered with reCAPTCHA Enterprise, which seems to be the only version I can register with, although it seems a bit much for a small fella like me...:) my Form looks like this at the moment: <form id="contact-form" method="POST" action="{% url 'send_email' %}"> <a name="contact"></a> <label>Name</label> <input required class="input-field" type="text" name="name"> <label>Betreff</label> <input required class="input-field" type="text" name="subject"> <label>Email</label> <input required class="input-field" type="text" name="email"> <label>Nachricht</label> <textarea required class="input-field" name="message"></textarea> <label>Captcha:</label> <div class="g-recaptcha" data-sitekey="6L..."></div> <input id="submit-btn" type="submit" value="Send"> </form> of course this form does send even if I don't check the "I'm not a Robot" box... How can I go forward from here? Google Guide says I need to … -
Check visitor´s city to build dynamic home page based on it - Django
I'm working on a web app where one can consult a rating of some specific companies. My goal is to develop a dynamic home page that shows top-3 companies in a visitor's city. I´m thinking of the following logic: first, get the visitor´s city and save it as a variable and then use this variable to query the database to get top 3 companies for that city. I´m a very newbie with web apps, so my questions are quite general: Do we always have to get the visitor´s IP in order to check his/her city location? If not, what else can be used to check the city? So far, I´ve seen people using mostly Geodjango with Geoip2 or HTML5 geolocation API (navigator.geolocation). Which one is more preferable for my task? Are there any other packages that could be used? P.S.: We use Django 3.2, python 3.7, SQLite. -
None form fields unexpected in django
I have this django's file forms.py in my project. from django import forms class DateInput(forms.DateTimeInput): input_type='date' class userRequest(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) lat_Origin = forms.FloatField(widget=forms.HiddenInput(attrs={"id":"lat_Origin"}),required=False,initial=181) lon_Origin = forms.FloatField(widget=forms.HiddenInput(attrs={"id":"lon_Origin"}),required=False,initial=181) lat_Dest = forms.FloatField(widget=forms.HiddenInput(attrs={"id":"lat_Dest"}),required=False,initial=181) lon_Dest = forms.FloatField(widget=forms.HiddenInput(attrs={"id":"lon_Dest"}),required=False,initial=181) origin_address=forms.CharField(max_length=200,widget=forms.TextInput(attrs={"class":"data_aux data","id":"origin_address"})) destination_address=forms.CharField(max_length=200,widget=forms.TextInput(attrs={"class":"data_aux data","id":"destination_address"})) I don't know why lat_Origin,lon_Origin,lat_Dest and lon_Dest are None in the post method because they have an initial value of 181. Here you can see the view: def home(request): blablaTrips={} skyscannerTrips={} trips_busTrain={} if request.method == 'POST': form = userRequest(request.POST) if form.is_valid(): print((form.cleaned_data)) Here you can see the result of print(form.cleaned_data). {'lat_Origin': None, 'lon_Origin': None, 'lat_Dest': None, 'lon_Dest': None, 'origin_address': 'Calle Francisco de Enzinas, 2, 09003 Burgos, España', 'destination_address': 'Avenida Diagonal, Barcelona, España', 'date': datetime.date(2021, 6, 11), 'maxPrice': None, 'OrderType': 'NONE', 'OrderBy': 'PRICE'} -
Updating a specific field in a table via form
I'm attempting to update a Model via a table front end in django - no matter what I've tried I can't get this to work with my class based view. Image of the website. from what I understand, the forms.py is trying to insert a new record INSERT VALUES(id, null, null, null ,1) from the example. I've toyed with only using the field that I'm interested in, but it still attempts to create a new field where as I want to update the record in the dataset, i.e update public.product_table set price_checked = 1 where product_id = ... sorry for the amount of code! models.py from django.db import models class ProductTable(models.Model): id = models.AutoField( primary_key=True, editable=False ) product_name = models.TextField(max_length=255,null=False) price = models.DecimalField(max_digits=6,decimal_places=2,null=False) from_date = models.DateTimeField() to_date = models.DateTimeField(null=True) price_checked = models.IntegerField(default=0,null=False) def __str__(self : str) -> str: return f"{self.product_name}" forms.py from django.forms import ModelForm from .models import ProductTable class ProductUpdateForm(ModelForm): class Meta: model = ProductTable fields = '__all__' views.py from typing import Any, Dict from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import redirect from django.views.generic import ListView from .forms import ProductUpdateForm from .models import ProductTable class TableDataView(LoginRequiredMixin,ListView): model = ProductTable context_object_name = 'product' template_name = 'tables/product.html' … -
How to avoid distinct() when filtering on membership in multiple collections?
I'm wrestling with a fairly slow query in django that needs to display users filtered by membership of multiple groups. The resulting list needs to only contain unique users which is fine for small numbers, but becomes quite a problem when returning dealing with large querysets. Unfortunately, modfiying the database structure at this stage isn't really viable as this is a live product with a large active userbase. Basic example of how the current setup looks: class Group( models.Model ): name = models.CharField(max_length=50) class User( models.Model ): name= models.CharField( max_length=100) groups = models.ManyToManyField( Group, related_name='members' ) class UserDisplayModule( models.Model ): display_groups = models.ManyToManyField( Group, related_name='display_modules' ) A view will typically load a module, then list all the users associated with the module via the assigned groups, eg: class UserModuleMembers( ModelViewSet ): def get_queryset(self): user_module = self.get_module() return User.objects.filter(groups__in=module.display_groups.all()).distinct()[offset:offset+limit] The actual models are quite a bit larger in terms of columns, but the relationships are as above really. A User may be a member of multiple groups, and multiple groups may be assigned to a module, hence the need for a distinct() clause here as an individual user may be selected multiple times if they feature in several groups that are … -
Is There A Way to Add A Field to Serializer After Declaring It?
I am want something like this: def get_user_serializer_class(include_section_name): class UserSerializer(serializers.ModelSerialzer) section_name = serializer.CharField(source='section.name') class Meta: model = User fields = ['username', 'section_name'] return UserSerializer But at the runtime, while defining the UserSerializer, I don't know whether to add section_name or not. It will be decided by include_section_name. I am writing something like this to acheive it: def get_user_serializer_class(include_section_name): class UserSerializer(serializers.ModelSerialzer) class Meta: model = User fields = ['username'] + ['section_name'] if include_section_name else [] if include_section_name: setattr(UserSerializer, 'section_name', serializer.CharField(source='section.name')) return UserSerializer But it's not working for me. Is there a way to achieve this goal? -
Django RSS feed showing ip in <link> instead of domain
I have a Django website, recently I added the RSS feed. I noticed that the resulting feed is showing the ip of the hosting instead of my domains: <link>http://12.324.6.789/articles/</link> Here below the code from django.contrib.syndication.views import Feed from django.template.defaultfilters import truncatewords from django.urls import reverse from django.utils.feedgenerator import Atom1Feed class blogFeed(Feed): title = "BLOGTITLE" link = "/articles/" description = "RSS feed of BLOG" def items(self): return ArticlePage.objects.live().order_by('-date_display')[:10] def item_title(self, item): return item.title def item_link(self, item): return item.full_url and this route # RSS route path("rss/", blogFeed(), name ="feed"), Any suggestion? -
static files in python using css
<html> <head> <title> <link rel="stylesheet" href="//maxcdn.bootstrap.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link rel="stylesheet" href={% static 'css/blog.css' %}"> <link href="//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext" rel="stylesheet" type="text/css"> </head> <body> <div> <h1><a href=" ">Cradle's Blog</a></h1> </div> {{ % for post in posts }} <div> <p> published: {{ post.published_date }}</p> <h1><a href=" ">{{ post.title }}</a></h1> <p>{{ post.text|linebreaksbr }}</p> </div> {{% endfor %}} </body> </html> the error I'm getting states; Invalid block tag on line 6: 'static'. Did you forget to register or load this tag?... how do I perform this action? -
django social auth does not return user
I have a django application that uses django social auth to authenticate users with Google. It was working just fine and then....suddenly it stopped. I have no clue why. I've tried everything I can think of. Here's my social auth pipeline: SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'myapp.custom_social_auth_pipeline.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'myapp.custom_social_auth_pipeline.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) And here's the code on my custom_social_auth_pipeline: from django.contrib.auth.models import Group, User from django.shortcuts import redirect USER_FIELDS = ['username', 'email'] def create_user(strategy, details, backend, user=None, *args, **kwargs): print("CREATE USER CALLED") <-- this is never called! :( if user: return {'is_new': False} fields = dict((name, kwargs.get(name, details.get(name))) for name in backend.setting('USER_FIELDS', USER_FIELDS)) try: if User.objects.get(email=fields['email']): return {'is_new': False, 'user': User.objects.get(email=fields['email'])} except: pass if not fields: return fields['is_staff'] = True user = strategy.create_user(**fields) staff = Group.objects.get(name='Staff') user.groups.add(staff) return { 'is_new': True, 'user': user } def auth_allowed(backend, details, response, *args, **kwargs): print ("AUTH ALLOWED CALLED") <-- this prints in my logs print(details) <-- this returns the correct user if not backend.auth_allowed(response, details): return redirect('/') It's not returning any error and it is not redirecting to our "error" url. It's just behaving like it does if no one is signed in (the app has a public-facing page that is for … -
How to pass data from django to js from html template
I have following files as mentioned below and I want to know how can I pass the django username to js in the index.html file view.py file from django.shortcuts import render from django.contrib.auth.decorators import login_required from .models import Message import json def index(request): return render(request, 'chat/index.html') @login_required def room(request, room_name): messages = Message.objects.filter(room=room_name)[0:25] return render(request, 'chat/room.html', {'room_name': room_name, 'username': json.dumps(request.user.username),'messages': messages}) models.py file from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Message(models.Model): username = models.ForeignKey(User, related_name='author_message',on_delete=models.CASCADE) room = models.CharField(max_length=255) content = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('date_added',) def __str__(self): return self.author.username script in index.html <script> document.querySelector('#room-name-input').focus(); document.querySelector('#room-name-submit').onclick = function(e) { var roomName = document.querySelector('#room-name-input').value; var userName = JSON.parse( {{ username|safe }} ); window.location.replace(roomName + '/?username=' + userName); }; </script> -
Django Error During Template Rendering - Need 2 values to unpack in for loop; got 13
The View processes the forms post request and creates the new context to pass to my template 'home.html'. If this template is rendered with 'dimensions' the template is meant to loop through the dimensions displaying the keys and values of this dictionary. I attempted {% for key, value in dimensions.dimensions %} however this yielded a quote_from_bytes() expected bytes error which I did not fully comprehend. How can I adjust my logic to properly evaluate the keys and values of the dimensions dictionary? Django View def tunnel_frame_input_form(request): """Frame measurements""" inner_frame_h = float(request.POST['IFH']) outer_frame_h = float(request.POST['OFH']) inner_frame_w = float(request.POST['IFW']) outer_frame_w = float(request.POST['OFW']) haunch_depth = float(request.POST['HAD']) haunch_height = float(request.POST['HAW']) side_thickness = outer_frame_w - inner_frame_w top_thickness = outer_frame_h - inner_frame_h dimensions = { 'inner_frame_h': inner_frame_h, 'outer_frame_h': outer_frame_h, 'inner_frame_w': inner_frame_w, 'haunch_depth': haunch_depth, 'haunch_height': haunch_height, 'side_thickness': side_thickness, 'top_thickness': top_thickness, } image = None context = { 'dimensions': dimensions, 'image': image, } return HttpResponseRedirect(render(request, 'home.html', context)) Django Template {% extends 'base.html' %} {% block title %} 2D Tunnel File{% endblock %} {% block content %} <div class="container"> <div class="row mt-4"> <div class="col-6"> <form class="" action="process/" method="post"> {% csrf_token %} <label for="frame description" class="form-label">Input Frame Dimensions</label> <div class="input-group mb-3"> <span class="input-group-text" id="input">default units = mm</span> <input type="text" class="form-control" … -
'python manage.py collectstatic' is still collecting static to C drive instead of s3 bucket, am I missing something?
I am trying to use s3 bucket with django (I have done this like twice before) but this time, after installing boto3 and django-storages and assigning correct values to necessary variables in settings.py, python manage.py collectstatic is still collecting static files to a local directory on my computer instead of s3 bucket. Below is my settings.py... settings.py INSTALLED_APPS = [ ... "storages", ] AWS_ACCESS_KEY_ID = "*****" AWS_SECRET_ACCESS_KEY = "******" AWS_STORAGE_BUCKET_NAME = "****" AWS_S3_CUSTOM_DOMAIN = "%s.s3.amazonaws.com" % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=86400"} AWS_DEFAULT_ACL = None AWS_LOCATION = 'static' STATICFILES_DIRS = [ BASE_DIR / "build/static", #this is the correct path by the way! ] STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' terminal (env) C:\Users\LENOVO\Desktop\project> python manage.py collectstatic You have requested to collect static files at the destination location as specified in your settings: C:\Users\LENOVO\Desktop\project\staticfiles This will overwrite existing files! Are you sure you want to do this? According to all tutorials and my expectation, collectstatic is supposed to be collecting my static files into my s3 bucket.. Am I missing something?? Thanks for your time! -
How to use Nuxt auth with a Django server to login with Google
I'm using nuxt-auth to handle my session based authentication, it works perfect with local strategy, but it has been a disaster trying to make it work with Google strategy, after solving a lot of issues (redirect_uri, challenge_code, etc), my current problem is that after I choose a Google account it redirects me to the defined redirect_uri and there nothing happens, nuxt auth is not calling the api endpoints to validate the session key. I've tried with @nuxtjs/auth ^4.9.1 and @nuxtjs/auth-next but none of then work. The local strategy just calls the API method and it returns a Set-Cookie header which is applied correctly, but as I told before, the call to the API is not being done by Google strategy. Here is my code: nuxt.config.js modules: [ ..., //'@nuxtjs/auth' '@nuxtjs/auth-next' ], auth: { local: { endpoints: { login: { url: 'auth/login/', method: 'post', propertyName: false, withCredentials: true }, logout: { url: 'auth/logout/', method: 'post' }, user: { url: 'user', method: 'get', propertyName: false, withCredentials: true, autoFetch: true } }, tokenRequired: false, tokenType: false, }, google: { clientId: my_client_id, redirectUri: isProd ? "example.org" : "http://localhost:3000", codeChallengeMethod: "", responseType: "token id_token", tokenKey: "id_token", endpoints: { token: isProd ? "example.org" : "http://localhost:8000/api/auth/google", // … -
Getting KeyError at /vaccine 'sessions' in django
Hi I making a page where user can enter pincode for their respective state and can get availability of vaccine in their area. But I am getting KeyError at /vaccine 'sessions' in django But I remove the pincode option from views and put a specific code i.e, pincodeU = '110046' then it will work. my views.py def vaccine(request): today = date.today() d1 = today.strftime("%d-%m-%Y") pincode = request.POST.get('pincode') pincodeU = str(pincode) # if I remove above two line and put pincodeU = '110046' then it will work baseurl = 'https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/findByPin?pincode={}&date={}'.format(pincodeU,d1) vaccine = requests.get(baseurl) data = vaccine.json() vaccinedata = data["sessions"] return render(request, 'vaccine_data.html', {'vaccinedata':vaccinedata})90 vaccine_data.html {% extends 'base.html' %} {% block title %}Home{% endblock title %} {% block body %} <div class="form-control"> <form method="POST"> {% csrf_token %} <label for="pincode">Enter Pincode</label> <input type="text" name="pincode"> <button type="submit">submit</button> </form> <table class="table table-bordered"> <thead> <tr> <th scope="col">#</th> <th scope="col">Center ID</th> <th scope="col">Name</th> <th scope="col">Address</th> <th scope="col">Fee Type</th> <th scope="col">Vaccine</th> <th scope="col">Age limit</th> </tr> </thead> <tbody> {% for i in vaccinedata %} <tr> <th scope="row">{{forloop.counter}}</th> <td>{{i.center_id}}</td> <td>{{i.name}}</td> <td>{{i.address}}</td> <td>{{i.fee_type}}</td> <td>{{i.vaccine}}</td> <td>{{i.min_age_limit}}</td> </tr> {% endfor %} </tbody> </table> </div> {% endblock body %} urls.py from django.urls import path from home import views from django.conf.urls import * urlpatterns = … -
Not sure how my /etc/systemd/system/gunicorn.service file should look like on digital ocean
Files on digital ocean: -> root -> templates -> static -> manage.py -> myapp -> mainpage -> aboutpage -> ve (virtual environment) This is what my /etc/systemd/system/gunicorn.service file currently looks like: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=x Group=www-data WorkingDirectory=/root ExecStart=/root/vr/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ myapp.wsgi:application [Install] WantedBy=multi-user.target What do i need to change? im not really sure how it should look. -
Django how to redirect back to list page after update data?
In a ListView I render a table using the Paginator with paginate_by = 5 . In each row I have a Button that opens the UpdateView . After a successful update I’m back on my ListView but always on the first page. How can I change the success_url so that I’m back on the page number, from where I opened the UpdateView ? Is there a proper way in Django to solve this? class ApproveCommentPage(PermissionRequiredMixin,UpdateView): raise_exception = True permission_required = ("blog.add_commentblog","blog.change_commentblog","blog.delete_commentblog","blog.view_commentblog") model = BlogComment template_name = "approve_comment.html" form_class =AdminComment def get_success_url(self): return reverse_lazy('blog-admin') -
Django package is not getting installed in virtualenv
The many times I am trying to install Django in a virtual environment in Python 3.9. It's showing an OSError and the package is not getting installed. Kindly help me resolve this issue. -
Django passing a list of tuples in a form and getting it in the view
I have a list of tuples in this format: [(a,b,c), (d,e,f),(g,h,i)]. For some reasons, I need to pass it as a hidden field in my form and in my views I need to retrieve it. However, Im not able to do it. Here is my code snippet: html template <form id="form1" action="{% url 'job_recommendations' %}" method="POST"> {% csrf_token %} <a onclick="document.getElementById('form1').submit();">View more recommendations&nbsp</a <input type="hidden" name="recommendations" value="{{ job_recommendations }}"> #it is the list that I want to pass. It already has correct values </form> views.py def job_recommendations(request): if request.method == "POST": recommendations = request.POST['recommendations'] for job, recruiter, percentage in recommendations: print(percentage) return render(request, 'recommendations.html') -
Django Channels running through daphne in azure rejects websockets connections (503 error)
I'm developing a web app using Django Channels. It needs to serve HTTP requests and also accept websockets connections. In local everything runs fine, but I'm having trouble in Azure. It rejects the websockets connections (HTTP code 503). I've tried everything I found, but I can't seem to solve it. I think the problem is with daphne or azure load balancers, because there's nothing relating to the failed connections on the logs. I'm using App Service on Azure with python (3.8). The websockets switch is on, and the startup command is: daphne -b 0.0.0.0 bstore_server.asgi:application -v 3 My asgi.py file is: import os from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application # Important que vagi aquí dalt os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bstore_server.settings.production') asgi_application = get_asgi_application() from channels.auth import AuthMiddlewareStack import bstore_server_app.routing application = ProtocolTypeRouter({ 'http': asgi_application, 'websocket': AuthMiddlewareStack( URLRouter( bstore_server_app.routing.websockets_urlpatterns ) ), }) And here's my client (needless to say it works on the local server): import asyncio import websockets import json import ssl from websockets.exceptions import ConnectionClosedError, WebSocketException station_id = '0824201' # uri = f'ws://127.0.0.1:8000/ws/station/{station_id}/' uri = f'wss://bstore-test.azurewebsites.net/ws/station/{station_id}/' ssl_context = ssl.create_default_context() ssl_context.options |= ssl.PROTOCOL_TLS async def server_connect(): while True: try: async with websockets.connect(uri, ssl=ssl_context) as websocket: print('>>> S\'ha connectat') # Espera … -
How to limit response size in django lamba query
I know the typical way to limit queries within Django is to append [:10] to the end of the query, but I have a function that uses a functools.reduce(lambda and I'm unsure how to limit the query size. As it stands the query is taking way too long and fetching way too much data. What's the best way to limit this query and increase efficiency? Here's the function: def get_threads_for_student_mentor(cls, student_id=None, mentor_id=None): clauses = [] if student_id: clauses.append(models.Q(student_id=student_id)) if mentor_id: clauses.append(models.Q(mentor_id=mentor_id)) if len(clauses) == 0: raise ValueError("student_id and mentor_id cannot both be None") return cls.objects.filter(functools.reduce(lambda a, b: a & b, clauses)) I tried changing the return statement to return cls.objects.filter(functools.reduce(lambda a, b: a & b, clauses))[:5].all() and I also tried adding it to the append functions, as in clauses.append(models.Q(student_id=student_id)[:5]) but alas, nothing has works thus far. What am I doing wrong here? I'm sure it's just a silly mistake. -
reconnecting-websocket.min.js:1 WebSocket connection to 'wss://site.com/messages/user' failed:
I facing a problem I have a chat app in Django, and this app worked with me in the development environment put after I deployed it to production id didn't work and shows this messages in the console CustomEvent {isTrusted: false, detail: null, type: "error", target: div, currentTarget: div, …} reconnecting-websocket.min.js:1 WebSocket connection to 'wss://site.com/messages/user' failed: My javascript websocket <script src="https://cdnjs.cloudflare.com/ajax/libs/reconnecting-websocket/1.0.0/reconnecting-websocket.min.js" integrity=""anonymous"></script> var loc = window.location var wsStart = 'ws://' if (loc.protocol == 'https:'){ wsStart = 'wss://' } var endpoint = wsStart + loc.host + loc.pathname var socket = new ReconnectingWebSocket(endpoint) The Nginx configuration location /ws/ { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_pass http://127.0.0.1:8001; } -
weird url string missing when changing langcode from en-gb to en in django modeltranslation
I am new to django and this awesome library. Yet, I encounter the following issue: I firstly register the django project with LANGUAGES as en-gb: https://drive.google.com/file/d/15KGHEUFwmcE5m9cP4XpoY9j8lKFMqgaa/view?usp=sharing Then, the translation works fine when i switch to en-gb: https://drive.google.com/file/d/15KGHEUFwmcE5m9cP4XpoY9j8lKFMqgaa/view?usp=sharing However, when i switch to LANGUAGES as en, weird things happen. The url get mispelled while i have not change anything in urls.py of my apps: https://drive.google.com/file/d/1jSdzI-t-F60gwuSVLWxbiKtH8M8GyzvJ/view?usp=sharing https://drive.google.com/file/d/1vpIjZWdoal96MkCCKRoHGEz06xqccaEO/view?usp=sharing https://drive.google.com/file/d/1jSdzI-t-F60gwuSVLWxbiKtH8M8GyzvJ/view?usp=sharing My temporary soltuion is to keep using en-gb instead of en even though causing me inconvenience and confusing. Any idea and thought about this case? Many thx! -
Django redirect() method not removing bookmark in the URL
In my Django project, urls.py file urlpatterns = [ path("forgot-password", views.forgot_password), path("forgot-password/link-sent", views.forgot_password_link_sent), ] views.py file def forgot_password(request): # Some code redirect(forgot_password_link_sent) def forgot_password_link_sent(request): # Some code Now URL for the template associated with the view function forgot_password() looks like : http://localhost:8000/forgot-password and the URL for the template associated with the view function forgot_password_link_sent() looks like : http://localhost:8000/forgot-password/link-sent There is no problem in this. But if the URL for the template associated with the view function forgot_password() looks like : http://localhost:8000/forgot-password#error then the URL for the template associated with the view function forgot_password_link_sent() looks like : http://localhost:8000/forgot-password/link-sent#error instead of : http://localhost:8000/forgot-password/link-sent So why is that happening?? and what should I change in the code redirect(forgot_password_link_sent) in the forgot_password() view function of views.py file to avoid that from happening?? Or is there any alternative to avoid this from happening?? -
Django upload_to callable use in Form
I am trying to make a video upload form, but I wanted the video's file name to have a specific format, so I used a callable on the upload_to parameter: def createFileName(instance, filename): fname, ext = filename.split(".") return "videos/{0}_{1}_{2}.{3}".format(fname, instance.timeStamp, instance.id, ext) class Video(models.Model): # id é automático timeStamp = models.DateTimeField(verbose_name="timeStamp", auto_now_add=True, null=False) file = models.FileField(upload_to=createFileName, null=True) author = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE) I was trying to make a modelForm for this model but I didn't know what fields I would insert. The author I will fill, using the authenticated one so I don't need it. So would it be something like this? class VideoInputForm(ModelForm): class Meta: model = Video fields = ["filename", "file"] I searched not only in the StackOverflow for an answer, but in other sites but I haven't found anything. Thanks in advance. -
Как вывести в административной панели данные связанной модели
enter image description here Я выбрал нужную мне книгу.Как мне отразить в поле audio только те файлы которые относятся к выбранной книге?