Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I have tried to submit the form in django but only redirection function is working data is not showing in django admin
My views.py are def login_register(request): if request.method=='POST': first_name=request.POST['first_name'] last_name=request.POST['last_name'] email=request.POST['email'] password=request.POST['password'] # check for errornous inputs #create the user myuser=User.objects.create( first_name=first_name, last_name=last_name ) myuser.save() return redirect('shophome') return render(request, 'shop/login.html') my urls.py are urlpatterns = [ path('', views.index, name='shophome'), path('product-list/', views.product_list, name='product_list'), path('product-detail/', views.product_detail, name='product_detail'), path('cart/', views.cart, name='cart'), path('checkout/', views.checkout, name='checkout'), path('my-account/', views.my_account, name='My_account'), path('contactus/', views.contactus, name='contactus'), path('wishlist/', views.wishlist, name='wishlist'), path('login/', views.login_register, name='login_register'), ] I have tried to submit the form with post method but its not working. when i submit the form it should redirect to home page and data should save in django admin but only redirection is working. -
Django Database Routing using USER from request
I am trying to implement a PER USER database routing in Django and things are not going that smoothly. This is what I have right now and IT WORKS but I was wondering if there is anything better for what I want : class DatabaseMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if (str(request.company) == 'company1'): request.database = 'COMPANY_X' else: request.database = 'default' response = self.get_response(request) return response #THIS HAS SECURITY RISKS BUT I DONT THINK THERE IS SOMETHING BETTER OUT THERE FOR NOW from threadlocals.threadlocals import get_current_request class UserDatabaseRouter: def db_for_read(self, model,user_id=None, **hints): request = get_current_request() if(not (request is None)): return request.database else: return None def db_for_write(self, model,user_id=None, **hints): request = get_current_request() if(not (request is None)): return request.database else: return None -
Django with Postgres - Sub query slow
Django Postgres - Sub query slow Hello, I want to select players with their current location (not in the futur and closest from now) ordered by Player.registered_at. I also want to filter the Player regarding their current location with DRF. Here are my models : class Player(models.Model): class Meta: indexes = [ models.Index( fields=["closed", "deleted"], condition=Q(closed=False, deleted=False), name="opened_player_index", ) ] registered_at = models.DateTimeField(_("registerd at"), db_index=True) name = models.CharField(max_length=100) closed = models.BooleanField(_("closed"), default=False) deleted = models.BooleanField(_("deleted"), default=False) class Location(models.Model): name = models.CharField(max_length=100) class PlayerLocation(models.Model): class Meta: indexes = [ models.Index( fields=["player", "active_since", "location"], name="player-active-since-location", ) ] active_since = models.DateTimeField(_("active since"), db_index=True) player = models.ForeignKey( Player, on_delete=models.PROTECT, related_name="locations" ) location = models.ForeignKey( Location, on_delete=models.PROTECT, related_name="+" ) Here is my query : class PlayerQuerySet(models.QuerySet): def with_location(self): # Get current healthcare facility as SubQuery current_player_location = PlayerLocation.objects.filter( player_id=OuterRef("pk"), active_since__lte=Now() ).order_by("-active_since") return self.annotate( # add current location of player queryset lookup_location=Subquery( current_player_location.values("location")[:1] ), location_name=Subquery( current_player_location.values("location__name")[:1] ), ) Here is the output of the explain analyze postgres query (for the count) : EXPLAIN ANALYZE SELECT COUNT(*) AS "__count" FROM "player" WHERE ( NOT "player"."closed" AND NOT "player"."deleted" AND ( SELECT U0."location_id" FROM "player_location" U0 WHERE ( U0."active_since" <= (STATEMENT_TIMESTAMP()) AND U0."player_id" = ("player"."id") ) ORDER BY … -
postgresql unittest db and django
HI I'm making test code but I have a problems... this is my django settings.py DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "name", "USER": "user", "PASSWORD": "passwd", "HOST": IP, "PORT": port, "ATOMIC_REQUEST": True, "TEST": { "NAME": "test_db", }, } } and my test code class TestPreprocessAPI(APITestCase): preprocess_data = factories.PreprocessDataFactory() def test_get_preprocess_data(self): url = reverse("url") response = self.client.get(url) data = response.json() self.assertEqual(response.status_code, 200, "status code is not 200") self.assertIsInstance(data, list) the temperate test data store in production db "settings.py's default db" not "TEST settings test db" why this happen? and how can I use test db I checked test db made I checked my postgresql auth -
Getting custom User details from access token in API(DJANGO)
I am a novice in Django and have started learning about jwt authentication implementation in django. I have successfully obtained access token and refresh token on successful login (username and password) by a user. Now, if I want to get the same user details like email, username and his mobile number when he clicks on some button from frontend, how to do it? Does the returned token from backend gets stored in frontend so that I can send it in the fetch function OR is there any way to get access to that token in another APIView in backend? I have tried every code provided in the answers for the similar question but not getting the result. Please help me in understanding this and as well as the code to implement it. -
Redirect a indexed broken url to new one in python django- nginx server
I've a python-django projet & it's hosted in AWS- nginx server. recently we chnaged the filename but whenever someone searching the old file (that is indexed in google) shows. it throws 404 error. how will I redirect old url(indexed one ) to new one. ie: "www.example.com/logistics-services-odisha" to "www.example.com/logistics-services-in-odisha" please help me. this is urgent. we are trying it in robots.txt but no clue more -
Way to Return a Return [closed]
Is there any way to achieve return a return? This way I can achieve return from nested functions. I achieved by returning in if block and returned None as default. def inner_function(user): if isinstance(user, User) and not is_admin(user): return HttpResponse("Access Forbidden!", status=403) def outer_function(model_instance, param1, param2): response = inner_function(model_instance) if response is not None: return response """ ...codes """ outer_function(model_instance) -
AttributeError: module 'django.db.models' has no attribute 'PriceRanges' [closed]
Getting the error when trying to execute django admin command as per code below. This runs no problem if I render it to html but getting the error when trying to execute through command line. Ignore the ''' around the code, couldnt see another way to allow this page to submit the question. Folders: project General management # (inc __init__.py) commands # (inc __init__.py) data_import.py # command file __init__.py migrations templates models.py view.py etc... data_import.py from django.core.management.base import BaseCommand, CommandError from django.contrib import admin from django.db import models from General.models import PriceRanges class Command(BaseCommand): help = 'Run the data import process' def handle(self, *args, **options): all_ranges = models.PriceRanges.objects.all() self.stdout.write(all_ranges) models.py from django.db import models class PriceRanges(models.Model): price_range_id = models.CharField(primary_key=True, max_length=36) price_range_from = models.IntegerField(blank=True, null=True) price_range_to = models.IntegerField(blank=True, null=True) price_range_increment = models.IntegerField(blank=True, null=True) def __str__(self): return f"{self.price_range_from}, {self.price_range_to}, {self.price_range_increment}" class Meta: managed = False db_table = 'price_ranges' db_table_comment = 'Define the search price ranges and increments' execute command in terminal - python manage.py data_import error details: all_ranges = models.PriceRanges.objects.all() ^^^^^^^^^^^^^^^^^^ AttributeError: module 'django.db.models' has no attribute 'PriceRanges' Any help would be very appreciated. -
Django Channels SSE messages are hit or miss unpredictably
I am building an app with general django views and DRF views for a Flutter app for the same features. I also have django-channels for sending notifications to clients through Server Sent Events. I have inherited from AsyncHttpConsumer for the SSE consumer and locally everything works perfectly fine. The entire project is a docker compose setup quickstarted with cookiecutter-django, with redis, celery, django, traefik, and some other containers. In my django and DRF views, I call a function I created in the User model to send notifications where I send messages to the channel layer through the group name. Locally all messages are received as it should, but when I perform the same actions in a staging environment, the messages are a hit or miss. Without any apparent pattern, sometimes messages arrive as it should, other times only one out of 4-5 attempts work, and even other times, none do. I use the JavaScript EventSource to handle incoming messages. From the django logs, I can see 4 workers and some debug statements show that one (varying each time) worker receives the event, while the rest prints empty content. (The consumer checks if the message is actually for the user in … -
how to split Django urls.py into multiple files
I have a function based view in my app, and I am trying to split my urls.py as follows my_app / |- urls |- __init__.py |- dogs.py |- cats.py |- views |- __init__.py |- dogs |- index.py ... # my_app/urls/__init__.py from .dogs import urlpatterns as dog_urls from .cats import urlpatterns as cat_urls app_name = "pets" urlpatterns = dog_urls + cat_urls # my_app/urls/dogs.py from .. import views urlpatterns = [ path("dogs/", views.dogs.index, name="dogs") ... ] With this set up I am getting this error django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'pets.urls' (namespace)>' does not appear to have any patterns in it. If you see the 'urlpatterns' variable with valid patterns in the file then the issue is probably caused by a circular import. I do not see where in my code I am creating a circular dependency, nor do I understand what I am doing wrong with urlpatterns. -
PeriodicTask model not creating in some conditions #676
I'm using Django 4.2 with django-celery-beat 2.5.0. I had no trouble creating PeriodicTasks and they were running properly. But 2 days ago, without any related changes, just some of my tasks are not being created. These tasks has a name with pattern of task_*. Note that my other tasks(other patterns) are being created using PeriodicTask model normally. I get no error when creating my tasks, I also log the periodic task ID in EFK but In the database there is no such ID. This is how I create my tasks: schedule, _ = IntervalSchedule.objects.get_or_create( every=repeat_every, period=IntervalSchedule.SECONDS, ) periodic_task = PeriodicTask.objects.create( interval=schedule, name=self.data.get("task_name"), task="my_app.tasks.call_services_periodic_task", args=json.dumps([ self.data.get("v1"), self.data.get("v2"), self.data.get("v3"), self.data.get("v4"), self.data.get("v5"), ]), start_time=timezone.now() + datetime.timedelta(seconds=self.data.get("start_in")), ) print(periodic_task.id) And it prints the periodic task ID. But it is not in the database. How can I fix the issue? Any help would be appreciated, Thank you very much -
Django Logger - writing logs in different files
These are the parameters I have inside my LOGGING in a Django REST Framework project. I have set logs everytime I shoot an email, and everytime I catch an error, I would like it to log into my error file and debug stuff into my debug.log file. However, I get error logs in both files, while I only get debug in my email debug.log file. "handlers": { "invitation_email_info": { "level": "DEBUG", "class": "logging.FileHandler", "filename": "projectname/logs/invitation/.debug.log", "formatter": "verbose" }, "invitation_email_error": { "level": "ERROR", "class": "logging.FileHandler", "filename": "projectname/logs/invitation/.error.log", "formatter": "verbose" }, }, "loggers": { "Invitation": { "handlers": ["invitation_email_info", "invitation_email_error"], "level": "DEBUG", "propagate": False, }, I tried playing around and was thinking if I should create more loggers, one for Invitation_Debug and one for Invitation_email. Please let me know. Thanks. -
getting error when integrating ccavenue in my django project
# ccav_app/ccav_utils.py from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.primitives import padding as sym_padding from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend import base64 import os def pad(data): padder = padding.PKCS7(128).padder() padded_data = padder.update(data) + padder.finalize() return padded_data def unpad(data): unpadder = padding.PKCS7(128).unpadder() unpadded_data = unpadder.update(data) + unpadder.finalize() return unpadded_data def derive_key(secret_key): salt = os.urandom(16) # Generate a random salt (16 bytes) kdf = PBKDF2HMAC( algorithm=hashes.SHA256(), iterations=100000, salt=salt, length=32, # Use 32 bytes for a 256-bit key backend=default_backend() ) key = base64.urlsafe_b64encode(kdf.derive(secret_key.encode())) return key def encrypt(plain_text, secret_key): key = derive_key(secret_key) iv = os.urandom(16) cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend()) encryptor = cipher.encryptor() encrypted_text = encryptor.update(plain_text.encode()) + encryptor.finalize() return base64.b64encode(iv + encrypted_text).decode() def decrypt(cipher_text, secret_key): key = derive_key(secret_key) data = base64.b64decode(cipher_text.encode()) iv = data[:16] cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend()) decryptor = cipher.decryptor() decrypted_text = decryptor.update(data[16:]) + decryptor.finalize() return unpad(decrypted_text).decode() this is my ccavutil.py file where i am gettig data and secret key through encrypt and decrypt but getting error ValueError at /cc/ Invalid key size (352) for AES. Request Method:POSTRequest URL:http://127.0.0.1:8000/cc/Django Version:4.2.1Exception Type:ValueErrorException Value:Invalid key size (352) for AES. I want to integrate the ccavenue payment gateway in my website … -
Dockerized Django application not accessible on specified port
I have a Django application running inside a Docker container on my server. I am trying to access it via a specific port, but it's not working as expected. Here are the relevant details: Dockerfile (CMD section): CMD ["python", "manage.py", "runserver", "0.0.0.0:9000"] Jenkins Pipeline (part of the Jenkinsfile): stage('Build and Deploy') { steps { script { // Build the Docker image sh 'docker build -t my-django-app -f Dockerfile .' // Stop and remove the existing container (if any) sh 'docker stop my-django-container || true' sh 'docker rm my-django-container || true' // Run the Docker container sh 'docker run -d --name my-django-container -p 9000:9000 my-django-app' } } } Additionally, I've allowed port 9000 through the firewall using the following command: sudo ufw allow 9000/tcp My Jenkins server is publicly available at ip:8080, but when I try to access my Django application at ip:9000, it doesn't work. I'm relatively new to Docker, and any assistance in troubleshooting this issue would be greatly appreciated. -
How to test Django with multiple broswers together with Selenium to reduce the code?
I installed pytest-django and selenium in Django as shown below. pip install pytest-django && pip install selenium Then, I created pytest.ini, test.py and __init__.py(Empty file) in tests folder as shown below: django-project |-core | └-settings.py |-my_app1 |-my_app2 |-pytest.ini └-tests |-__init__.py └-test.py Then, I set the code below to pytest.ini: # "pytest.ini" [pytest] DJANGO_SETTINGS_MODULE = core.settings testpaths = tests Finally, I could test Django (Admin) with the multiple browsers Google Chrome, Microsoft Edge and Firefox separately but not together with Selenium as shown below so the code is a lot: # "tests/test.py" import pytest from selenium import webdriver from django.test import LiveServerTestCase """ Google Chrome Test Begin """ @pytest.fixture(scope="class") def chrome_driver_init(request): chrome_driver = webdriver.Chrome() request.cls.driver = chrome_driver yield chrome_driver.close() @pytest.mark.usefixtures("chrome_driver_init") class Test_URL_Chrome(LiveServerTestCase): def test_open_url(self): self.driver.get(("%s%s" % (self.live_server_url, "/admin/"))) assert "Log in | Django site admin" in self.driver.title """ Google Chrome Test End """ """ Microsoft Edge Test Begin """ @pytest.fixture(scope="class") def edge_driver_init(request): edge_driver = webdriver.Edge() request.cls.driver = edge_driver yield edge_driver.close() @pytest.mark.usefixtures("edge_driver_init") class Test_URL_Edge(LiveServerTestCase): def test_open_url(self): self.driver.get(("%s%s" % (self.live_server_url, "/admin/"))) assert "Log in | Django site admin" in self.driver.title """ Microsoft Edge Test End """ """ Firefox Test Begin """ @pytest.fixture(scope="class") def firefox_driver_init(request): firefox_driver = webdriver.Firefox() request.cls.driver = firefox_driver yield firefox_driver.close() @pytest.mark.usefixtures("firefox_driver_init") … -
Django won't create SQLite3 database
So I have a django project that I used with a MySQL database. And now I'm following the MDN tutorial to try to deploy it on Railway. I have changed the database from MySQL to SQLite3. And now when I try to run it on my local machine I receive this error: (venv) ~/Documents/FDM/Readinghood POD Project/readinghood $ python3 manage.py makemigrations readinghoodWARNING:root:No DATABASE_URL environment variable set, and so no databases setup /Users/lionel/Documents/FDM/Readinghood POD Project/readinghood/venv/lib/python3.11/site-packages/airflow/configuration.py:241: DeprecationWarning: distutils Version classes are deprecated. Use packaging.version instead. if StrictVersion(sqlite3.sqlite_version) < StrictVersion(min_sqlite_version): Traceback (most recent call last): File "/Users/lionel/Documents/FDM/Readinghood POD Project/readinghood/venv/lib/python3.11/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/lionel/Documents/FDM/Readinghood POD Project/readinghood/venv/lib/python3.11/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute return super().execute(query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ sqlite3.OperationalError: no such table: book The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/lionel/Documents/FDM/Readinghood POD Project/readinghood/manage.py", line 22, in <module> main() File "/Users/lionel/Documents/FDM/Readinghood POD Project/readinghood/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/lionel/Documents/FDM/Readinghood POD Project/readinghood/venv/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/Users/lionel/Documents/FDM/Readinghood POD Project/readinghood/venv/lib/python3.11/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/lionel/Documents/FDM/Readinghood POD Project/readinghood/venv/lib/python3.11/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/Users/lionel/Documents/FDM/Readinghood POD Project/readinghood/venv/lib/python3.11/site-packages/django/core/management/base.py", line 453, in execute self.check() File "/Users/lionel/Documents/FDM/Readinghood POD Project/readinghood/venv/lib/python3.11/site-packages/django/core/management/base.py", line 485, in check all_issues … -
Is a call using super.save(commit=False) needed on a Model Form parent class needed if only adding in additional attributes after form submit?
Or could I just use the regular form instances own save(commit=False) method? Here's the code. I don't understand why this is needed. There is a signal that created the a profile extension instance but it's called post_save. (I don't think there's much use in the signal here either). The model view call on save is pretty basic too, no additional form handling other than calling save. Any guidance here is much appreciated. views.py: class ProfileSignupView(CreateView): model = CustomUser form_class = ProfileSignupForm template_name = 'accounts/profile_signup.html' def form_valid(self, form): user = form.save() login(self.request, user) return render(self.request, "accounts/userdash.html", {user: user.id}) forms.py: class ProfileSignupForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = CustomUser fields = ('email',) def save(self): data = super().save(commit=False) # <-- why is this needed? data.is_local = True data.save() return data signals.py: @receiver(post_save, sender=CustomUser) def create_user_type(sender, instance, created, **kwargs): if created and instance.is_local == True: Profile.objects.create(user=instance) -
Access the rows of a model B through a list of foreign keys of B
I have 2 models A & B in django, A stores a list of foreign keys to B in a JSONField. In the template, how do I retrieve the B instances from the B foreign keys stored in A? models.py class B(models.Model): someField = models.CharField(max_length = 128) class A(models.Model): # e.g. contains [1, 5, 3, 6, 2]: foreignKeysOfB = models.JSONField(null = True) views.py def myView(request): a = A.objects.all() b = B.objects.all() context = { 'a':a, 'b':b, } template = loader.get_template('my_template.html') return HttpResponse(template.render(context, request)) my_template.html {% for my_a in a %} {% for foreignKeyOfB in my_a.foreignKeysOfB %} <tr> <td>{{ do something to get the B out of its foreign key}}</td> </tr> {% endfor %} {% endfor %} -
Selenium "ERR_CONNECTION_RESET" using headless on Heroku
I have a Django + Selenium app I'm trying to deploy to Heroku. I have a management command I call that activates a Selenium Webdriver to use. Whenever I run it locally it's totally fine (without headless) however upon deploying to Heroku no matter what I try I just get: Message: unknown error: net::ERR_CONNECTION_RESET (Session info: headless chrome=116.0.5845.140) I instantiate my webdriver as follows: ... logger.info("Starting selenium webdriver...") options = Options() options.add_argument("--headless") options.add_argument("--disable-dev-shm-usage") options.add_argument("--no-sandbox") options.add_argument("--disable-gpu") options.add_argument("--enable-logging") options.add_argument("--incognito") options.add_argument("--ignore-certificate-errors") options.add_argument("--disable-extensions") options.add_argument("--dns-prefetch-disable") self.webdriver = webdriver.Chrome( service=Service(ChromeDriverManager().install()), options=options ) I think the issue is the headless argument - adding it locally at least is what breaks things, however. This is running on Heroku so I need the headless to work. I'm really stumped. Any help/advice is appreciated - thank you! -
drf-spectacular produce array of dict instead of dict
This is my GET request with drf-spectacular for swagger generation: @extend_schema(request=None,response=RespondentResponseTransactionalWithQuestionGetSerializer(many=False) ) def get(self, request, *args, **kwargs): This is Serializer itself: class RespondentResponseTransactionalWithQuestionGetSerializer(serializers.Serializer): answers = RespondentResponseTransactionalGetSerializer(many=True) general_question = GeneralQuestionResultTransactionalPostSerializer(required=False) which I expect to produce an object similar to this: { "general_question": { "id": 0, "value": "string", "employee": 0, "general_question": 0 }, "answers": [ { "employee": 0, "activity": 0, "fte": 99999, "values": [ { "value": 2147483647, "subdimension": 0 } ], "custom_fields": [ { "value": "string", "custom_field": 0 } ] } ] } But instead of this I getting an array of similar objects according to swagger documentation: [ { "general_question": { "id": 0, "value": "string", "employee": 0, "general_question": 0 }, "answers": [ { "employee": 0, "activity": 0, "fte": 99999, "values": [ { "value": 2147483647, "subdimension": 0 } ], "custom_fields": [ { "value": "string", "custom_field": 0 } ] } ] }] Any ideas on how to make it looks properly? I tried many=False, without many but nothing of that seems to work for me. -
Browser not saving cookies but Set-Cookie headers present
I am using React frontend and Django backend and have been struggling for days with authentication. I have boiled down the issue I am having to the browser not setting the cookies it receives from the backend. When in inspect, I can verify that the Set-Cookie headers are present in the response. They are not appearing in storage though... (the cookies are a csrf token and session id). Other functionalities dependant on these cookies like logout fail. However, when using the Django rest framework interfaces (connecting to the backend urls, e.g., localhost:8000/users/login/), I can perform the login and over there, the cookies appear in storage. I have tried both fetch and axios, I have included credentials: 'include' and withCredentials: true respectively. As a final note, when using fetch, I grab the response fetch(url, { ... }) .then(res => console.log(res.headers.get('Set-Cookie'))) When this prints null, when looping over all present headers I only see two (like application json). For reference some screenshots. These are all the cookies present, I am expecting to see csrftoken and session. The next image shows the headers, there are two Set-Cookie headers with both sessionid and csrftoken. And finally the cookies from the response I have enabled … -
Forms with HTMX, how to choose where to post?
I have a page '/ask-tagname' with an html form <form hx-post="/set-tagname"> <label for="tagName">Tag Name:</label> <input type="text" id="tagName" name="tagName" required /> <button >Submit</button> </form> I am serving this by Django and the views file serving both endpoints is the following from django.shortcuts import render, redirect from django.core.handlers.wsgi import WSGIRequest from lobby.models import Users from django.http import HttpResponse def ask_tagname(request: WSGIRequest): return render(request, "tag_name_entry.html", {}) def set_tagname(request: WSGIRequest): tagName = request.POST["tagName"] defaults = {"tag_name": tagName} print(defaults) Users.objects.update_or_create(id=user_id, defaults=defaults) response = HttpResponse() response["HX-Redirect"] = "/" return response when I click on the submit button I get a GET request to '/ask-tagname' with the tagname as url parameter followed by an empty POST to '/set-tagname'. What I expected is no more calls to '/ask-tagname' and instead a post request to '/set-tagname' with tagname as parameter. -
Book an appointment in Django
I want to book a specific time for the user (start hour and end hour ) and no one else can book at the same time Example Like : John made an appointment on the 5th day of the month at 7 to 8 o'clock i want no one else can book at the same time How I can Do This in Models Django I could not find a solution to this problem -
make prestashop store in a django subdomain
good afternoon everyone, I have my website made with django (python app), hosted in the domain www.cannareis.com.ar. but I want to add a virtual store using prestashop. Thanks to my hosting provider, I can download prestashop directly from the Cpanel of my website. Since I already have my page made with django, I don't want or can't put my page made with prestashop in the same domain, so I created a subdomain called www.tienda.cannareis.com.ar. but when I want my prestashop to be hosted there, it doesn't let me and the first thing that appears when I enter is the django error message, asking me to put the domain in allowed hosts. I don't understand why the django message appears if I'm on a subdomain, I'm not on the original domain where I put my django app. I tried to register the subdomain in allowed hosts (settings.py) but when I do that, when I enter the subdomain www.tienda.cannareis.com.ar , the main template of my web page appears, that is, the "home". and to access the prestashop page I have to add /es to the url. that is to say, it remains www.tienda.cannareis.com.ar/es/ or putting anything after the / takes me to … -
How can I use a Django template variable inside a HTML tag attribute?
Im trying to make a wikipedia clone for studying purposes, 'encyclopedia' is my django app name and {{entry}} its a wiki page. My code line looks like this : <a href="{% url 'encyclopedia:{{entry}}'%}">, I searched in google but cant find anyone talking about django variables inside HTML tag atributtes. When I run my code i see this error: `NoReverseMatch at / Reverse for '{{entry}}' not found. '{{entry}}' is not a valid view function or pattern name. `