Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a draggable icon on a web page with JavaScript or a third-party library
I would like to create a website where I can create a round icon by clicking an add button. I can then drag and drop the icon onto an image. When I release the mouse, the icon's position on the image should be saved. Later, on another page, the icon should be displayed on the same position. For the backend I use Django. I have not been able to find a way to implement this and would like to ask for your ideas. -
How to prevent double encryption in Django with Vercel
I am hosting a django website on Vercel and, both, vercel and Django are encrypting the url. So, the " " character in the url gets encrypted to "%20" and then django again encrypts it to "%2520", but when decrypting, it decrypts only once. In my code, I am appending a name which allows " " to be used and that name gets appended to url which later gets used by a function in views.py as pk(not primary key but just a way to get data from the database). The problem is clearly seen in the image, url has replaced " " with %20 but django se getting "%2520". So, the problem was just with the " " character, so I removed space character from the name, which solves the problem, but I don't want that to be the solution. -
Cannot query "zs": Must be "Product" instance
I want the seller to be able to choose one of the offers for sale and then close the sale by clicking on the close button. This code doesn't do anything if I put a separate for loop in the html file, but if it's the way I sent it, it displays the button to close the sale, but after clicking the button, it gives this error. and, I feel that this graphic is not very user-friendly. What is your suggestion for a better design and to reduce the number of buttons to close the auction? Error: Exception Type: ValueError at /seller_page/ Exception Value: Cannot query "zs": Must be "Product" instance. views.py: def seller_page(request): seller_offers = PriceOffer.objects.filter(product=request.user) if request.method == 'POST': offer_id = request.POST.get('offer_id') offer = get_object_or_404(PriceOffer, pk=offer_id) offer.is_closed = True offer.save() return render(request, 'auctions/product_detail.html', {'seller_offers': seller_offers}) def close_offer(request): if request.method == 'POST': offer_id = request.POST.get('offer_id') offer = get_object_or_404(PriceOffer, pk=offer_id) offer.is_closed = True offer.save() return redirect('seller_page') product_detail.html : <ul> {% for offer in offers %} <li><a> {{ offer.author }}:{{ offer.offer_price }}</a></li> <form method="post" action="{% url 'close_offer' %}"> {% csrf_token %} <input type="hidden" name="offer_id" value="{{ offer.id }}"> <button type="submit">Close Offer</button> </form> {% endfor %} </ul> <form method="POST" action="{%url 'product_detail' product.id %}"> … -
django.db.utils.ProgrammingError: relation "authentication_cityhaldata" does not exist LINE 1: ...hentication_cityhaldata"
I'm trying to perform migrations on my production server. I installed all packages and dependencies. However, I receive the message: django.db.utils.ProgrammingError: relation "authentication_cityhaldata" does not exist LINE 1: ...hentication_cityhaldata"."url_for_interview" FROM "authentic... I tried deleting all files from the migrations folder of the application and project, but it didn't help. I then tried to create a migration only for the authenticator app by 'python manage.py makemigrations authentication' it didn't work properly. What can I do to make the system allow me to create a makemigrations on the server? My modes: from django.db import models from django.contrib.auth.models import AbstractUser from imagekit.models import ProcessedImageField, ImageSpecField from imagekit.processors import ResizeToFill from decimal import Decimal from django.utils.text import slugify from dashboard.choices import PROVINCES_CHOICES class CustomUser(AbstractUser): ACCOUNT_TYPE_CHOICES = [ ('Konto firmowe', 'Konto firmowe'), ('Konto indywidualne', 'Konto indywidualne'), ] name = models.CharField(max_length=200, blank=True, null=True) [..more fields here..] def __str__(self): return self.email class Meta: ordering = ['email', ] class RecommendationsSystem(models.Model): owner = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='owner', verbose_name='Osoba pierwsza') [..more fields here..] class SocialMediaUrl(models.Model): PERCENT_RANGE = [ (0.05, '5 procent'), # (0.10, '10 procent'), # (0.15, '15 procent'), # (0.20, '20 procent'), # (0.25, '25 procent'), # (0.30, '30 procent'), # (0.35, '35 procent'), # (0.40, '40 procent'), # (0.45, … -
How to update availability set by user?
I have a model with two users Student and Consultant. Consultant is able to set up his availability like this: from django.db import models from userregistration.models import UserProfile class Setup_Availability(models.Model): consultant = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name='consultant_availability') start_date = models.DateField() # The date when availability starts monday_start_time = models.TimeField(null=True, blank=True) monday_end_time = models.TimeField(null=True, blank=True) tuesday_start_time = models.TimeField(null=True, blank=True) tuesday_end_time = models.TimeField(null=True, blank=True) wednesday_start_time = models.TimeField(null=True, blank=True) wednesday_end_time = models.TimeField(null=True, blank=True) thursday_start_time = models.TimeField(null=True, blank=True) thursday_end_time = models.TimeField(null=True, blank=True) friday_start_time = models.TimeField(null=True, blank=True) friday_end_time = models.TimeField(null=True, blank=True) saturday_start_time = models.TimeField(null=True, blank=True) saturday_end_time = models.TimeField(null=True, blank=True) sunday_start_time = models.TimeField(null=True, blank=True) sunday_end_time = models.TimeField(null=True, blank=True) def __str__(self): return f"Availability for {self.consultant.user.username} starting on {self.start_date}" And Student will be able to book appointment through: class Appointment(models.Model): student = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name='student_appointments') consultant = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name='consultant_appointments') appointment_datetime = models.DateTimeField() appointment_start_time = models.TimeField() appointment_end_time = models.TimeField() is_available = models.BooleanField(default=True) def __str__(self): return f"{self.student.user.username} - {self.consultant.user.username} - {self.appointment_datetime}" def book_appointment(request): day_of_week_name = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'] if request.method == 'POST': form = AppointmentBookingForm(request.POST) if form.is_valid(): consultant = form.cleaned_data['consultant'] date = form.cleaned_data['date'] appointment_start_time = form.cleaned_data['appointment_start_time'] appointment_end_time = form.cleaned_data['appointment_end_time'] # Check if the selected time slot is available availability = Setup_Availability.objects.get(consultant=consultant) day_of_week = date.weekday() available_start_time = getattr(availability, … -
How to get last modified date with each image present in different folders in AWS S3 bucket
I have created a bucket on aws s3 storage and saving folders dynamically by the user in that bucket. The code is working perfectly and getting each folder images. But I am not able to get last modified date of each image present in different folders. I want to get last modified date of each image present in different folders. #views.py code: def home(request): data = {} storage = S3Boto3Storage() s3 = boto3.client('s3') image_info_list = {} for obj in s3.list_objects(Bucket=storage.bucket_name)['Contents']: # Getting the folder name from the object key. folder_name = obj['Key'].split('/', 1)[0] if folder_name not in image_info_list: image_info_list[folder_name] = [] # Adding the image url to the folder's image list. image_info_list[folder_name].append(storage.url(obj['Key'])) # Check if a Camera instance with the same name already exists camera, created = Camera.objects.get_or_create(name=folder_name) data = { 'image_info_list': image_info_list, 'cameras': cameras, } return render(request, 'index.html', data) -
How to use Django test without Django models?
I have a Django app for REST api, but not using Django REST Framework. I don't use models for any tables, only using Raw SQL query. Could've used flask since not using any Django features, but higher ups decided to use Django. I want to use Django test but digging in the source code I can see both dumpdata and loaddata which test uses to create Test DB uses app's model. But since I don't have any models how do I test my Django app? It is OK to use the actual development DB for testing. I see django overrides the DEFAULT_DB_ALIAS connection param with the newly created test db params, should I just override the param with the actual default db connection param instead? So can I use django test without models and migrations? can I use default database for testing and prevent django from creating a test db? -
Angular 16 catch errors response from Django
i learning Angular and i have a standard login service in Angular 16.2.0 and backend with Django. I post login details all working fine but when i catch errors i get only get only generic errors, Django is sending personalized messages for errors and i try to catch those to be able to show them in frontend. This is my login service function: login(username: string, password: string): Observable<any> { return this.http.post(apiRoot + 'dj-rest-auth/login/', { username, password, }, ).pipe(catchError((error: HttpErrorResponse) => { let errorMsg = ''; if (error instanceof ErrorEvent) { errorMsg = `Error: ${error}`; } else { errorMsg = `Error Code: ${error}, Message: ${error.message}`; console.log(error.message) } return throwError(() => new Error(errorMsg)); })); } Now in case of an error this is all i got: Http failure response for https://link.stars-nexus.com/dj-rest-auth/login/: 400 OK . In network i have: Network Headers Django is sending personalized error messages in response: Response Image That messages i try to catch them to be able to show them letter in front end. Django is taking care of all validations and provide proper personalized per error feedback. There is any way to catch them? Thank Kind regards. To be able to catch those messages from error response to … -
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.