Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I cannot connect pip to download any packages
I am new to programming, but my computer seems unable to utilise pip, here is an example of an error I got, I've also tried extending the duration of the connect (forcibly closed by connection host) and tried a tonne of different ways to ask it to install django even specific versions anything that requires connection through pip does not work, ive diabled ipv6 and completely turned off all my firewall safety's, jumbo packets arent a system setting I can change I feel like I'm running out of ideas here, I've been to about 150 different pages today, my goal was to get django working, which I have successfully created a virtual environment for and used git to put django into, but when I attempt to finish setting up django by installing that way in the environment, it needs to download dependencies from somewhere which again result in it getting stuck, can my computer not communicate properly with the websites? I can use curl to view the sources that were layed out and both curl and ping show a perfectly fine connection to these places, I am on a stable internet connection and have tried using a different internet connection … -
Modify Django "Select Form" Icon
I am making a Django app, and I am using Django's form.ChoiceFields to make a form! brand = forms.ChoiceField( label="Marca:", choices=[('', 'Selecionar marca')] + [(brand.id, brand.name) for brand in models.Brand.objects.all()], widget=forms.Select(attrs={'id': 'brand', 'onchange': 'filterModels()', 'class': 'select'}) ) So this is the form element that I get (with a background color), but I want to change the icon pointing up and down in the right but I cannot figure how to do it. I already tried to do it by adding an icon form FontAwesome but the problem is that when I do so, when I click on the icon the form does not open, so it can confuse the users :( I tried adding javascript codes by using implementing the click() function when clicking on the icon but it did not give me any results. So is there a way to do this by simply replacing Django's "Select Form" default arrow icon? Thanks in advance! -
How can I achieve filtering with multiple values for the same parameter in Django?
I am building a Django website that displays snowboards that will fit you based on some parameters. One of the parameters is gender and for example if the user specifies she is a girl, then I want to display Female as well as Unisex boards - and also then filter again by all the other parameters (height, style, level, etc). Same for the boys. I want to also display Male boards as well as Unisex boards. This is the code snippet in my TemplateView: def get(self, request, *arg, **kwargs): gender = request.GET.get('gender') skills = request.GET.get('skills') style = request.GET.get('style') rider_name = request.GET.get('rider_name').split("'")[1].split("'")[0] filter = process_queryset(gender, skills, style) queryset = Snowboard.objects.filter( gender=filter['gender'], style=filter['style'], level=filter['level'], ) return render(request, self.template_name, {'gender': gender, 'snowboards': queryset, 'rider_name': rider_name}) and I have this separate function for processing the filtering: def process_queryset(gender, skills, style): filter_dict = {'gender': 'Female' if gender == 'girl' else 'Male', 'level': 'Beginner' if 'rookie' in skills else 'Intermediate-Advanced'} if style == 'freestyle': filter_dict['style'] = 'Park' elif style == 'freeride': filter_dict['style'] = 'Free Ride' else: filter_dict['style'] = 'All mountain' return filter_dict So I first tried to filter by the gender and have them both (tried both with | and with &) and then nest the … -
Change the parent lookup kwarg in nested routes using Django REST Framework
In this project we use Django, Django REST Framework, DRF Nested Routers and DRF Spectacular. Let's say that we have the model classes Category and Product. We have a nested route: /categories/<category_pk>/products/<pk>/ In the Swagger UI (generated by DRF Spectacular) it is displayed as: /categories/{category_pk}/products/{id}/ I want to change the parent lookup keyword argument to be category_id, but I couldn't find a way to do it. -
I want to genarete report from different modals which are related by foriegn key
class ReporttListView(LoginRequiredMixin,ListView): model = Assignments context_object_name='assignments' template_name="workshop/report.html" login_url='workshop:custom_login' def get_queryset(self): # Filter the assignments by is_valid=True and prefetch the related item and component models return Assignments.objects.filter(is_valid=True).prefetch_related('item', 'item__component_set') class Item(models.Model): """ This is the item model has five fields name,stock_id,serial_no, status(pending,accepted,completed,not maintable),remark """ ws_id = models.CharField(max_length=15) received_date=models.DateField(auto_now=1) stock_id = models.CharField(max_length=15) Serial_no =models.CharField(max_length=15) delivered_by = models.CharField(max_length=100) received_by= models.CharField(max_length=100) status = models.CharField(choices=( ('pending', "pending"), ('on_prograss', "On_progress"), ('completed', "Completed"), ('Not maintainable', "Not maintanable"), ),default='pending' , auto_created=True ) remark= models.TextField(blank=True) is_valid=models.BooleanField(auto_created=True,default=True) is_accepted=models.BooleanField(auto_created=True,default=False) is_maintainable=models.BooleanField(auto_created=True,default=True) def __str__(self) -> str: return self.Serial_no def get_absolute_url (self): return reverse("workshop:item") class Component(models.Model): recived_date=models.DateField(auto_now=True) item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='components') stock_id = models.CharField(max_length=15) Serial_no =models.CharField(max_length=15) is_valid=models.BooleanField(auto_created=True,default=True) def __str__(self) -> str: return self.Serial_no def get_absolute_url (self): return reverse("workshop:component") class Section(models.Model): name = models.CharField(max_length=100) manager = models.ForeignKey(User, on_delete=models.CASCADE) is_valid=models.BooleanField(default=True) def __str__(self) -> str: return self.name class Assignments(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) engineer= models.ForeignKey(User, on_delete=models.CASCADE) Section= models.ForeignKey(Section, on_delete=models.CASCADE) remark= models.TextField(blank=True) Assigned_date=models.DateField(auto_now=True) completed_date=models.DateField(default="2023-11-02",auto_created=True) is_valid=models.BooleanField(auto_created=True,default=True) def __str__(self) -> str: return str(self.item) I want my report contains list of components that is related to every assigned Item . In orrder to achieve this role . I have the above class based view. but my system did not work.It show me the below error. AttributeError at /report Cannot find 'component_set' … -
Using Crispy forms in my Django project and the input field appears to be too small
When I see other examples people can make the entire field screen-wide. Like this: Bootstrap example However what appears on my screen is too small: My example How can I fix it? For reference, I'm using Bootstrap v4.5.3 Code: models.py from django.db import models from django.utils import timezone from django.core.validators import FileExtensionValidator # Create your models here. class Video(models.Model): title = models.CharField(max_length=100) description = models.TextField() video_file = models.FileField(upload_to='uploads/video_files', validators = [FileExtensionValidator(allowed_extensions=['mp4', 'mkv'])]) thumbnail = models.FileField(upload_to='uploads/thumbnails', validators = [FileExtensionValidator(allowed_extensions=['png', 'jpeg', 'jpg'])]) date_posted = models.DateTimeField(default=timezone.now) create_videos.html {% extends 'videos/base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="container mb-5"> <div class="row justify-content-center"> <div class="col-md-6 col-sm-12 col-xs-12"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <legend class="border-bottom mb-4">Upload video</legend> {{ form | crispy }} <div class="col-md-4 ml-auto"> <button class="btn btn-outline-primary btn-block mt-3">Upload</button> </div> </form> </div> </div> </div> {% endblock content %} I have tried: Messing with the 3rd to change col-md size. Editing individual fields (mainly 'title' and 'description') with {{ form.field | as_crispy_field }}. -
ImportError: DLL load failed while importing _psycopg: The specified module could not be found. and i use pip instal psycopg2 and the binary one
enter image description here I can't access tp psycopg2 no error and access to psycopg2 and not connected to django project show error no module found and server can't run and i use pip instal psycopg2 and the binary one (myvenv) C:\Users\justp>python -c "import psycopg2" Traceback (most recent call last): File "", line 1, in File "C:\Users\justp\myvenv\Lib\site-packages\psycopg2_init_.py", line 51, in from psycopg2._psycopg import ( # noqa ImportError: DLL load failed while importing _psycopg: The specified module could not be found. (myvenv) C:\Users\justp>pip freeze -
Netsuite - Multiple Page Forms / Multi Step Forms
Is there a way to setup multiple paged form in Netsuite (or Hubspot) or somehow reorganize it custom after integration in a website. Not a problem if the page is updating or fetching the next field element. The most important is the multi-page structure (as a kind of quiz card) and the completeness of the arranged data. Working on django/js, kind of PRG pattern. Have tried to use the pagination libraries or sliders to give that effect through putting the timeout after the form mounting. Didn't really work. -
Binding Ajax Search Result To TextField
The search functionality that I have implemented using Ajax works as expected, the problem that I am facing is I couldn't find a solution to bind the search result to the text field when I click an item from the search result. The Ajax search results are displayed using resultBox and the input text field used for searching is SearchInput. Upon clicking an item in the resultBox the value needs to be binded to the searchInput. But currently when I click the item in the resultBox the page is getting refreshed. console.log("Sanity check!"); const url = window.location.href window.onload = function() { const searchForm = document.getElementById("search-form") const searchInput = document.getElementById("search-box") const resultBox = document.getElementById("results-box") const csrf = document.getElementsByName("csrfmiddlewaretoken")[0].value const sendSearchData = (stock_name) =>{ $.ajax({ type: "POST", url: '', data:{ 'csrfmiddlewaretoken' : csrf, 'stock_name':stock_name }, success: (res) =>{ console.log(res.data) const data = res.data if (Array.isArray(data)) { resultBox.innerHTML= "" data.forEach(stock_name =>{ resultBox.innerHTML += ` <a href="" style="text-decoration : none;"> <div> <p> ${stock_name.symbol_name} </p> <small> ${stock_name.symbol}</small> </div> </a> ` }) } else { if (searchInput.value.length > 0) { resultBox.innerHTML =`<b>${data}</b>` } else { resultBox.classList.add('not-visible') } } }, error: (err) =>{ console.log(err) } }) } searchInput.addEventListener('keyup',e=> { console.log(e.target.value) if (resultBox.classList.contains('not-visible')){ resultBox.classList.remove('not-visible')} sendSearchData(e.target.value) }) } Please … -
i am facing django.db.migrations.exceptions.InvalidBasesError Cannot resolve bases, when i run python manage.py migrate
I have two apps, coreapp and product app. As all models in product app have common fields , i created a BaseModel in coreapp and then inherited the BaseModel in the models in product app. Then i ran python manage.py makemigrations and python manage.py migrate. After that i made some changes in the models, I added abstract = True in BaseModel and renamed some fields in the models in product app. Then i ran python manage.py makemigrations. Now, when i run python manage.py migrate i get the following error django.db.migrations.exceptions.InvalidBasesError: Cannot resolve bases for [<ModelState: 'product.Attribute'>, <ModelState: 'product.Category'>, <ModelState: 'product.Product'>, <ModelState: 'product.AttributeValue'>] This can happen if you are inheriting models from an app with migrations (e.g. contrib.auth) in an app with no migrations; see https://docs.djangoproject.com/en/4.1/topics/migrations/#dependencies for more Below are the two models coreapp/models.py from django.db import models # Create your models here. class BaseModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) product/models.py from django.db import models from project_root.coreapp.models import BaseModel # Create your models here. class Attribute(BaseModel): title = models.CharField(max_length=100) def __str__(self): return self.title class AttributeValue(BaseModel): title = models.CharField(max_length=100) attribute_object = models.ForeignKey(Attribute,on_delete=models.CASCADE, related_name='attribute_values') def __str__(self): return self.title class Category(BaseModel): title = models.CharField(max_length=200) parent= models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.title … -
session cookie is working in other browser
I created log in system in Django using session(not using built in functionality), Now I face issue like : if I log in into one private tab/in my browser then Django create on cookie named "sessionid" and if I create same cookie on other pc or other browser window(Except current log in window) then that also works and shows user is logged in. Why this problem occur and how i can solve this? I want the solution of this problem and explanation why this happens? -
Creating a range of objects at once in django
I am creating a set of numbers and I want to save each of them in the database. My approach is: class NbrSetForm(forms.ModelForm): last_number = Nbr.objects.order_by("-number").first().number start_number = forms.IntegerField(required=True, initial=last_number+1) end_number = forms.IntegerField(required=True, initial=last_number+1) class Meta: model = Nbr fields = ["start_number", "end_number", ...] exclude = ["number"] def clean(self): cleaned_data = super().clean() s = int(cleaned_data["start_number"]) e = int(cleaned_data["end_number"]) + 1 self.number_list = [n for n in range(s, e)] def save(self, commit=False): for n in self.number_list: print("number to create", number) instance = Nbr.objects.create(number=n, ...) print("all done", instance) return super.save(self) I can see the output of both of the print statements in the console (number has a reasonable value here). But nothing is saved to the database and I get an IntegretyError from the return super().save(self) statement (I guess it's this one) saying: NOT NULL constraint failed: app_nbr.number. -
How to improve a complex django code to reduce database queries and avoid loops?
This code is currently making a separate query to the database for each module in the queryset, because I need to have the progress for each of them. I would like to improve the code so that it makes a single query (or as less queries as possible) to the database and does not use a loop. Can anyone help me with this? This was the best I've got. def get_queryset(self): return CourseLanguage.objects.prefetch_related( "modules", "users" ).filter( pk=self.kwargs["course_language_pk"] ).first() @property def modules(self): modules = [] queryset = self.get_queryset().modules.all().values() for module in queryset: percentage = UserContentAnswer.objects.filter( user=self.request.user, content__topic__module__pk=module["id"] ).aggregate( total=Count("pk"), completed=Count("pk", filter=Q(status=ContentStatusType.COMPLETED)), progress=ExpressionWrapper( Case( When(total=0, then=Value(0.0)), default=100.0 * F("completed") / F("total"), ), output_field=FloatField() ), )["progress"] modules.append( { **module, "percentage": f"{percentage:.1f}" } ) return modules -
Docker build failed [insufficient_scope: authorization failed]
I am trying to build an image for a django project. I tried '''sudo docker login''', after that also same error message. tried in macOS M1 & rasberrypi 4B. **Dockerfile: FROM python3.9.2-slim ENV PYTHONUNBUFFERED 1 RUN sudo apt update -y && sudo apt upgrade -y RUN mkdir /app WORKDIR /app COPY requirements.txt /app/ RUN pip install --user -r requirements.txt COPY . /app/ CMD python3 manage.py runserver Output(sudo docker build . -t ttapp-image): [+] Building 2.1s (4/4) FINISHED docker:default => [internal] load build definition from Dockerfi 0.0s => => transferring dockerfile: 279B 0.0s => [internal] load .dockerignore 0.0s => => transferring context: 2B 0.0s => ERROR [internal] load metadata for docker.io/l 2.0s => [auth] library/python3.9.2-slim:pull token for 0.0s ------ > [internal] load metadata for docker.io/library/python3.9.2-slim:latest: ------ Dockerfile:1 -------------------- 1 | >>> FROM python3.9.2-slim 2 | 3 | ENV PYTHONUNBUFFERED 1 -------------------- ERROR: failed to solve: python3.9.2-slim: pull access denied, repository does not exist or may require authorization: server message: insufficient_scope: authorization failed -
"Got KeyError when attempting to get a value for field `username` on serializer `UserSerializer`
trying to get current user but it shows username keyerror but everything's all good from my side. Can anyone say whats the error? views : @api_view(['POST']) def register(request): data = request.data user = SignUpSerializer(data=data) if user.is_valid(): if not User.objects.filter(username = data['email']).exists(): user = User.objects.create( first_name = data['first_name'], last_name = data['last_name'], username = data['email'], email = data['email'], password = make_password(data['password']) ) user.save() return Response({ 'details':'Sucessfully registered.' }, status.HTTP_201_CREATED) else: return Response({ 'error':'User already exists.' }, status.HTTP_400_BAD_REQUEST) else: return Response(user.errors) Serializers.py : class SignUpSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('first_name', 'last_name', 'email', 'password') extra_kwargs = { 'first_name':{'required':True, 'allow_blank':False}, 'last_name':{'required':True, 'allow_blank':False}, 'email':{'required':True, 'allow_blank':False}, 'password':{'required':True, 'allow_blank':False, 'min_length':4} } This is user serializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('first_name', 'last_name', 'email', 'username') -
What is best practice for organizing Django REST Framework serializers?
I am working on migrating a legacy REST api to Django REST framework. Many responses from contain nested serializers, for example: class TemplateSerializer(serializers.ModelSerializer): colors = ColorSerializer(read_only=True, many=True) fonts = FontSerializer(read_only=True, many=True) property_ids = serializers.PrimaryKeyRelatedField(many=True, queryset=Property.objects.all()) ... class Meta: model = Template fields = '__all__' class ColorSerializer(serializers.ModelSerializer): swatch = SwatchSerializer(read_only=True) class Meta: model = Color fields = '__all__' # and so forth, just imagine several serializers with fields that are read only or write only etc Currently I was have all serializers in my_app/serializers.py and the serializers.py file has grown way too large and disorganized. In that file, a django model usually has several versions of serializers, for example, the list view method may have a different serializer than retrieve and create may have a different serializer than update, etc. So a single ViewSet may have 4-5 different serializers. Also, the nested serializers, like the ColorSerializer above, may have different versions based on requirements of the response when its nested in another serializer versus when GET /colors endpoint is called. With that being said, I want to start organizing/refactoring things for readability to try to be more DRY. I'm aware the API is poorly designed, but redesigning is not an option … -
How to remove from django sitemap pagination ?p=(1,2,3...n)
Okay we have a lot of pages. So when the content pages spill over 400 is created next page for sitemap and it looks like that - sitemap-instructions.xml?p=5 The problem is that pagination is conflicted with robots.txt where we have restrictions for many things including pagination pages. So we tried to handle it with robots.txt but got more problems than we had. My question is How to edit pagination address and replace or remove ?p= -
Django: Object of type WindowsPath is not JSON serializable
I am trying to add ckeditor_uploader to my project, and adding posts in django default admin site. I get the following error: Error during template rendering in \venv\lib\sitepackages\django\contrib\admin\templates\admin\change_form.html, error at line 6 Object of type WindowsPath is not JSON serializable 1 {% extends "admin/base_site.html" %} 2 {% load i18n admin_urls static admin_modify %} 3 4 {% block extrahead %}{{ block.super }} 5 <script src="{% url 'admin:jsi18n' %}"></script> 6 {{ media }} 7 {% endblock %} in settings.py MEDIA_URL = "/media/" MEDIA_ROOT = BASE_DIR / 'media' CKEDITOR_BASEPATH = BASE_DIR / 'static/ckeditor/ckeditor' CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', 'height': 300, 'width': 1300, }, } in models.py from django.db import models from ckeditor_uploader.fields import RichTextUploadingField class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) category = models.ForeignKey(Category, on_delete=models.CASCADE, default=get_default_category) text = RichTextUploadingField(default="add your post here") Kindly help. I tried adding + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) after urlpatterns in urls.py and got no luck. -
How do i get Django API javascript call to work
I am making a fake stock trading django app. i am 99% sure that my file structure is correct. I get a 404 error from the javascript fetch Not Found: /api/stock/IBM/ [24/Oct/2023 19:09:52] "GET /api/stock/IBM/ HTTP/1.1" 404 2250 could someone assist me? I was expecting to get a live feed of the ibm stock. I would also like to make it customizable to any stock. I am new to handling api. Thank you! Relevant Files api_utils.py import requests def fetch_intraday_data(symbol): API_KEY = 'HRUU8PUIVR7TPGIJ' # Replace with your Alpha Vantage API key url = f'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol={symbol}&interval=5min&apikey={API_KEY}' try: response = requests.get(url) response.raise_for_status() # Raise HTTPError for bad responses (4xx and 5xx) data = response.json() # Check if Alpha Vantage returns an error message if "Error Message" in data: return {"error": data["Error Message"]} return data except requests.RequestException as e: return {"error": str(e)} views.py from django import forms from django.shortcuts import render from django.http import HttpResponseRedirect from django.contrib.auth.forms import UserCreationForm from django.urls import reverse from django.contrib.auth.models import User from .models import UserProfile from django.contrib import messages from django.contrib.auth import login as auth_login from django.contrib.auth import logout from django.shortcuts import redirect from django.contrib.auth.forms import AuthenticationForm from django.shortcuts import render from stocktrading.api_utils import fetch_intraday_data from django.http import … -
Querying Django Models linked by a Foreign Key to get a complete Query set, counting liked posts
This is a CS50 Pset - Network - I'm battling my way through this and all but this bit is finished I think I have trapped myself into a corner, I have 4 different Models, 3 are related to this question, User, Posts and LikeMatrix. LikeMatrix uses a Foreign key to both the User Model (user) and the Posts Model (post), its a matrix recording what user liked what post as I couldn't get my original idea to work with a many to many link between User and Posts Models. (if I did it all again I would do it different). I have my Js working, my API's working, evrything else working except the last piece of the puzzle, to count the likes per post in the LikeMatrix Model and then send it to index.html I run a query in views.py that extracts the data from Posts and sends it in a template/Queryset to index.html, see screen shot below for what it looks like on the screen. Im sure there are a lot more professional ways to do what I'm doing but I'm learning as I go and doing it solo, this has taken me weeks already...... Any advice on … -
I want to filter a queryset according to which button is pressed
i am quite new to django. I have a Task model which has various fields such as date, task name, description, is_completed, level of importance. I what to filter the result according to which button is clicked in a template. I am really stuck! this is my code enter code here 'from django.db import models # Create your models here. class Task(models.Model): IMPORTANT_CHOICES = [("high","high"),("mid","mid"),("low","low")] taskName = models.CharField(max_length = 100) taskDescription = models.CharField(max_length = 100) createdDate = models.DateField(auto_now_add = True) finishDate = models.DateField(blank=True, null=True) last_access = models.DateField(auto_now = True) importance = models.CharField(max_length = 20, choices=IMPORTANT_CHOICES, default="low", blank=True, null=True) daysToFinish = models.IntegerField(blank=True, null=True) completed = models.BooleanField(default = False) def __str__(self): return self.taskName views.py def all_tasks(request, pk): person = Person.objects.get(id=pk) all_t = person.task_set.all() tasks = all_t #calulate day to complete task: date_now = datetime.now() date_now_date = date_now.date() for i in tasks: finish_date = i.finishDate diff = finish_date - date_now_date diff_in_days = diff.days i.daysToFinish = diff_in_days i.save() if request.POST.get('s') == "completed": tasks = tasks.filter(completed = True) elif request.POST.get('s') == "notcompleted": tasks = tasks.filter(completed = False) context ={"tasks":tasks} elif request.POST.get('s') == "high": tasks = tasks.filter(importance = "high") context ={"tasks":tasks} print("high") print(tasks) elif request.POST.get('s') == "mid": tasks = tasks.filter(importance = 'mid') context ={"tasks":tasks} print(tasks) print("mid") … -
How to get 1 list when using django queries with a M2M relationship
This question is very similar(if not the same to): Django query — how to get list of dictionaries with M2M relation? . I am just asking this question to be able to learn if there has been any improvements to djagno that include functionality for this since 11 yrs ago I have a M2M relationship: class RandomObject(models.Model): name = models.CharField(max_length=50,blank=False) description = models.TextField(blank=False) features = models.ManyToManyField('Features',blank=False,db_table='RandomObjectFeatures') class Features(models.Model): LIGHTING = "LIT" SECURE = "SGE" COVERED ="CVP" FEATURE_NAME_CHOICES = [ (LIGHTING,"Lighting"), (SECURE,"Secured Well"), (COVERED,"Covered"), ] feature_name = models.CharField(max_length=3,choices=FEATURE_NAME_CHOICES,blank=False,null=True) def __str__(self): for code, display_name in self.FEATURE_NAME_CHOICES: if self.feature_name == code: return display_name return self.feature_name I have populated the database and now want to query the database to be able to show the features of a randomObject in a template random_objects_data = random_objects.values('name','features__feature_name') Now when I print this I get the following: (I have truncated it as it is long, but it makes the point) {'name': 'object1', 'features__feature_name': 'SGE'}, {'name': 'object1', 'features__feature_name': 'LIT'},{'name': 'object1', 'features__feature_name': 'CVP'} This is unhelpful as objects not in the database are created. I would like to get (or something similar to): {'name': 'object1', 'features__feature_name': ['SGE','LIT','CVP']} This means in the template I can iterate though each feature in features__feature_name. … -
Activate the virtual environment through the command line
I have a problem to Activate the virtual environment through the command line,I did it before and this problem didn`t appear to meenter image description here Microsoft Windows [Version 10.0.19045.3570] (c) Microsoft Corporation. All rights reserved. C:\Users\user>cd projects\django_pm C:\Users\user\projects\django_pm>pipenv shell Launching subshell in virtual environment... Microsoft Windows [Version 10.0.19045.3570] (c) Microsoft Corporation. All rights reserved. (user-KgVmIwbj) C:\Users\user>` I try to create new virtual environments -
Django model relations - "Owning" a related model enforced at the model level
I'm not really sure how to title this question, so forgive my title's ambiguity. I have two models, Customer and Address. Each has typical fields you would infer from their model names. Address is also set as an inline to Customer in admin.py: class Customer(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField(unique=True) phone = models.CharField(max_length=15, blank=True) def __str__(self): return f"{self.first_name} {self.last_name}" class Address(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) street = models.CharField(max_length=100) street_additional = models.CharField(max_length=100, blank=True) city = models.CharField(max_length=50) state = models.CharField(choices=US_STATES) zip = models.CharField(max_length=5) def __str__(self): return self.street I want to add a billing_address and shipping_address to the Customer model to allow a customer to choose one of several saved addresses to be used as those types of addresses accordingly, but I don't want any customer to be able to choose any address. My initial plan was to model the Customer with a foreign key relation back to Address while using limit_choices_to such as: class Customer(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField(unique=True) phone = models.CharField(max_length=15, blank=True) billing_address = models.ForeignKey("Address", on_delete=models.SET_NULL, related_name='billing_address', blank=True, null=True, limit_choices_to={'customer_id':some_callable()) shipping_address = models.ForeignKey("Address", on_delete=models.SET_NULL, related_name='shipping_address', blank=True, null=True, limit_choices_to={'customer_id':some_callable()) def __str__(self): return f"{self.first_name} {self.last_name}" I realized this is not how limit_choices_to is intended … -
empty data in views.py with threads in django app
I have a Django app where I'm initializing generative and document retrieval models. I want to dedicate a thread to the generative model as it uses GPU. Below is my apps.py: import atexit import threading import time import torch import os import pickle from django.apps import AppConfig from django.conf import settings from haystack.nodes import EmbeddingRetriever, PromptNode, PromptTemplate, AnswerParser from transformers import LlamaForCausalLM, LlamaTokenizer, BitsAndBytesConfig from queue import Queue class ChatbotConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'chatbot' generative_queue = Queue(maxsize=1) # Create a queue for generative pipeline requests document_queue = Queue(maxsize=10) device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') session_data = {} generative_data= {} models_initialized = False # Flag to track if models have been initialized gen_models_initialized = False session_lock = threading.Lock() # Lock for session management generative_data_lock = threading.Lock() processing_complete_event = threading.Event() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.models_initialized = False def ready(self): # Register resource cleanup for application exit atexit.register(self.cleanup_resources) # Create a thread for processing generative pipeline requests generative_thread = threading.Thread(target=self.generative_thread) generative_thread.daemon = True generative_thread.start() # Create a thread for concurrent document retrieval document_retrieval_thread = threading.Thread(target=self.document_retrieval_thread) document_retrieval_thread.daemon = True document_retrieval_thread.start() def cleanup_resources(self): self.deallocate_gpu_memory() def deallocate_gpu_memory(self): gc.collect() torch.cuda.empty_cache() def generative_thread(self): while True: session_id, query, pipeline_type, last_activity = self.generative_queue.get() if pipeline_type …