Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Google oauth + django - cant authenticate from saved data
Okay, so i got the flow working, but it only works on the current session, if i try to load the data in, even with just a refresh the credentials dont hold up. So this works which is where oauth redirects to after user accepts prompts: def oauth_redir(request): u=Employee.objects.filter(dashboard_user=request.user) if not u: u=Employee.objects.create(dashboard_user=request.user) else: u=u[0] flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( CLIENT_SECRETS_FILE, scopes=SCOPES, state=request.GET.get("state")) flow.redirect_uri = REDIRECT_URL flow.fetch_token(authorization_response=request.build_absolute_uri().replace("http:","https:")) #saving credentials for future use credentials = flow.credentials if not Emp_google_creds.objects.filter(employee=u): Emp_google_creds.objects.create( token= credentials.token, refresh_token= credentials.refresh_token, token_uri = credentials.token_uri, client_id = credentials.client_id, client_secret= credentials.client_secret, scopes = " ".join(credentials.scopes), employee = u ) else: creds=Emp_google_creds.objects.get(employee=u) creds.token = credentials.token, creds.refresh_token = credentials.refresh_token, creds.token_uri = credentials.token_uri, creds.client_id = credentials.client_id, creds.client_secret = credentials.client_secret, creds.scopes = " ".join(credentials.scopes), creds.save() if not credentials or not credentials.valid: print(credentials, credentials.valid, credentials.expiry) # credentials.refresh(Request()) # return redirect("/calendar/cal_auth/") try: service = googleapiclient.discovery.build('calendar', 'v3', credentials=credentials) # Call the Calendar API now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time print('Getting the upcoming 10 events') events_result = service.events().list(calendarId='primary', timeMin=now, maxResults=10, singleEvents=True, orderBy='startTime').execute() events = events_result.get('items', []) if not events: print('No upcoming events found.') return # Prints the start and name of the next 10 events for event in events: start = event['start'].get('dateTime', event['start'].get('date')) print(start, event['summary']) except … -
Problem when deploying Django with apache when running the server
I'm currently working on deploying a Django app with apache (on Debian server). I configured apache with mod_wsgi. I added my server IP in allowed_hosts in settings.py. Migrations done correctly. When I run the server : python manage.py runserver 0.0.0.0:8000 I get an infinite loop with the following message : "GET / HTTP/1.0" 302 0 I can't find a solution, any idea plz ? enter image description here -
what Django request.META is
I read a lot of articles about request.META but I didn't understand anything about it and what it does. Can anyone explain it? -
Problem when sending dictionary with ajax ( POST ) to python ( django views ) -> always empty
So i call this in the head of the html : <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> then with a button i call a function : <div> <button class= "button" type="ajax-call" onclick="getValue();">Envoyer</button> </div> And the function is : <script type="text/javascript"> function getValue(){ .... $.ajax({ url: "{% url 'sondage' %}", type : 'POST', dataType: "json", data: {heure_reponse: heure, jour_reponse: jour,habitude_reponse: habit, faim_reponse : faim, soif_reponse: soif, estomac_reponse:estomac, miam_reponse: miam, quantite_reponse: quantite, but_reponse: but, adresse_reponse: adresse, identifiant_reponse:identifiant } }) } </script> The problem is : When i write in the views.py of my django site ( python ) with from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt from django.shortcuts import render from csv import writer from csv import QUOTE_MINIMAL @csrf_exempt @login_required def sondage(request): #Récupération des données par ajax reponses = request.POST.items() reponses = list(reponses) if len(reponses) == 0: print(" AJAX PROBLEME ") reponses.append(request.user.get_filename().split('/')[1].split('.')[0]) name = request.user.get_filename().split('/')[1].split('.')[0] #Ecriture dans le csv write_csv(reponses,name) #Appel de la page que l'on est en train de traiter return render(request, 'sondage.html',{'data':reponses}) def write_csv(data,name): #Ouverture en mode APPEND with open('uploads/questionnaire/sondage.csv', 'a', newline='', encoding="utf-8") as csvfile: csv_writer = writer(csvfile, delimiter=',') csv_writer.writerow(data) csvfile.close() I always have "AJAX PROBLEME" ! Why ? And how do we fix this ? -
How to create a registration form in Django that will recognise when password and confirm password don't match
I am trying to build a registration form for a user on a webpage using python and the Django framework. The form works fine and registers a user if all the fields are valid and Django has built in error messages if fields are left blank etc which work fine. However, I am trying to add my own error for if the 'password' and 'confirm password' fields don't match. If they don't match I get an error stating: 'The view main.views.register didn't return an HttpResponse object. It returned None instead.' My question is how would I successfully return the registration page with the error displayed to the user? Here is my views.py code: def register(request): if request.method == "GET": register_form = RegisterForm() return render(request, "main/register.html", { 'form': register_form }) else: register_form = RegisterForm(request.POST) if register_form.is_valid(): register_form.save() return render(request, "main/login.html") Here is my form.py code: class RegisterForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) confirm_password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email', 'password'] def clean(self): cleaned_data = super(RegisterForm, self).clean() password = cleaned_data.get("password") confirm_password = cleaned_data.get("confirm_password") if password != confirm_password: self.add_error("confirm_password", "Password does not match") -
Django + Twilio 500 Error (Session issue?)
I forked this Tutorial https://github.com/TwilioDevEd/automated-survey-django and am trying to get it to run locally. The current behavior is that, I send a text to the Twilio number and then it correctly texts me the first question of the survey. However, then when I text back, I don't get a response (should be the 2nd question of the survey) and I see a 500 error in Django. I can see that the second text message is being received by Django and, from the following function, it prints HELLO. However, it doesn't make it to YEP, so it appears to be erroring on answering_question = request.session.get('answering_question_id'), which seems like it is a problem with the session. I can see that there is a new session in the Django_session table created from my first text. I'm stuck on what is going wrong. request.session['answering_question_id'] is being set elsewhere in the code, but, my understanding, is if wasn't set, then answering_question would just be false, not an error. I'm stuck - any thoughts? def redirects_twilio_request_to_proper_endpoint(request): print("HELLO") answering_question = request.session.get('answering_question_id') print("YEP") if not answering_question: print('1') first_survey = Survey.objects.first() redirect_url = reverse('survey', kwargs={'survey_id': first_survey.id}) else: print('2') question = Question.objects.get(id=answering_question) redirect_url = reverse('save_response', kwargs={'survey_id': question.survey.id, 'question_id': question.id}) return … -
Signature Error with xmlsec on Windows with django_saml2_auth
I am following this tutorial to set up a SSO Login on Django. I have installed the xmlsec library from this link and everything seems correct but when testing the endpoint with Azure it throws this error: check_sig: ['C:\\Users\\user\\code\\project-backend\\env\\Scripts\\xmlsec.exe', '--verify', '--enabled-reference-uris', 'empty,same-doc', '--enabled-key-data', 'raw-x509-cert', '--pubkey-cert-pem', 'C:\\Users\\user\\AppData\\Local\\Temp\\tmpg9oixidy.pem', '--id-attr:ID', 'urn:oasis:names:tc:SAML:2.0:assertion:Assertion', '--node-id', 'xxxxxxx', '--output', 'C:\\Users\\user\\AppData\\Local\\Temp\\tmp4q_a_mb0.xml', 'C:\\Users\\user\\AppData\\Local\\Temp\\tmpybj2a3vf.xml'] correctly_signed_response: Failed to verify signature Signature Error: Failed to verify signature XML parse error: Failed to verify signature Internal Server Error: /sso/acs/ Internal Server Error: /sso/acs/ I've tried it on a Unix system and It works fine. -
Django, more type of user with other permission - I need advice
I need advice. I want make 3 types of user: member (only nickname/password/email) company (nickname/password/email/company/regon + permision for edit model) admin My question is aobut how make model for this users: make big model for member and company together but field which are only for comapny make empty for member. Next to by admin panel i can make group and add "comapny" ppl make 2 type of user (here i will need advice like what i should use on it) and seperate website register for member and company and login should be the same form Thank you for answer -
Can I use more than one name attribute in HTML tag?
I am doing a django project. But I wanted to have radio buttons grouped as well as name of the buttons to work with django. Is it okay to use two name attributes in one HTML tag? Will I be facing any errors if I do so? Below is my code I am stuck in. <input type="radio" name="group1" name="removePunc"> Remove Punctuations <br> -
List of child ID in django template
Here is my models.py: #child class Country(models.Model): name = models.CharField(max_length=255) wine_rg = models.ManyToManyField(WineRegion, blank=True) #parent class WorldRegion(models.Model): name = models.CharField(max_length=255) country = models.ManyToManyField(Country, blank=True) def __str__(self): return self.name views.py: world_region_filters = WorldRegion.objects.all() templates/test.html: {% for world_region in world_region_filters %} {{ world_region.name }} - {{ return list of country ID }} {% endfor %} How to return all country ID (child) on django template? I know I can do this: {% for country in world_region.country.all %} {{ country.id }} {% endfor %} But is there any way to make it shorter? I've tried this: {{ world_region.country.all.id }} But it doesn't work. Any suggestions? -
djano - can not display an uploaded image from mySQL database
I configured everything as it should and yet I can't display the images from my database. settings.py : STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) models.py class Etudiants(models.Model): numeroetudiant = models.BigIntegerField(db_column='numeroEtudiant', blank=True, null=True) # Field name made lowercase. nom = models.CharField(max_length=255, blank=True, null=True) prenom = models.CharField(max_length=255, blank=True, null=True) groupe = models.BigIntegerField(blank=True, null=True) photo = models.ImageField(blank=False, null=False, upload_to='images/') email = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'etudiants' def __str__(self): return self.nom + " " + self.prenom views.py : def ajoutetudiant(request): submitted = False if request.method == "POST": form = EtudiantsForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect("../ajoutetudiant/") else: form = EtudiantsForm() if 'submitted' in request.GET: submitted = True return render(request, 'ajoutetudiant.html', {'form': form}) urls.py (of my project) : from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('',include('notes.urls')), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) .html : <img src="{{etudiant.photo.url}}"/> The pictures are saved in my database as you can see here. But cannot display it. My field in mySQL database is "blob". If it shouldn't be blob what should i put ? -
Django modal form not showing with HTMX
I have tried to replicate the example of this Github repository but the modal form won't display using HTMX. I'm really new to HTMX and I cannot figure out why. Here are my files: I use a Class Based View instead of a FBV in views.py: class UserAddReportView(LoginRequiredMixin, RequestFormMixin, CreateView): """ View to create a report. """ model = Report template_name = 'tool/add-report.html' form_class = ReportForm success_url = reverse_lazy('tool:home') def form_valid(self, form): self.object = form.save() self.request.session['report_id'] = self.object.pk if not self.object.slug: self.object.slug = slugify(str(self.object.company) + "-" + get_random_string(length=32)) date_f = self.request.session['date_f'] self.object.title = self.object.company.name + " " + date_f return super().form_valid(form) In models.py: class Report(models.Model): """ Class designed to create a report and assign it to a company. """ title = models.CharField(max_length=200, null=True, blank=True) company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True) brand = models.ForeignKey(Brand, on_delete=models.CASCADE, blank=True, null=True) slug = models.SlugField(max_length=255, blank=True) def __str__(self): return str(self.slug) In forms.py: class ReportForm(forms.ModelForm): """ Form to create a report. """ date = forms.DateField(widget=forms.widgets.DateInput(attrs={'type': 'date'})) class Meta: model = Report fields = ['company', ] def __init__(self, request, *args, **kwargs): super().__init__(*args, **kwargs) self.request = request user = self.request.user self.initial['company'] = user.company def clean(self): super().clean() filtered_date = self.cleaned_data.get('date') month = filtered_date.month month = calendar.month_name[month] year = filtered_date.year date_f … -
How to correctly send data to the server from the table?
I apologize for possible grammatical errors, this text was translated through Google translate. I'm not very good at programming yet, I'm learning right away in practice. Now I'm making a Django web application for warehouse management. I have a select with a list of products that is loaded via api, and when the select is selected, a row with the product is added to the table success: function (res) { let invoiceRow = document.querySelector(".invoice-add-table table tbody tr.add-elements").insertAdjacentHTML('beforebegin', '<tr class="invoice-row">' + '<td align="right" class="fixed">'+ res.articul +'</td>' + '<td class="name" align="left"><span title="'+ res.name +'" style="text-decoration: underline; cursor: pointer;">'+ res.name +'</span></td>' + '<td align="right" class="fixed"><input name="quantity" value="1" class="ta-right fixed" type="text"></td>' + '<td align="right" class="fixed"><input name="last_buy_price" value="'+ res.last_buy_price +'" class="ta-right fixed" type="text"></td>' + '<td align="right" class="fixed"><input name="summ" value="" class="ta-right fixed" type="text"></td>' + '<td align="right" class="fixed"><input name="sell_price" value="'+ res.sell_price +'" class="ta-right fixed" type="text"></td>' + '<td align="right"><div style="display: flex;" class="edit-tool-table"><span class="iconify" data-icon="bx:trash" style="color: white;" data-width="20"></span></div></td>'+ '</tr>'); $(".add-items-select")[0].selectize.clear() Question: How do I identify each row to send it to the server, as well as the data in the inputs that are responsible for the quantity and price? There can be as many lines as you want, I don't understand how to get them on the server And … -
Multiple filters in django
I want to filter movies, that fit only to selected genres, for example: def get_queryset(self): queryset = Movie.objects.all() if 'genres' in self.request.GET: queryset = queryset.filter(genre__in=self.request.GET.getlist('genres')) return queryset This filter shows movies that fit into at least one to filter, but I want to show movies that are fit all of the selected genress like 'comedy, horror, fantasy' and all of the selected genres must be in the movie genres How cat I do this? -
How to roll up multiple rows filtered by a column value into a single row in Django?
I have a model for Notification: class VerbChoices(models.TextChoices): COMMENTED = 'commented' LIKE = 'like' id = models.CharField(primary_key=True, default=generate_id, max_length=255) actor = models.ForeignKey(Users, on_delete=models.DO_NOTHING, related_name='notify_actions', null=True) recipient = models.ForeignKey(Users, on_delete=models.DO_NOTHING, related_name='notifications') verb = models.CharField(max_length=255, choices=VerbChoices.choices) read = models.BooleanField(default=False) target_content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) target_object_id = models.CharField(max_length=255) target = GenericForeignKey('target_content_type', 'target_object_id') created_at = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) I am trying to write a query which will return the count of rows with verb = LIKE, grouped by target_object_id. All the other rows should be without group by. Any help in this regard would be much appreciated. -
How to overrider Logger class with method to select log level and output line of the log
I need to record logs in many places of my Django application and I want to have it in a standardized way so that when people contribute they don't have to worry to much about it. So instead of calling: logger.info(<standardized message here>) I would like to write a function or probably a class that inherits Logger and selects the correct .info, .warning, .error and so on and outputs the message the way we want. So in the code I would only call log(request, 200, "info", "Success message") And the function I wrote looks like this: logger = logging.getLogger(__name__) def log(request=None, status_code=None, level=None, message=None): """ Create a log stream in a standardized format <request_path> <request_method> <status_code>: user <user_id> <message> """ method = request.method path = request.path user_id = None if not request.user.is_anonymous: user_id = request.user.id log = f"{path} {method} {status_code}: user {user_id} {message}" if level == 'info': logger_type = logger.info elif level == 'warning': logger_type = logger.warning elif level == 'error': logger_type = logger.error elif level == 'debug': logger_type = logger.debug return logger_type(log) The problem is that our log formatter also records the line in the code where the log happened, and because the log is called in the log … -
Axios post request to create a Django REST model with ForeignKey field
I am working on a NextJS + Django REST Framework project where I have two models; Document, MySource models.py class Document(models.Model): id = HashidAutoField(primary_key=True) title = models.CharField(max_length=100, default="Untitled") template = models.CharField(max_length=100, default="") updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class MySource(models.Model): id = models.AutoField(primary_key=True) document = models.ForeignKey( Document, related_name="mysource", on_delete=models.CASCADE, null=True, blank=True, ) url = models.CharField(max_length=500, default="") title = models.CharField(max_length=500, default="", blank=True) publisher = models.CharField(max_length=500, default="", blank=True) desc = models.CharField(max_length=500, default="", blank=True) summary = models.CharField(max_length=500, default="", blank=True) I want to make an axios.post request that creates a MySource object that is linked to a document of a provided documented. Something like this: { "url": "aaaa", "title": "bbbb", "publisher": "bbbb", "desc": "bbbb", "summary": "bbbb", "document": "J9DY2pE" } Currently, making a POST request with the fields above will create the object but with document set to null. I can however select the document model manually from the admin panel below. [![admin panel][1]][1] Only after then, I get the desired axios.GET(documents) result like the following. "id": "J9DY2pE", "mysource": [ { "id": 16, "url": "google.com", etc. . . }, ], "title": "renamed title", "template": "commonapp", "updated": "2022-05-19T02:16:00+0000", "created": "2022-04-21T06:59:05+0000" Here's the rest of my code serializers.py from django.forms.models import model_to_dict class … -
How to order a related table using list of ids in Django
here is example of what I am trying to perform; class GroupA(models.Model): name=models.CharField(max_length=250) class GroupB(models.Model): category = models.CharField(max_length=250) group_a = models.ForeignKey(GroupA) I have list of ids; [1, 2, 3]. How do I perform an order of GroupA through GroupB using the list of ids. Currently, an example of data I am returning is; [ { "id": 3, "category": "Category 1", "group_a": [ { "id": 2, "name": "John" }, { "id": 1, "name": "Doe" }, { "id": 3, "name": "Jane" } ] } ] What I am trying to archive is order the data of group_a using list of ids; [1, 2, 3]. So it would return something like this; [ { "id": 3, "category": "Category 1", "group_a": [ { "id": 1, "name": "Doe" }, { "id": 2, "name": "John" }, { "id": 3, "name": "Jane" } ] } ] -
How to redirect user to vue app from django without forcing him to login second time?
Let's suppose I have a django app based on templates, but i want to make a button that redirects user to admin app made in Vue.js, what is the best way to redirect user to that vue service and not force him to login second time on that vue page? -
Is there a way to print only the data with the json key in python?
im trying to print a json in python "rules":[ { "table":"Forest", "format":"List", "header":{"en":"Forest","fr":"Forêt"}, "fields":[ { "name":"Name", "displayName":{"en":"Forest","fr":"Forêt"} }, { "name":"ForestMode", "displayName":{"en":"Forest Mode","fr":"Mode forêt"}, "ok":"re.search('Windows(2019|2016)Forest',x) != None", "warn":"re.search('Windows(2012R2|2012)Forest',x) != None", "nok":"re.search('Windows(2008R2|2008|2003|2003Interim|2000)Forest',x) != None", "comment":{"en":"Increase the functional level of the forest","fr":"Augmenter le niveau fonctionnel de la forêt"} }, { "name":"RootDomain", "displayName":{"en":"Root Domain","fr":"Domaine racine"} }, { "name":"Domains", "displayName":{"en":"Domains","fr":"Domaines"} }, { "name":"Sites", "displayName":{"en":"Sites","fr":"Sites"} }, { but i've run into an issue some of the json data doent have the key while some do i have written this thus far with open('./rules-adds.json', 'r') as ad_file: ad_data = json.load(ad_file) # print(ad_data) data = ad_data["rules"] # print(data) # print(json.dumps(ad_data, indent=4)) for x in data: print(x['table'], x['fields']) for y in x['fields']: print(y['name']) But i get an error since the first element of the json file doesn't have the "ok" key print(y['ok']) KeyError: 'ok' -
How to convert string list to list in python [duplicate]
I have a List emp_id = "['1406','41232']" I want to convert the same into List ['1406','41232'] I tried emp_id = emp_id.strip('][').split(", ") But it resulted output was ["'1406'","'41232'"]" -
Is it possible to send an MQTT message with mqttasgi inside a Celery Worker that use Redis Backend
I am using mqttasgi library in Django to receive a large number of messages, and process them with a REDIS queue and I would like to publish this information back to another TOPIC. Is this possible? If yes, how can I do it ? For the moment I am only overriding the publish function into my consumer as below. from mqttasgi.consumers import MqttConsumer from mqtt_handler.tasks import processmqttmessage import json class MyMqttConsumer(MqttConsumer): async def connect(self): await self.subscribe('application/5/device/+/event/up', 2) async def receive(self, mqtt_message): print('Received a message at topic:', mqtt_message['topic']) print('With payload', mqtt_message['payload']) print('And QOS:', mqtt_message['qos']) print(type(mqtt_message['payload'])) dictresult = json.loads(mqtt_message['payload']) print(type(dictresult)) print(dictresult) jsonresult = json.dumps(dictresult) print(type(jsonresult)) print(jsonresult) processmqttmessage.delay(jsonresult) print("test") pass async def publish(self, topic, payload, qos=1, retain=False): await self.send({ 'type': 'mqtt.pub', 'mqtt': { 'topic': topic, 'payload': payload, 'qos': qos, 'retain': retain, } }) async def disconnect(self): await self.unsubscribe('application/5/device/+/event/up') I want to be able able to now publish but from the inside of my task processmqttmessage. Thank you. Pd: @Santiago Ivulich maybe you can help me with that. -
'NoneType' object has no attribute 'app' in saleor
I am using saleor backend for my current project. There I have to execute saleor graphql queries and mutations inside the code. So instead of hitting graphql api using url I am using schema.execute() with query and variables. With this approch the custom queries and mutations that I created are working perfectly fine. But when I am executing saleor's mutation or queries like- import graphene schema = graphene.Schema(ProductQueries) query = """ { products(first: 2, channel: "default-channel") { edges { node { id name defaultVariant{ id } } } } } """ data = schema.execute(query, context_value={"app":"app"}) print(data.data) output - {'products': None} And when I am checking for errors using print(data.errors), It is giving me this error- **[GraphQLLocatedError("'NoneType' object has no attribute 'app'")]** i checked out in types and schemas of these mutations and queries and nowhere this 'app' attribute is mentioned. Just to test I tried to pass this 'app' attribute in context_value with empty string as well but still It didn't work and this time the error was- **[GraphQLLocatedError("'dict' object has no attribute 'app'")]** -
error when Redirecting user to someone profile in other model
I want to redirected user to the profile page in the question model, I want when user click on url in the username of the question model, I want that url to redirected user to the author of that question to his/her public_profile page like facebook you can visit someone profile by clicking on his name when he/she post something, I have try using this method but it throws me an error: Reverse for 'Public_Profile' with arguments '('',)' not found. 1 pattern(s) tried: ['userProfile/(?P[-a-zA-Z0-9_]+)/\Z'] this is what i have try: my urls: urlpatterns = [ path('', views.rules, name='Rules'), path('create', views.login, name='login'), path('index/', views.index, name='index'), path('view/<slug:slug>/', views.viewQuestion, name='view-Question'), path('question/<int:pk>/answer/', views.My_Answer.as_view(), name='answer'), path('question/', views.My_Question.as_view(), name='question'), path('register/', views.register, name='register'), path('feedback/', views.PostFeedBack.as_view(), name='FeedBack'), path('notification/', views.NotificationListView.as_view(), name='notification'), path('profile/<int:pk>/', views.profile, name='Profile'), path('edit/<slug:slug>/', views.EditProfile.as_view(), name='edit'), path('userProfile/<slug:slug>/', views.public_profile, name='Public_Profile'), ] my index/home template: <div class="container"> <div class="row justify-content-center"> {% for question in list_of_question reversed %} <div class="col-md-4"> <div class="card my-3"> <div class="card-header"> <p class="card-title"><a href="{% url 'Public_Profile' profile.slug %}"> {{question.user.username.upper}} </a></p> </div> <div class="card-body"> <a href="{% url 'view-Question' question.slug %}" style="text-decoration: none;"> <p class="card-title">{{question.title}}</p> </a> <h5>{{question.category}}</h5> </div> </div> </div> {%endfor%} </div> </div> my views: def profile(request, pk): profiles = Profile.objects.filter(user=request.user) questions = Question.objects.filter(user=request.user) context = { 'profiles':profiles, 'questions':questions … -
Django on Google App Engine add version URL's to ALLOWED_HOSTS
I am hosting on GAE and want to be able to access different versions without promoting them. Currently, I get a 400 error: Invalid HTTP_HOST header: '1234568-dot-myapp.ey.r.appspot.com'. You may need to add '1234568-dot-myapp.ey.r.appspot.com' to ALLOWED_HOSTS. How can I add the URL to ALLOWED_HOSTS, so that I can access any version of my app? Currently, my ALLOWED_HOSTS looks like this: APPENGINE_URL = env("APPENGINE_URL", default=None) if APPENGINE_URL: if not urlparse(APPENGINE_URL).scheme: APPENGINE_URL = f"https://{APPENGINE_URL}" ALLOWED_HOSTS = [urlparse(APPENGINE_URL).netloc, 'my-personal-domain.com'] CSRF_TRUSTED_ORIGINS = [APPENGINE_URL, 'https://my-personal-domain.com'] SECURE_SSL_REDIRECT = True else: ALLOWED_HOSTS = ["*"] From my understanding, wildcards only work for sub-domains. How can I add something like this to the allowed hosts? [version-number]-dot-myapp.ey.r.appspot.com Thanks!