Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Registration showing password does not match
I am a beginner that start from python crash course. In the chapter 19, registration, when I tried to register user, it always have this line "Your username and password didn't match. Please try again." Views.register def register(request): if request.method != 'POST': form = UserCreationForm() else: form = UserCreationForm(data=request.POST) if form.is_valid(): # account created new_user = form.save() # Check the username and password is correct # password is hashed, cannot retrieve normally authenticated_user = authenticate(username=new_user.username, password=request.POST['password1']) # login to the user account login(request,authenticated_user) return HttpResponseRedirect(reverse('learning_logs:index')) context = {'form':form} return render(request,'users/register.html',context) register.html {% extends "learning_logs/base.html" %} {% block content %} <!-- the action is the views url that handle the form ---> <form method="post" action="{% url 'users:login' %}"> {% csrf_token %} {{ form.as_p }} <button name="register"> Register </button> <input type="hidden" name="next" value="{% url 'learning_logs:index' %}"> </form> {% endblock content %} login.html {% extends "learning_logs/base.html" %} {% block content %} {% if form.errors %} <p> Your username and password didn't match. Please try again. </p> {% endif %} <!-- the action is the views url that handle the form ---> <form method="post" action="{% url 'users:login' %}"> {% csrf_token %} {{ form.as_p }} <button name="login"> Login </button> <input type="hidden" name="next" value="{% url 'learning_logs:index' … -
Is it possible to create custom class for the Django default table 'auth_group_permissions'?
Is it possible to create custom class for the Django default table 'auth_group_permissions'? I want to create a simple history table for the 'auth_group_permissions' table. Is it possible to create a custom table by inheriting the base class auth_group_permissions. -
I need an interactive page in Django [closed]
The user uploads a checklist: The user uploads a file with a checklist and a note to the site. Checking for comments: The system analyzes the downloaded file. If there are any comments, go to the next step. If not, it ends. Model for downloading letters and instructions: The site provides the user with a form for downloading a letter and prescription. The user downloads the appropriate files and proceeds to the next step. Processing of letters and instructions: The system processes the downloaded letter and order and proceeds to the next step. Model for loading a repeat checklist: The site provides the user with the opportunity to download a new checklist and note. Checking the repeated checklist: The system analyzes the new file. If there are any comments, go to step 3 (downloading the letter and instructions). If there are no comments, go to step 7. Model for downloading the report: The site provides the user with a form to download the report. The user downloads the report and proceeds to the next step. Completing the process: The system processes the downloaded report. All these steps should be on one page. I tried using fetch js, but something went … -
server django and react [closed]
i have a server problem when I try to valide all data from input I use REACT for the frontend and DJANGO for the backend here is my problem on the console: Erreur lors de l'envoi de la requête: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data Guest.js:93 handleSubmit Guest.js:93 here is my code which contains the handleSubmit function: handleSubmit = e => { e.preventDefault(); const { nom, prenom, contact, dateRDV } = this.state; const client = { nom, prenom, contact, dateRDV }; // Créez un objet contenant les données du formulaire // const Data = { // nom: nom, // prenom: prenom, // contact: contact, // rdv: dateRDV // }; this.setState((prevState) => ({ clients: [...prevState.clients, client], nom: '', prenom: '', contact: '', dateRDV : '' })); // Envoyez les données du formulaire au serveur Django fetch('http://127.0.0.1:8000/store/ClientGuest/', { method: 'POST', headers: { 'Content-Type': 'application/json', // Utilisez JSON pour le contenu }, body: JSON.stringify(client), }) .then(response => response.json()) .then(data => { console.log('Réponse du serveur:', data); // Faites quelque chose avec la réponse du serveur si nécessaire this.props.history.push({ pathname: '/ListeClients', state: { data: client } }); }) .catch(error => { console.error('Erreur lors de l\'envoi de la requête:', … -
Django: How to do something in init state of ModelAdmin
Currently I have something like this: from django.db import models from django.contrib import admin import requests API_SERVER= 'https://someapiserver.com' class Member(models.Model): nodeid = models.CharField(max_length=20, blank=True, null=True, editable=False) authorized = models.BooleanField(default=False) name = models.CharField(max_length=15, blank=False, null=False) assigned_ip = models.CharField(max_length=15, blank=True, null=True, verbose_name='USE IP') def __str__(self) -> str: return self.name class MemberAdmin(admin.ModelAdmin): list_display = ('nodeid', 'name','authorized', 'assigned_ip', 'from_ip') def from_ip(self, obj): try : r = requests.get(f'{API_SERVER}/peer/{obj.nodeid}') srcData = r.json() srcIP = srcData['from_ip'] return srcIP except Exception as e : return 'Unknown' I realize that with above methode, I need to make a http call for each custom field ('from_ip'). Acttualy, the API_SERVER can give me list of all peer in single call by just use r = requests.get(f'{API_SERVER}/peer') My question is : How to define a 'custom variable' inside this modelAdmin in init state, so that I can change my custom field definition like def from_ip(self, obj): try : srcData = [p for p in self.peers if p['id'] == obj.nodeid][0] srcIP = srcData['from_ip'] return srcIP except Exception as e : return 'Unknown' Sincerely -bino- -
I am getting Exception: 'QuerySet' object has no attribute 'client' where client is defined as a foreign key on a one to many relation
Here are the log entries around the prolem. 2023-09-25 10:29:25,768 - facebookapi.fetchMetadata - CRITICAL - about to save to master 2023-09-25 10:29:25,771 - facebookapi.fetchMetadata - CRITICAL - Master exists now update... 2023-09-25 10:29:25,773 - facebookapi.fetchMetadata - CRITICAL - _master.save() Exception: 'QuerySet' object has no attribute 'client' Here are the two models Client and Master class Client(models.Model): id = models.BigAutoField(primary_key=True), name = models.CharField(max_length=200, blank=False, null=True) #more fields abbreviated class Master(models.Model): id = models.BigAutoField(primary_key = True) client = models.ForeignKey(Client, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) user_metadata = models.JSONField(max_length=5000, null=True, blank=True) user_id = models.CharField(max_length=500, blank=False, null = True) user_name = models.CharField(max_length=500, blank=False, null = True) #more fields abbreviated and the code that is generating the error. logger.critical("about to save to master+++++++++++++++++++++OOOOOOOOOOOO+++++++++++++") try: _master = Master.objects.filter(client=client_fk) if _master is None: logger.critical("Master does not exist now create...") new_master = Master.objects.create() new_master.client = client_fk new_master.user_id = user_id new_master.user_name = result["name"] new_master.user_apprequests = _connections1["apprequests"] new_master.user_business_users = _connections1["business_users"] new_master.user_businesses = _connections1["businesses"] new_master.user_accounts = _connections1["accounts"] new_master.user_adaccounts = _connections1["adaccounts"] new_master.user_assigned_ad_accounts = _connections1["assigned_ad_accounts"] new_master.user_assigned_pages = _connections1["assigned_pages"] new_master.user_permissions = _connections1["permissions"] new_master.user_personal_ad_accounts = _connections1["personal_ad_accounts"] new_master.user_metadata = result["metadata"] new_master.account_status = "created" new_master.save() else: logger.critical("Master exists now update...") logger.critical("Master.client: %s", _master.client) #_master.client = client_fk _master.user_id = user_id _master.user_name = result["name"] _master.user_apprequests = _connections1["apprequests"] _master.user_business_users … -
How to Update a django model wihtout using Django forms
I have a model called Record which i am trying to Update it by validating the html form without using Django Forms. I dont know what is wrong with my views.py Views.py def update_record(request, pk): current_record = Record.objects.get(id=pk) if request.user.is_authenticated: if request.method =='POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] email = request.POST['email'] phone_number = request.POST['phone_number'] state = request.POST['state'] current_record = Record.objects.update(first_name=first_name, last_name=last_name, email=email, phone_number=phone_number, state=state) current_record.save() print('Record updated sucessfully') messages.info(request,'Record updated sucessfully') return redirect('home') return render (request, 'update_record.html', {current_record:current_record}) else: messages.info(request, 'you dont have access to this, you must login') return redirect ('home') -
How to optimize nested serializer custom update method
I'm writing a serializer that points to a nested serializer and as the documentation explains it is necesary to write custom create and update methods so that nested serializers could be writable. The way I'm doing this is next: def update(self, instance, validated_data): instance.attr1 = validated_data.get('attr1', instance) instance.attr2 = validated_data.get('attr2', instance) instance.attr3 = validated_data.get('attr3', instance) instance.save() return instance but the instance has 26 attributes. The question is. Is there a way of improving this code? -
Why is paddle.com overlay checkout not working from localhost?
I am trying to get a simple paddle.com overlay checkout working from a local hosted Django site - I'm using the sandbox for now. Currently I am just getting a "something went wrong" dialog when I try and open the checkout. I think I am following all the steps: I am including the following js in the webpage that is trying to show the checkout: <script src="https://cdn.paddle.com/paddle/paddle.js"></script> <script type="text/javascript"> Paddle.Environment.set('sandbox'); Paddle.Setup({ vendor: xxxx, }); </script> And then in the html later on in this page I have a button that I am pressing: <a href="#!" class="paddle_button" data-product="pri_xxxxxxxxxxxxx">Buy Now!</a> I have also set up the address in the sandbox checkout settings to be the url of the same page: https://localhost:8000/account/subscription When I press the Buy Now button I get the “something went wrong” dialog box coming up. I notice in Firefox developer console that it is trying to do an http get on: https://sandbox-create-checkout.paddle.com/v2/checkout/product/pri_xxxxxxxx/?product=pri_xxxxxxxxx&parentURL=https://localhost:8000/account/subscription&parent_url=https://localhost:8000/account/subscription&referring_domain=localhost:8000 / localhost:8000&display_mode=overlay&apple_pay_enabled=false&paddlejs-version=2.0.72&vendor=xxxxx&checkout_initiated=1695581565275&popup=true&paddle_js=true&is_popup=true And when I try and do a get on this link manually I get the following JSON back: {"errors":[{"status":404,"code":"error-creating-checkout","details":"Error creating the checkout"}]} I can also see a Cross-Origin Request Blocked error code in the console too – so I don’t know if that has something … -
How can I translate a Django website entirely?
I have a Django project. How can I translate the entire website? It's worth noting that additional data can be added to the database later, so I want to translate all the existing data in the database, including information added later. -
Django project - quiz Error 405 while clicking on + on the website
I am writing an newbie application - newbie quiz for learning programming languages. I am getting this message: #views.py from django.shortcuts import render from django.views import View from .models import Question # Create your views here. class QuestionView(View): def get(self, request): if request.method == "POST": print('Received data:', request.POST['itemName']) Question.objects.create(name = request.POST['itemName']) all_items = Question.objects.all() #Access to items from database Nur 1 .get(id=1); .filter(name='Hello') return render(request, "questionmanager.html", {'all_items': all_items}) #models.py from django.db import models from datetime import date # Create your models here. class Question(models.Model): created_at=models.DateField(default=date.today) name=models.CharField(max_length=200) done=models.BooleanField(default=False) #HTML - here questions/ items can be added <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-COMPATIBLE" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link href="https://fonts.googleapis.com/css2?family=Lato&display=swap" rel="stylesheet" /> <style> body { font-family: "Lato", sans-serif; background-color: rgba(179, 241, 245, 0.1); margin: 0; } header { background-color: rgba(142, 250, 184, 0.05); display: flex; padding-left: 20px; box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.1); } button { height: 60px; width: 60px; border-radius: 50%; background-color: rgba(163, 122, 11); border: unset; font-size: 35px; color: rgba(31, 28, 20); position: absolute; right: 16px; bottom: 16px; } .list-item { background-color: #9effff; height: 60px; box-shadow: 2px 2px 2px rgba(0, 0, 0, … -
Django Rest Framework Default Settings Not Working
I'm facing an issue with Django Rest Framework (DRF) where the default settings I've configured in my settings.py file are not working as expected. Specifically, I've set up default pagination and authentication classes, but they don't seem to be applied to my views. I am using : python3.11 Django==4.2.5 djangorestframework==3.14.0 django_filter==23.3 Here are the relevant parts of my project configuration: settings.py: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10, 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', 'rest_framework.permissions.DjangoModelPermissions', ] } project/urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')), ] myapp/urls.py urlpatterns = [ path('myview/', views.MyListView.as_view()), # MyListView is a DRF view ] -
I can't populate the datatable in postgresql from Django
I'm struggling to populate the a table in a postgresql Database, it worked fine when for Users Database. My PropertyListing Model is not populating as a table in postgresql when i run Python manage.py migrate PropertyListings --database=PropertyListing Operations to perform: Apply all migrations: PropertyListings Applying PropertyListings.0001_initial... OK it populates a tabled called django_migrations as attached in the screenshotenter image description here here is my model.py file from django.db import models from django.utils.translation import gettext_lazy as _ from django.core.validators import FileExtensionValidator PROPERTY_CHOICES = [ ("DVILLA", _("Detached Villa")), ("SDVILLA", _("Semi-Detached Villa")), ("Apartment", _("Apartment")), ("House", _("House")), ("Land", _("Land")), ("Commercial", _("Commercial")), ("Agriculture", _("Agriculture")), ] LISTING_CHOICES = [ ("RENT", _("Rental")), ("SELL", _("Sell")), ("VACRENTAL", _("Vacation Rental")), ] class ImageFieldWithExtension(models.ImageField): def __init__(self, *args, **kwargs): kwargs.setdefault('upload_to', 'MarocHomes/') kwargs.setdefault('validators', [FileExtensionValidator(allowed_extensions=['jpg', 'jpeg', 'png'])]) super().__init__(*args, **kwargs) class PropertyListing(models.Model): listing_type = models.CharField(max_length=200,blank=False, null=True, choices=LISTING_CHOICES, verbose_name=_("Listing Type")) realtor = models.EmailField(max_length=255, blank=False, null=True) propertytype = models.CharField(max_length=200, blank=False, null=True, choices=PROPERTY_CHOICES, verbose_name=_("Property Type")) slug = models.SlugField(unique=True, default="") title = models.CharField(max_length=50, verbose_name=_("Title")) building_name = models.CharField(max_length=100, blank=True, null=False, verbose_name=_("Building Name/Building No.")) street_name = models.CharField(max_length=100, blank=False, null=False, verbose_name=_("Street Name")) city = models.CharField(max_length=100, blank=False, null=False, verbose_name=_("City")) postal_code = models.CharField(max_length=50, blank=False, null=False, verbose_name=_("Postal Code")) description = models.TextField(blank=True, verbose_name=_("Description")) price = models.DecimalField(max_digits=30, decimal_places=2, verbose_name=_("Price")) ceiling_height = models.FloatField(blank=True, null=True, verbose_name=_("Ceiling height")) bedrooms = … -
Problem with Django project while trying to dockerise [duplicate]
im trying to run my django project as a Webserver. Dockerfile: FROM python:3.8.3-slim WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 #install dependencies RUN pip install --upgrade pip RUN pip install --upgrade setuptools COPY ./webserver /usr/src/app/ RUN pip install -r requirements.txt RUN python manage.py makemigrations RUN python manage.py migrate EXPOSE 8000 CMD [ "python", "manage.py", "runserver", "0.0.0.0:8000" ] while the makemigrations is running i get the error that the DB tables dont exist. I also tried to run makemigrations after the Container started. But that also does not work and i get the same error. I made the github Repo public if you would like to test it for yourself: my Github Repo thank you for your help in advance. -
Langchain : Querying from postgresql database using SQLDatabaseChain
i am querying postgresql database using langchain. For this i am using Claude llm whose api key is anthropic_api_key. I am connecting postgresql database using SQLDatabase.from_uri() method. this is my code inside file postgres_db.py from langchain import SQLDatabase from constants import anthropic_key from langchain.chat_models import ChatAnthropic from langchain_experimental.sql import SQLDatabaseChain from langchain.agents.agent_toolkits import SQLDatabaseToolkit from langchain.agents import create_sql_agent from langchain.agents.agent_types import AgentType import os os.environ["ANTHROPIC_API_KEY"] = anthropic_key API_KEY = anthropic_key # Setup database db = SQLDatabase.from_uri( f"postgresql+psycopg2://postgres:umang123@localhost:5432/delhi_cime_2", ) # setup llm llm = ChatAnthropic(temperature=0) # Create db chain QUERY = """ Given an input question, first create a syntactically correct postgresql query to run, then look at the results of the query and return the answer. Use the following format: "Question": "Question here" "SQLQuery": "SQL Query to run" "SQLResult": "Result of the SQLQuery" "Answer": "Final answer here" "{question}" """ # Setup the database chain db_chain = SQLDatabaseChain(llm=llm, database=db, verbose=True) def get_prompt(): print("Type 'exit' to quit") while True: prompt = input("Enter a prompt: ") if prompt.lower() == 'exit': print('Exiting...') break else: try: question = QUERY.format(question=prompt) result = db_chain.run(question) print(result) except Exception as e: print("eeeeeeeeeeeeeeeeeee",e) pass get_prompt() when i am executing the above script using python postgres_db.py command stuck in this error … -
Django multiple database
I'm using two same structure database in Django: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'database1', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306' }, 'db_1402': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'database2', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306' } } and user select a database in login page. I want to use user selected database in whole project and all Models read and write in user selected database. I try to use database router but user logout automatically. I define bellow decorator to save database name in connections['default'].alias and pass it to database router: from django.db import connections def db_login_required(login_url): def decorator(view): def wrapper_func(request, *args, **kwargs): if not request.user.is_authenticated: next_url = request.get_full_path() return redirect(f'{reverse(login_url)}?{urlencode({"next": next_url})}') connections['default'].alias = request.session.get('database', 'default') return view(request, *args, **kwargs) return wrapper_func return decorator and then I create a database router like this: class SessionDatabaseRouter(object): def db_for_read(self, model, **hints): return connections['default'].alias def db_for_write(self, model, **hints): return connections['default'].alias def allow_relation(self, obj1, obj2, **hints): return True def allow_migrate(self, db, app_label, model_name=None, **hints): return True but after login suddenly user logout automatically. How can fix this? -
Django added .well-known before static/style.css and now the website doesn't see the style.css, why and how to fix?
I used: <link rel="stylesheet" href="{% static 'style.css' %}"> <link rel = "stylesheet" href = "{% static 'whatsapp_widget/whatsapp_widget.css' %}"> And it always worked but today I opened the website and see that the website suddenly doesn't see the style.css. I've discovered that in the style's path it indicates the directory as /.well-known/static/style.css instead of just /static/style.css. Maybe this is the reason? How to fix? Many thanks in advance. -
Deployment of Django project on Railway using Nixpacks
Has anyone know about step by step process how to deploy Django project on Railway using Nixpacks? I really mean easy to follow step by step guide follow up my first steps. I am using Windows 10: Django project created with apps tested locally at http://127.0.0.1:8000/ Django project uploaded on github ... . . . -
Order details not saving to database in django
I am a beginner in django and i have been working on this ecommerce platform for a while now and i'm stuck in this place. Whenever i fill order details form, it is not saving to the database. Please i need your help Here is the form class OrderForm(forms.ModelForm): class Meta: model = Order fields = ['first_name', 'last_name', 'phone_number', 'email', 'address_line_1', 'address_line_2', 'country', 'state', 'city', 'order_note'] Here is the view for the place order: def place_order(request, total=0, quantity=0,): current_user = request.user cart_items = CartItem.objects.filter(user=current_user) cart_count = cart_items.count() if cart_count <= 0: return redirect('store') grand_total = 0 tax = 0 for item in cart_items: total += (item.product.price * item.cart_quantity) quantity += item.cart_quantity tax = (3 * total) / 100 grand_total = total + tax if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): data = Order() data.first_name = form.cleaned_data['first_name'] data.last_name = form.cleaned_data['last_name'] data.phone_number = form.cleaned_data['phone_number'] data.email = form.cleaned_data['email'] data.address_line_1 = form.cleaned_data['address_line_1'] data.address_line_2 = form.cleaned_data['address_line_2'] data.country = form.cleaned_data['country'] data.state = form.cleaned_data['state'] data.city = form.cleaned_data['city'] data.order_note = form.cleaned_data['order_note'] data = form.save(commit=False) data.order_total = grand_total data.tax = tax data.ip = request.META.get('REMOTE_ADDR') # Save the data before generating the order number data.save() # Generate Order Number using the date, month, and day ordered yr = … -
Sphinx mock issue with django `get_user_model` in a custom pakage for django
I am creating a custom package for a django project. The package contains two authentication backends. I have modules configured as below, # Backend 1 module from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend UserModel = get_user_model() # ModelBackend = object # This will fix actual import issue and uses mocked import only class AuthBackendOne(ModelBackend): pass # Backend 2 module from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend UserModel = get_user_model() # here calls actual django method class AuthBackendTwo(ModelBackend): pass In my sphinx conf.py I haveautodoc_mock_imports = [ "django.conf", "django.contrib.auth" ] Issue: The problem is when I generate sphinx-build for docs, in module 2 it is trying to call actual django get_user_model(). It is not considering that was mocked. By trying myself, I found the issue was when I use ModelBackend to base my custom backend class. No issue in importing ModelBackend, but using that breaks the module 2. Just before using ModelBackend, I have re-assigned to object and run sphinx-build with successful. Findings: For my test trials I have printed the UserModel and its type in the above two methods, (I didn't call the get_user_model function in this test) cognito - CustomBackend 1 ldap - CustomBackend 2 In the … -
Axios POST Request using JWT in Vue3 and Django
Alright so as the title says I have a working Django application where my API creates a JWT key and saves it to my cookies. Now my frontend which is in Vue is supposed to send a form to the backend which is supposed to generate the jwt key and set it to my cookies. How do I go about this. My apologies if the writing is a little crude, I have been troubleshooting this for well over 4 hours. It shows me a 403 Forbidden error on my console. Here's a snippet of my code for the frontend: try { const response = await axios.post('link/', UserData) const jwtToken = response.data.jwt Cookies.set('jwt', jwtToken) this.confirmed = true console.log(this.confirmed) } catch(error) { console.log(error) } Everything is imported as it should be. But this is the underlying code. the django app sends a response with the jwt code. while this is not secure, it is needed for the troubleshoot. Please what can i do -
What does the code qs = super(OwnerDeleteView, self).get_queryset() do? [duplicate]
super().get_queryset() call will call the superclass's get_queryset() method depending on the MRO, but what do the parameters (OwnerDeleteView, self) mean? Is it the same as super().get_query_set()? Here is the full code from django.views.generic import CreateView, UpdateView, DeleteView, ListView, DetailView from django.contrib.auth.mixins import LoginRequiredMixin class OwnerUpdateView(LoginRequiredMixin, UpdateView): def get_queryset(self): print('update get_queryset called') """ Limit a User to only modifying their own data. """ qs = super(OwnerUpdateView, self).get_queryset() return qs.filter(owner=self.request.user) -
How to Filtter With Foreign key
I have a football stadium booking site -- the user logs in and then selects the stadium he wants to book and then selects the day and how much he wants to book the canned (an hour or two hours, etc.*) example: user John booked the stadium X on the day of 5 at 10 to 12 I want to make sure that there is no reservation at the same stadium, the same day and the same time, and if there is a reservation at the same data, he does not complete the reservation when i try to filtter in models with Foreign key pitche filter = OpeningHours.objects.filter(made_on=self.made_on,pitche=self.pitche,period = self.period).filter(Q(from_hour__range=in_range) | Q(to_hour__range=in_range)).exists() the error happens (relatedobjectdoesnotexist) OpeningHours has no pitche. my models is : enter image description here and views : enter image description here -
Getting error : django.db.utils.OperationalError: (2002, "Can't connect to server on 'db' (115)"), while trying to host django-mysql on docker
So basically I am trying to setup my Django-MySQL backend on Docker but I am getting errors and not able to run the server. I went through previous answers it didn't help that's why I am putting it here again. I have tried various ways , so i'll list them out and provide the errors as well. First of all here are the required files Django settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_name', 'USER': 'root', 'PASSWORD': 'pass', 'HOST': 'db', # Use 'localhost' for a local MySQL server 'PORT': '3306', # MySQL default port } } DockerFile FROM python:3.9 ENV PYTHONUNBUFFERED 1 RUN mkdir /Pizza-Delivery-System WORKDIR /Pizza-Delivery-System COPY . /Pizza-Delivery-System RUN apt-get update RUN apt-get update && apt-get install -y iputils-ping RUN pip install -r requirements.txt EXPOSE 8000 docker-compose.yml version: '3' services: db: hostname: 'db' image: mysql:8.1.0 environment: MYSQL_DATABASE: db_name MYSQL_ROOT_USER: "root" MYSQL_ROOT_PASSWORD: "password" ports: - "3306:3306" volumes: - ./mysql-data:/var/lib/mysql web: build: context: . dockerfile: Dockerfile command: ["python", "manage.py", "runserver", "0.0.0.0:8000"] volumes: - .:/Pizza-Delivery-System ports: - "8000:8000" depends_on: - db Now here is the method I have tried running all services at once docker-compose up -d In this case I got following error: manually running db service first … -
Add method to the Django CMS Page Model
Problem/Gap The Django CMS documentation clearly describes the process for extending the Page and Title Models. However, documentation on the possibility of adding a method such as the property method below is lacking, or I can't seem to find it. Note: The example provided works perfectly when I include it directly under the Django CMS Page model. This is not the preferred way of course. Question Say I want to add the below method to the Page (cms.models.pagemodel.Page) or Title Model (assuming they are likely to follow the same process) outside the CMS app. How can this be achieved? @property def my_custom_page_property(self): try: logger.info(f'Working....') return {} except Exception as e: logger.error(f'Error: {e}') return {} Attempt In a seperate app I added the code below, and migrated. The image field is properly configured and works fine. The method however doesn't seem to return anything. from cms.extensions import PageExtension from cms.extensions.extension_pool import extension_pool class MyCustomExtension(PageExtension): image = models.ForeignKey(Image, on_delete=models.SET_DEFAULT, default=None, blank=True, null=True) @property def my_custom_page_property(self): ..