Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to retrieve single object from many to many relationship using elasticsearch in django
I am trying to use elasticsearch for search functionality in my django site. Here is my code. models.py: class Category(MPTTModel): name = models.CharField() class Product(models.Model): name = models.CharField() description = models.TextField() category = TreeManyToManyField(Category) class ProductImage(models.Model): product = models.ForeignKey( Product, on_delete=models.PROTECT, related_name= "product_pictures", ) image = models.ImageField(...) class ProductInventory(models.Model): product = models.ForeignKey(Product, related_name="product", on_delete=models.PROTECT) product_images = models.ManyToManyField( ProductImage, related_name = "product_inventory_images", through="MediaProductImage") is_default_varient = models.BooleanField(default=False) class MediaProductImage(models.Model): product_inventory = models.ForeignKey( ProductInventory, on_delete=models.PROTECT, related_name="media_product_inventory", ) image = models.ForeignKey( ProductImage, on_delete=models.PROTECT, related_name="media_product_image", ) is_feature = models.BooleanField( default=False, ) documents.py: @registry.register_document class ProductInventoryDocument(Document): product = fields.ObjectField( properties={ "name": fields.TextField(), "description": fields.TextField() } ) category = fields.ObjectField( properties={ "name": fields.TextField() } ) product_images = fields.NestedField( properties={ 'image': fields.FileField(), }) media_product_inventory = fields.ObjectField( properties={ 'is_feature': fields.BooleanField(), }) class Index: # Name of the Elasticsearch index name = 'productinventory' class Django: model = ProductInventory # The model associated with this Document # The fields of the model you want to be indexed in Elasticsearch fields = [ 'id', 'is_default_varient', ] I want to search product from ProductInventory table matching with by matching name by matching description by matching category # if possible filter by is_deafult_varient=True # for getting default ProductInventory object filter by media_product_inventory__is_feature=True # for … -
I have change custom user model in middle of project so admin page is giving me this error But my Api is working fine only admin page has problem
enter image description herei have change my custom user model in middle of the project so iam getting such error inside table which is having foreign relationship Template error: In template C:\Users\User\.virtualenvs\tagon-lucky_wheel_api-OldNbhB5\lib\site-packages\django\contrib\admin\templates\admin\includes\fieldset.html, error at line 19 __str__ returned non-string (type NoneType) 9 : {% for field in line %} 10 : <div{% if not line.fields|length_is:'1' %} class="fieldBox{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}{% if field.field.is_hidden %} hidden{% endif %}"{% elif field.is_checkbox %} class="checkbox-row"{% endif %}> 11 : {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %} 12 : {% if field.is_checkbox %} 13 : {{ field.field }}{{ field.label_tag }} 14 : {% else %} 15 : {{ field.label_tag }} 16 : {% if field.is_readonly %} 17 : <div class="readonly">{{ field.contents }}</div> 18 : {% else %} 19 : {{ field.field }} 20 : {% endif %} 21 : {% endif %} 22 : {% if field.field.help_text %} 23 : <div class="help">{{ field.field.help_text|safe }}</div> 24 : {% endif %} 25 : </div> 26 : {% endfor %} 27 : </div> 28 : {% endfor %} 29 : </fieldset> -
Django dynamic nested model forms
Suppose I have the following models, where there is a 1:many relationship from Teacher to Course, and from Course to Student: class Teacher(Model): name = CharField(max_length=64) degree = CharField(max_length=64) class Course(Model): title = CharField(max_length=64) level = CharField(max_length=64) teacher = ForeignKey(Teacher, on_delete=CASCADE) class Student(Model): name = CharField(max_length=64) year = CharField(max_length=64) course = ForeignKey(Course, on_delete=CASCADE) If I want to have a "register teacher" page, where a user can input the details of a Teacher, and also be able to add any number of Courses with their corresponding details, and to each Course add any number of Students, how could this be done? I am aware of ModelForms, which would make constructing a basic form for a single instance of a model rather trivial, but how can I create a form or forms that essentially nests the models within each other, and allows for a dynamic number of Course and Student? For example, within the Teacher form, there is an "add Course" button, that adds another Course form under that Teacher, such that any details entered into it populate a Course that belongs to that Teacher, and then for each Course form, there is an "add Student" button that adds a Student form … -
How do I check if such a field exists for a product (product model)?
I'm a beginner in django....... I have such a model class Product(models.Model): title = models.CharField(max_length=50) description = models.TextField(blank=True) owner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) slug = models.SlugField(unique=True) # "штрих код" price = models.DecimalField(max_digits=8, decimal_places=2, ) creation_date = models.DateTimeField(auto_now_add=True) last_update_time = models.DateTimeField(auto_now=True) image1 = models.ImageField(blank=True) mark = models.CharField(max_length=50, blank=True) class Review(models.Model): review = models.TextField(max_length=500) author = models.ForeignKey(User, on_delete=models.CASCADE) product_connected = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="reviews") creation_date = models.DateTimeField(auto_now_add=True) last_update_time = models.DateTimeField(auto_now=True) rating = models.IntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(5)]) and here is such a views class ProductDetailView(LoginRequiredMixin, DetailView): model = Product template_name = "product.html" context_object_name = "product" @staticmethod def round_custom(num, step=0.5): return round(num / step) * step def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) data["pictures_list"] = Photo.objects.filter(product_connected=self.get_object()) data["comments"] = Review.objects.filter(product_connected=self.get_object()) if self.request.user.is_authenticated: data['comment_form'] = CommentForm(instance=self.request.user) average_rt=Review.objects.filter( product_connected=self.get_object()).aggregate(Avg('rating')) avr_intermediate = str(average_rt.get("rating__avg")).replace(",", ".") data["average_rating"] = self.round_custom(float(avr_intermediate)) return data This whole scheme with average is needed to display a rating on the site (rating), the problem is that a product is created in the product model, and the review class is created only when the user writes a review. So, how do I check that there is a Review for this Product, and if there is, then return return data["average_rating"] through my scheme, and if not, then just return 0 in data … -
Factory Boy FuzzySubFactory available?
I am wondering if there is something like FuzzyChoice for Objects. Background is that I have a base factory and 3 different implementations. Another Factory which uses these factories should randomly choose one of the three implementations. So I did not found that specify FuzzySubFactory within the docs but is there another way to achieve this? Thanks and regards Matt -
How to get the output parameter as the response in python
I'm trying to get the list of user's based whose name starts based on the typing the name from the SQL database. In SQL there is an output parameter in which I want to return as API response views.py: @api_view(['POST']) def FetchSuggestionAuditAgent(request): if request.method =='POST': agents = request.data.get('Agents') sql = """\ DECLARE @response NVARCHAR; EXEC dbo.sp_FetchSuggestionAuditAgent @agents = %s, @response = @response OUTPUT; SELECT @response AS out_value; """ params = (2,) cursor = connection.cursor() cursor.execute(sql, params) result_set = cursor.fetchall() print(result_set) for row in result_set: agents = row[0] return Response({'Agents':agents}) SQL SP: ALTER PROCEDURE [dbo].[sp_FetchSuggestionAuditAgent] -- 'apolonia ','' @agents nvarchar(max),@response nvarchar(1000) OUTPUT AS BEGIN set @agents = LTRIM(RTRIM(@agents)) select top 1 @response = FullName from tblusers where FullName like '%'+@agents+'%' and isactive =1 and IsDeleted = 0 order by FullName desc END -
How can I solve the Not found problem when getting from pytest-django through pk?
I have a problem with django-pytest I'm using, djnago-rest-framework There is a problem testing the details. As shown in the code below, I entered the same details, detail1, detail2, and detail3 codes. However, only detail1 succeeds and detail2, detail3 indicates that '/api/v1/stats/1/' could not be found. It also occurs when implementing delete. I am curious about the cause and solution of this error. enter image description here // tests/test_apis.py import json from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase from stats.models import Stats class StatsApiTests(APITestCase): def setUp(self): Stats.objects.get_or_create(blockshots=1, memo='test1') Stats.objects.get_or_create(blockshots=2, memo='test2') self.create_read_url = reverse('api:stats:stats-list') self.read_update_delete_url = reverse('api:stats:stats-detail', kwargs={'pk': '1'}) def test_detail1(self): response = self.client.get(self.read_update_delete_url) data = json.loads(response.content) content = { 'blockshots': 1, 'memo': 'test1', } self.assertEqual(data, content) def test_detail2(self): response = self.client.get(self.read_update_delete_url) data = json.loads(response.content) content = { 'blockshots': 1, 'memo': 'test1', } self.assertEqual(data, content) def test_detail3(self): response = self.client.get(self.read_update_delete_url) data = json.loads(response.content) content = { 'blockshots': 1, 'memo': 'test1', } self.assertEqual(data, content) def test_list(self): response = self.client.get(self.create_read_url) self.assertContains(response, 'test1') self.assertContains(response, 'test2') -
how to email check on unique in django (@ya.ru == @yandex.ru)
how to check email address is unique, if example@yandex.ru and example@ya.ru it`s identically equal. i use [django-registration 3.2][1], to check unique email in urls.py add from django_registration.forms import RegistrationFormUniqueEmail from django_registration.backends.activation.views import RegistrationView ... urlpatterns = [ ... path('accounts/register/', RegistrationView.as_view(form_class=RegistrationFormUniqueEmail),name='django_registration_register',), ... ] all good for to check. I don't understand how to check it. help please. [1]: https://django-registration.readthedocs.io -
Constructing Dynamic Tables in Django with editable cells and nested categories
I am trying to get an excel-like setup (but more dynamic and customisable) using Django. On the right-hand side there is a filter list. The rows list is fully expanded. I want to be able to dynamically add or remove columns/rows and to be able to enter values into the cells. The cells should be either dropdowns or text cells. So for example, I could be able to delete Column Category A which would delete the Column and all sub-columns. Similarly, I could "Add Category" to the rows creating Row Category C and then add sub-categories. Of course, all names should be editable. Once that is all complete, I want to be able to save the final table into a database for a particular user. I am struggling to find any way to implement this. Are there any sub-libraries of Django which can build this? -
How to filter for Records in the admin backend
class OrderSVO(models.Model): product = models.ForeignKey(Products, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) seller = models.CharField(max_length=100, default='', blank=True) class OrderSVOAdmin(admin.ModelAdmin): def queryset(self, request): """Limit Pages to those that belong to the request's user.""" qs = super(OrderSVOAdmin, self).queryset(request) if request.user.is_superuser: # It is mine, all mine. Just return everything. return qs # Now we just add an extra filter on the queryset and # we're done. Assumption: Page.owner is a foreignkey # to a User. return qs.filter(seller='A Seller Name') admin.site.register(OrderSVO,OrderSVOAdmin) I want to filter records in the backend for a specific seller -
Calling a Django Api in Vue that has date parameter in between
How do I pass this Api call in Vue2 and calling it http://127.0.0.1:8000/api/2022-03-18 10:55/2022-04-18 10:55/displaydate parameter -
I keep getting this error in my django project and I have literally tried everything I could find on stackoverflow but nothing works
Error: Uncaught TypeError: $(...).autocomplete is not a function included in base.html: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css"> autocomplete code reference: https://www.geeksforgeeks.org/implement-search-autocomplete-for-input-fields-in-django/ -
pyodbc.ProgrammingError: ('42S22', "[42S22] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name 'xyzxyz'
I have one Django app which was working fine but after changing the data type of one column in DB from varchar to NVarchar I am getting the above error. Can anyone please guide me what am I missing? Do I need to do migration? -
How to display model inheritance in Pyhon Django?
I have this code : from django.db import models from category.models import Category # Create your models here. class Item(models.Model): item_name = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200,unique=True) description = models.TextField(max_length=500, blank=True) price = models.IntegerField() images = models.ImageField(upload_to='photos/products') stock = models.IntegerField() is_available = models.BooleanField(default = True) category = models.ForeignKey(Category,on_delete = models.CASCADE) created_date = models.DateTimeField(auto_now=True) modified_date= models.DateTimeField(auto_now=True) def __str__(self): return self.item_name class Meta: abstract = true class BookItem(Item): author = models.CharField(max_length=200) class LaptopItem(Item): cpu = models.CharField(max_length=200) ram = models.CharField(max_length=200) I want to display all BookItem and LaptopItem only by using model Item . Can someone show m3 how to do that ? -
Django Rest Framework - common nested serializer for multiple models with the same base class
Assuming that we have the following models: from django.db import models class BaseModel(models.Model): field_a = models.TextField() field_b = models.IntegerField() class Meta: abstract = True class ModelA(BaseModel): some_relation = models.ForeignKey( "app.RelatedModelA", related_name="model_a_set", ... ) class ModelB(BaseModel): different_relation = models.ForeignKey( "app.RelatedModelB", related_name="model_b_set", ... ) class RelatedModelA(models.Model): pass class RelatedModelB(models.Model): pass I would like to be able to define serializers in the following way: from rest_framework import serializers class RelatedModelASerializer(serializers.ModelSerializer): model_a_set = BaseModelSerializer(many=True) class Meta: model = RelatedModelA fields = ("id", "model_a_set") class RelatedModelBSerializer(serializers.ModelSerializer): model_b_set = BaseModelSerializer(many=True) class Meta: model = RelatedModelB fields = ("id", "model_b_set") The question is - how to define BaseModelSerializer? I found a solution that takes into account overriding to_representation, although it requires writing serializers for each type separately (ModelASerializer and ModelBSerializer), so it would look like this: class BaseModelSerializer(serializers.ModelSerializer): def to_representation(self, obj): if isinstance(obj, ModelA): return ModelASerializer(obj, context=self.context).to_representation(obj) elif isinstance(obj, ModelB): return ModelBSerializer(obj, context=self.context).to_representation(obj) raise NotImplementedError class Meta: model = BaseModel fields = ("id", "field_a", "field_b") The ideal solution for me would be something like that, without defining serializers for ModelA and ModelB: class BaseModelSerializer(serializers.ModelSerializer): class Meta: model = BaseModel fields = ("id", "field_a", "field_b") but unfortunately it won't work that way, because an abstract model cannot be … -
How to create a django model record using get_or_create and select_related
I have a class like below: class GroupProduct(models.Model): product = models.ForeignKey( 'myapp.Products' related_name='myapp_group_product') @classmethod def create_group_product(cls, p_id, product_id): cls.objects.get_or_create(id=p_id, defaults=dict(product=product_id).select_related('product') So I expect it creates a record in the table with the following params, however it doesn't. GP = GroupProduct() GP.create_group_product(3, 225) It says it product must be a myapp.Products instance. Is there any way to use select_related in this way rather than doing a seprate query and hit the database? -
Mapboxgl breaks when I change django language in settings
Basically my code works well when language in django settings.py is set to "en-us" But when I try to change it I get: Uncaught Error: Invalid LngLat object: (NaN, NaN) at new Ha (lng_lat.js:39:19) at Function.convert (lng_lat.js:142:20) at Rr.setLngLat (marker.js:337:31) at dodaj_marker ((indeks):282:37) at (indeks):296:9 I'm changing lang because I need to get months in different language, but how does it affect mapbox? Is there any mapbox language variable I have to edit in order to get it working ? -
win10 netstat -ano|findstr 8000 return empty and error ’WinError 10013” when python manage.py runserver 8000
receive Error: [WinError 10013] when i use 'python manage.py runserver 8000'. then netstat -ano|findstr 8000, but nothing is return,only empty list. I use win10, what missing? thanks. But run python manage.py runserver 9000 is ok? what problem with port 8000? why netstat -ano|findstr 8000 return empty? -
django.db.utils.OperationalError: no such table: main.authentication_user
I am getting the error mentioned in the title during my try to save some information to a postgres database. My models.py script is the following: from django.db import models from django.contrib.auth import get_user_model CustomUser = get_user_model() class Event(models.Model): user_id_event = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) dr_notice_period = models.IntegerField(blank=True, null=True) dr_duration = models.IntegerField(blank=True, null=True) dr_request = models.FloatField(blank=True, null=True) CustomeUser is from the models.py of a custom authentication application: from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): demo = models.CharField(max_length=40) My serializers.py script is the following: from rest_framework import serializers from vpp_optimization.models import Event class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = ('__all__') And my views.py where I am trying to add a specific event to the database is the following: from rest_framework.response import Response from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated from rest_framework import status from vpp_optimization.serializers import EventSerializer @api_view(['POST']) @permission_classes([IsAuthenticated,]) def event(request): serializer = EventSerializer(data=request.data) if serializer.is_valid(): serializer.save(user_id_event=request.user) return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) The full error is the following: Traceback (most recent call last): File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 413, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: main.authentication_user … -
Django - Vue - how to generate view for tag, or?
Im use vue and django with rest framework. In django models.py i have model field "tahs" this is charfield with tags separated by comma. exaple : django,forest,native I want to generate view for each tag example "django". OR try to search in filed tahs and return objects contains this tag[ex.django] this is my views.py class TagsResultsViewSet(viewsets.ModelViewSet): serializer_class = TagResultsViewSetSerializer queryset = CustomUserPass.objects.all() lookup_field = 'tahs' def get_queryset(self, *args, **kwargs): context = super().get_queryset(*args, **kwargs) tag = self.kwargs['tahs'] print('this is tags:', tag) context = self.queryset.filter(tahs__icontains=tag) print(context) return context serializer.py class TagResultsViewSetSerializer(serializers.ModelSerializer): tahs = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = CustomUserPass fields = '__all__' urls.py router = DefaultRouter() ... router.register('tags', TagsPassViewSet, basename='tags') router.register('tag', TagsResultsViewSet, basename='tag') urlpatterns = [ path('', include(router.urls)), ] vue file: TagView.vue <template> <div class="about"> <h1>You looking: {{tag}}</h1> <div v-for="result in results" :key="result.id"> <div>{{result.username}}</div> </div> </div> </template> <script> import axios from 'axios' export default { name: 'TagView', data() { return { results: [], errors: [], } }, props: { tag: { type: String, required: true, }, }, mounted() { this.getTagsResults() }, methods: { async getTagsResults() { this.$store.commit('setIsLoading', true) axios .get(`/api/v1/tag/${this.tag}`) .then(response => { this.results = response.data console.log(this.results) }) .catch(error => { console.log(error) }) this.$store.commit('setIsLoading', false) }, } } </script> actually when … -
How to fill in programmatically Django admin built-in autocomplete?
I would like to use JS in the Django admin to fill in programmatically a field that uses the built-in autocomplete option (NOT autocomplete-light). Let's say the field is called myfavfield. I can retrieve it with JS as follows $("#id_myfavfield"). If it is already filled in with some values, I can retrieve them with $("#id_myfavfield").val();, which, for example, returns ['1', '4'], I can also clear myfavfield with $("#id_myfavfield").empty();. However, I can't fill it in, for example, by running $("#id_myfavfield").val(['2', '4', '5']); or any other way that I have tried. Does anybody know how one can achieve that? -
Django - display image from database in edit form
I recorded a form that also contained an image. I would like that later in edit form to be able to visually see the previously uploaded image before changing it. I tried to display it in edit form via <img src = "{{curs.poster_curs.url}}" alt = "alternate text"> but in inspect it shows src = "unknown". How can I display the image already uploaded in edit form? I ask for a solution in this regard. Thank you -
Post a dcitionaries and lists along with a file using python resquests
I built an endpoint using Django-rest-framework which expects a file and some other information, including some dictionaries and lists. If I make the request using the browsable API from drf, none of the data is truncated and I also receive the file. However if I make a POST request through Python-requests library it doesn't work and the data received on the server side is received truncated as HTTP form-encoding is not capable of representing nested data structures. Does anyone know how can I reproduce the same behavior as the browsable API in the request through python requests library and avoid the truncation? Any help is greatly appreciated. -
django-tenants: redirecting to tenant url after login raises "NoReverseMatch: 'demo.localhost' is not a registered namespace"
I don't seem to find a way to solve an error happening at the user authentication. User needs to login at the public website level let's say localhost/login and when he/she is authenticated, I need the user to be redirected in the corresponding sub domain, for example demo.localhost. This is not working for me so far, even after checking some posts about the subject. Here is the views.py in customers.views where user log in: def login_view(request): if request.method == 'POST': form = AuthenticationForm(request,data=request.POST) print("form login view") if form.is_valid(): print("checkpoint") username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) user = form.get_user() schema_name = user.schema_name print(user) if user is not None: login(request, user) url = reverse(schema_name + '.localhost:8000/mydashboard/') print("url") return HttpResponseRedirect(url) else: print("not working") form = AuthenticationForm() context = { 'form': form, } return render(request, 'login.html', context) here is what urls in the core folder: urlpatterns = [ path('admin/', admin.site.urls), path('django_plotly_dash/', include('django_plotly_dash.urls')), path('mydashboard/', include('mydashboard.urls',namespace="mydashboard")), ] and I have added app_name = 'mydashboard' in mydashboard.urls Here is the traceback of the error I keep getting: Internal Server Error: /registration/loginUser Traceback (most recent call last): File "/Users/pierre/opt/anaconda3/lib/python3.9/site-packages/django/urls/base.py", line 71, in reverse extra, resolver = resolver.namespace_dict[ns] KeyError: 'demo.localhost' During handling of the above … -
Django ORM count or get precentage report
I have three models named Category, Account, and AccountCategory. I need to be able to generate a report wherein I can show the number of which each account was categorized. (e.g let's say I have 10 accounts, then I have three categories (A, B, C) I need to be able to show a piechart) Account has a many-to-many relationship with Category and AccountCategory is the junction table. Ideally, I need to have a result of Name Slug Percentage Num of Accounts A a 40% 4 B b 10% 1 C c 50% 5 I was able to get the raw Query but I still need to get the total number of accounts so I can get the percentage I'm struggling with how to do this on ORM. Basically, I did query the categories, joined account categories, and did a distinct on the account so it won't return the duplicates and then just total the result. For the ORM I think I need to filter the account categories to only return the latest account category per account and then total it but I can't seem to write the exact query using ORM I tried using the Subquery and Prefetch but no …