Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to select the fields that i want to show in DRF using a foreign key
I'm working on a small project using Django / Rest Framework, i have two models ( CustomUser and Team ) from django.db import models from users.models import CustomUser class Team(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) This is my serializer : from rest_framework import serializers from apps.teams.models import Team class TeamSerializer(serializers.ModelSerializer): class Meta: model = Team fields = '__all__' # how can i show the CustomUser model fields depth = 1 the result is : [ { "id": 3, "user": { "id": 8, "password": "", "last_login": null, "is_superuser": false, "is_staff": false, "is_active": true, "date_joined": "2021-05-04T21:23:46.513567Z", "first_name": "John", "last_name": "Doe", "username": "testingxe", "email": "ab@test.com", "groups": [], "user_permissions": [] } } ] how can i choose the user, fields that i want to show / i can't show all of them because i have the password ... -
ValueError: Field 'id' expected a number but got 'BlablaRequest'
I am using Django. I am trying to introduce a data in this table: migrations.CreateModel( name='Request', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=50)), ('description', models.CharField(max_length=200)), ('PartToaddToBaseUrl', models.CharField(max_length=200)), ('funcToExtractDataFromJsonName', models.CharField(max_length=100)), ('ParamsOrDataDictStructure', models.JSONField()), ('typeRequests', models.CharField(choices=[('GET', 'Get'), ('POST', 'Post')], max_length=5)), ('headers', models.JSONField(blank=True)), ('RApi', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='requests', to='app.restapi')), ], ), The data is: blablaCarRESTApi=RESTApi(name='BlablaCarRESTApi',BaseUrl='https://public-api.blablacar.com',APIKey='apiKey') I obtain this error: ValueError: Field 'id' expected a number but got 'BlablaRequest'. I don`t know why, I have tried to delete migrations and bd and make migrations and migrate(python manage.py makemigrations -> python manage.py migrate) -
I want to use ForeignKey Serializer
I have these Models Below class Campaign(models.Model): title = models.CharField(max_length=120) img = models.ImageField(upload_to='products/') def __str__(self): return self.title class Product(models.Model): title = models.CharField(max_length=100) data = models.DateField(auto_now_add=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) image = models.ImageField(upload_to="products/") campaign = models.ForeignKey(Campaign, on_delete=models.DO_NOTHING, null=True, blank=True, related_name="products") offer = models.ForeignKey(Offer, on_delete=models.DO_NOTHING, null=True, blank=True) market_price = models.PositiveIntegerField() selling_price = models.PositiveIntegerField() description = models.TextField() def __str__(self): return self.title I want to show campaign_wise products. But i cant find any solution for this. Though i tried reading the docs of DRF Here is my Serializer class CampaignProductsSerializer(serializers.ModelSerializer): products = serializers.PrimaryKeyRelatedField(read_only=True, many=True) class Meta: model = Campaign fields = ['title', 'products'] Whenever i try to run this i get 'Product' object has no attribute 'products' Here is my URL path('campaign_products/<int:id>/', CampaignProducts.as_view()), Here is my View: class CampaignProducts(APIView): def get(self, request, id): campaigns = Campaign.objects.all() query = Product.objects.filter(campaign_id = id) serializer = CampaignProductsSerializer(query, many=True) return Response(serializer.data) -
Django model method to get recursive children in M2M table inheritance
I am using table inheritance in Django and the base ModelA has a ManyToMany recursive field to itself called children. Then I have a ModelB that inherits from ModelA. The issue here is that when I query the children of an instance in ModelB, they are pointed to their equivalents in ModelA. What I would like to accomplish is that an instance of ModelB would return a queryset of children also of ModelB. I can do this using a method _children so it doesn't collide with the field name and have it return the correct model instances. Is there any way that I could instead have modelB.children.all() return the children with the correct model? I know I could use _children() but I would like to call it as an attribute and not a method(). The reason for all of this is that the table inheritance was added later in the game and all the instances will be migrated to these new models soon. Plus, children is broadly used in my project so it would be a hassle to change it all to _children. class ModelA(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4) children = models.ManyToManyField( 'self', related_name='parents', symmetrical=False ) def _children(self): return … -
Writing if else statements in Django's Admin.py
I would like to have my Django admin collapse certain information if the user is new and cannot seem to figure out how to write an if else statement within the admin.py. Here's a general example models.py class User(models.Model): name = models.CharField() is_new = models.BooleanField(default=True) class NewUserInfo(models.Model): join_date = models.CharField() ''' admin.py ''' class NewUserInfoInline(admin.StackedInline): model = NewUserInfo # Here is where I'd like the if else statement I believe # Something like this **if user.is_new is False: classes = ['collapse']** class UserAdmin(admin.ModelAdmin): inlines = [NewUserInfoInline] -
Saving instances of model to ManyToMany field thows AttributeError 'Post' object has no attribute 'save_m2m' but when db is checked, has saved
My Django 3.1.7 blog app has a Post model with a tags field, which is a ManyToManyField to the PostTag model. I want my users to be able to select from some popular tags, or add their own in the new_tags field I created in models.py. new_tags does not exist in the Post model. My idea was to grab the string of "new" tags, split it at the spaces, then check if the tag already existed - creating it if it does exist. That bit of code is working, as new tags are being added to the database. My issue comes when I try to attach these new tags to the instance of Post being updated with the form. I have read loads of SO posts, and have arrived at the view code below. This does save the new tags to the Post instance in the database. However, on submitting the form it still throws an AttributeError: 'Post' object has no attribute 'save_m2m' However if I remove the post.save_m2m() line, the instances are created, but are not attached to my Post instance. views.py class EditPostView(LoginRequiredMixin, UpdateView): """ Renders view to edit an existing post """ model = Post template_name = … -
Overwrite Django "Using" method
I want to use PostgreSQL multi schema in Django. I want to overwrite using method to make my query according schema name. I want like this: objs=MyModel.objects.using('schema_name') objs.filter(...) # extra codes -
Django filter model by method result
I'm looking to filter a model (InventoryItem) by a custom defined method (current_location) that is the filtered queryset of another model (InventoryMovement). I've tried reading the Django documentation, but can't make out exactly how they are using model managers to achieve something like this. One example of what I'm trying to achieve would be something like: InventoryItem.objects.filter(current_warehouse='A') Code is: class InventoryAddress: def __init__(self, warehouse, location, sublocation): self.warehouse = warehouse self.location = location self.sublocation = sublocation class InventoryItem(models.Model): inventory_sku = models.CharField(max_length=20, unique=True, primary_key=True, null=False, blank=False, verbose_name="Inventory SKU") authenticated = models.CharField(max_length=2, choices=yes_no_choices, verbose_name='Authentication Status') # GenericForeignKey for Specific Product content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT, null=True) object_id = models.CharField(max_length=50) content_object = GenericForeignKey('content_type', 'object_id') def movements(self): movements = InventoryMovement.objects.filter(inventory_item=self) return sorted(movements, key=lambda x: x.datetime_entered, reverse=True) def completed_movements(self): movements = InventoryMovement.objects.filter(inventory_item=self, datetime_completed__isnull=False) return sorted(movements, key=lambda x: x.datetime_completed, reverse=True) def current_location(self): movements = self.completed_movements() if movements: last_movement = movements[0] loc = InventoryAddress( warehouse=last_movement.warehouse, location=last_movement.location, sublocation=last_movement.sublocation ) else: loc = InventoryAddress( warehouse='EXT', location=None, sublocation=None, ) return loc def current_warehouse(self): return self.current_location().warehouse class InventoryMovement(models.Model): movement_id = models.CharField(max_length=20, unique=True, blank=False, null=False, verbose_name='Movement ID') warehouse = models.CharField(max_length=40, null=False, blank=False, choices=warehouse_location_choices, verbose_name='Warehouse') location = models.CharField(max_length=40, null=False, blank=False, verbose_name='Target Bin') sublocation = models.CharField(max_length=40, null=False, blank=False, verbose_name='Target Position') inventory_item = models.ForeignKey(InventoryItem, null=True, on_delete=models.PROTECT, verbose_name="Inventory … -
Django parse JSON structure into Q filters
I have an input JSON structure that defines a set of logic that should be applied to a queryset. The json structure looks like this: filters = { "and": { "field__ismissing": "some_text", "other_field__gt": 100, }, "or": { "field__ismissing": "some_text", "other_field__gt": 100, } } which should parse into the following filter. (Q(field__ismissing='some_text') & Q(other_field__gt=100)) | (Q(field__ismissing='some_text') & Q(other_field__gt=100)) Is it possible to parse the JSON as such? The end goal would be to do something like Model.objects.filter(**filter_function(a, b, c)) -
How to increment database row by 1 for every time a link is clicked?
Currently every time I click on a product link on the website the entire database column "views" increases by 1 where as I need it so that just the row increases by 1. The link opens in an external website. The link is opened by clicking on the product image. Any suggestions would be greatly appreciated Models.py class T_shirt(models.Model): Images = models.ImageField() Titles = models.CharField(max_length=250, primary_key=True) Prices = models.CharField(max_length=250) Link = models.CharField(max_length=250) Website = models.CharField(max_length=250) Brand = models.CharField(max_length=250) views = models.IntegerField(default=0) views.py def t_detail(request): if request.method == 'POST': T_shirt.objects.update(views=F('views') + 1) if 'q' in request.GET: q = request.GET['q'] owner_obj = T_shirt.objects.filter(Titles__icontains=q) else: owner_obj = T_shirt.objects.all() p = Paginator(owner_obj, 20) page_num = request.GET.get('page', 1) try: page = p.page(page_num) except EmptyPage: page = p.page(1) return render(request, 'tshirtshtml.html', {"owner_obj": page}) html <ul class="products"> {% for v in owner_obj %} <div class="container"> <form method="POST" type="submit"> <button style="border: none;"> {% csrf_token %} <a href="{{ v.Link }}" rel="noopener noreferrer"> <img src="{{ v.Images }}" width="150" height="150"> </a> </button> </form> <figcaption> {{ v.Titles }} </figcaption> <figcaption> <b>{{ v.Prices }}</b></figcaption> </div> {% endfor %} -
Django perform_update not updating entry
I have a few generic DRF API views: class PageCreateView(generics.CreateAPIView): queryset = Page.objects.all() serializer_class = PageSerializer def perform_create(self, serializer): text = self.request.data.get("text") json = generate_json(text) calculated_level = level_calculate(json) serializer.save(json=json, calculated_level=calculated_level) instance = super().perform_create(serializer) class PageView(generics.RetrieveUpdateDestroyAPIView): queryset = Page.objects.select_related().all() serializer_class = PageSerializer def perform_update(self, serializer): text = self.request.data.get("text") json = generate_json(text) calculated_level = level_calculate(json) serializer.save(json=json, calculated_level=calculated_level) instance = super().perform_update(serializer) The perform_create works perfectly. However the perform_update does not seem to. Should I be doing something differently with the instance or the self object so that it updates the object in question? Generating JSON and calculating the level are both metadata that are dependent on, but which I do not want to include in the POST or PUT request. They need to be re-calculated/re-generated on each save. -
TypeError: 'NoneType' object is not callable in testing django constraints
I want to test this constraint in django who include a condition check birth_date field that must be little than "2011-00-00" but when i run python3 manage.py test i got this error: Traceback (most recent call last): File "C:\Users\dd\Desktop\Dev\django\lemoon\lemoon\account\tests.py", line 45, in test_create_user_under_10 self.assertRaises(IntegrityError,user.save()) File "c:\users\dd\appdata\local\programs\python\python39\lib\unittest\case.py", line 733, in assertRaises return context.handle('assertRaises', args, kwargs) File "c:\users\dd\appdata\local\programs\python\python39\lib\unittest\case.py", line 201, in handle callable_obj(*args, **kwargs) TypeError: 'NoneType' object is not callable models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser from .managers import UserManager import datetime from django.db.models import Q class User(AbstractBaseUser): email = models.EmailField(max_length=120,unique=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) birth_date = models.DateField() is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['birth_date','first_name','last_name'] def __str__(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin class Meta: indexes = [ models.Index(name="email_user_idx",fields=['email']) ] constraints = [ models.CheckConstraint(name="check_birth_date",check=models.Q(birth_date__lte="2011-00-00")) ] tests.py: class Test(TestCase): def test_create_user_under_10(self): User = get_user_model() user = User.objects.test_under_age(email="majid@email.com",first_name="small_majid", last_name="majidi",birth_date="2011-05-22",password="mybestpassword") self.assertRaises(IntegrityError,user.save()) please correct me if i wrote my tests in bad form. -
Django choice not rendering properly using {% if %}
I'm trying to render sort of like a short name for each of the preferred languages in my models.py file, depending on the one the user inputs on the form.py, but it is currently only rendering "EN" across each individual object. How can I fix this? thanks all in advance... Models.py preferred_language_choices = [ ('English', 'English'), ('Español', 'Español'), ('Français', 'Français'), ('Other', 'Other') ] preferred_language = models.CharField(choices=preferred_language_choices, max_length=50, blank=False, null=True) forms.py class GroupForm(ModelForm): class Meta: model = Group exclude = ('admin_approval', 'slug',) page.html {% if group_model.preferred_language == English %} <div class="container"> <p>EN</p> </div> {% elif group_model.preferred_language == Español %} <div class="container"> <p>ES</p> </div> {% elif group_model.preferred_language == Français %} <div class="container"> <p>FR</p> </div> {% endif %} -
How to integrate django, firebase and android for custom authentication?
I am using firebase first time for push notifications. While going through various info I assumed that I may have to use custom authentication to generate unique IDs and send notification to the users using app. Now all processes adding confusion in my mind. My app accepts mobile no and password as login credentials and they are stored in backend our own server configured in django. I am making calls to server apis using retrofit. Now, I want to send a notification after one user completes certain process and it will be informed to another user using notification. I don't know unique firebase device ID of the another user but I know mobile number through backend dB. So how should I send message to server to get another users unique ID and send notification to that user using firebase dynamic dB? Appreciate step by step guidance. Regards, Pd -
Setting up Inlines in Django for a model that has foreign keys to multiple models
I am attempting to set up the admin for a project with inlines that have foreign keys to multiple models. I am using nested-django-admin to set up nested inlines, which is why you will see my admin set up in a slightly different way. user/models.py from django.db import models class Human(models.Model): name = models.CharField(max_length=50) age = models.IntegerField() def __str__(self): return self.name class Parent(Human): job = models.CharField(max_length=50) def __str__(self): return self.name class Child(Human): favorite_toy = models.CharField(max_length=50) def __str__(self): return self.name chore/models.py from django.db import models from user.models import Human, Parent, Child class Chore(models.Model): assigned_by = models.ForeignKey(Parent, on_delete=models.CASCADE) assigned_to = models.ForeignKey(Child, on_delete=models.CASCADE) other_parent = models.ForeignKey(Parent, on_delete=models.CASCADE) description = models.CharField(max_length=50) def __str__(self): return self.description user/admin.py from django.contrib import admin from .models import Human, Parent, Child from chore.admin import ChoreInline import nested_admin class ParentAdmin(nested_admin.NestedModelAdmin): inlines = [ChoreInline] class ChildAdmin(nested_admin.NestedModelAdmin): inlines = [ChoreInline] chore/admin.py from django.contrib import admin from .models import Chore import nested_admin class ChoreInline(nested_admin.NestedStackedInline): model = Chore fk_name = 'assigned_by' class ChoreAdmin(nested_admin.NestedModelAdmin): pass admin.site.register(Chore, ChoreAdmin) I expect this to run smoothly so that the user has the ability to see the chores associated with the child in their admin change and the same for the parents. What I get instead is this error. … -
Django filter traversing multiple foreign keys and generic foreign keys
I've tried a ton of different ways, but I've hit a brick wall with the logic and hoping someone on here may be able to come up with the easily. I have a few different connected relevant models (I've tried to strip out all irrelevant fields and methods for ease of viewing): class InventoryAddress: def __init__(self, warehouse, location, sublocation): self.warehouse = warehouse self.location = location self.sublocation = sublocation # Product Models class ProductMaster(models.Model): internal_id = models.CharField(max_length=20, unique=True, primary_key=True, null=False, blank=False, verbose_name="Internal ID") class ShoeAttributes(models.Model): style_id = models.CharField(max_length=20, unique=True, primary_key=True, null=False, blank=False, verbose_name="Style ID") product_master = models.OneToOneField(ProductMaster, related_name='ShoeAttributes', on_delete=models.CASCADE) brand = models.CharField(max_length=30, choices=shoe_brand_choices, default=None, blank=True, null=True, verbose_name="Brand") class Shoe(models.Model): sku = models.CharField(max_length=20, unique=True, primary_key=True, null=False, blank=False, verbose_name="SKU") product_master = models.ForeignKey(ProductMaster, blank=False, null=False, on_delete=models.CASCADE, verbose_name="Brands") size = models.CharField(max_length=20, null=False, blank=False, verbose_name="Size") condition = models.CharField(max_length=25, choices=shoe_condition_choices, blank=False, null=False, verbose_name='Condition') class InventoryItem(models.Model): inventory_sku = models.CharField(max_length=20, unique=True, primary_key=True, null=False, blank=False, verbose_name="Inventory SKU") authenticated = models.CharField(max_length=2, choices=yes_no_choices, verbose_name='Authentication Status') # GenericForeignKey for Specific Product content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT, null=True) object_id = models.CharField(max_length=50) content_object = GenericForeignKey('content_type', 'object_id') def movements(self): movements = InventoryMovement.objects.filter(inventory_item=self) return sorted(movements, key=lambda x: x.datetime_entered, reverse=True) def completed_movements(self): movements = InventoryMovement.objects.filter(inventory_item=self, datetime_completed__isnull=False) return sorted(movements, key=lambda x: x.datetime_completed, reverse=True) def current_location(self): movements = self.completed_movements() if movements: … -
Django & React CORS error - will allow GET requests but not POST
I have created an app using django for the backend and react for the frontend (structured within a django app). Hence there are CORS requests. I have added installed CORS for django and added the following to the settings: CORS_ALLOWED_ORIGINS = [ "http://localhost:8000", "http://127.0.0.1:8000", ] However, when I can make REST requests from react using the prefix "http://localhost:8000", I get the error 403 forbidden. For instance, it will let me login but when logging out I get a 403 forbidden error. I can make GET requests fine and when I tested the API using an external tool like Postman there are no issues. Please advise. -
How to get specific id from for loop in django template?
I'm working with django and javascript, I'm trying to follow and unfollow multiple users without refreshing the page. therefore i'm using ajax. The problem which i'm facing right now is that the first follower is getting follow and unfollow no matter if i click on that user or on other user.. its an obvious behavior because i couldn't understand how to get specific id of user from the for loop so that i can use that user in a js function. {% if follower.user in request.user.userprofile.follower.all %} <span><a class="btn btn-success" id="follow-button{{follow.id}}" toggle="{{follower}}" type="submit">{% csrf_token %}UnFollow</a></span> {% else %} <span><a class="btn btn-warning" id="follow-button{{follow.id}}" toggle="{{follower}}" type="submit">{% csrf_token %}Follow</a></span> {% endif %} </div><!--/ followers-body --> {% endfor %} <script> $(document).on('click','a[id^=follow-button]', function (e) { var user = $('#follow-button').attr('toggle'); //this user is coming the first use of looping object..no matter if i click on the 2nd or 3rd user of the loop. console.log(user,'im im im tested'); e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "profiles:toggle" %}', data: { user_toggle: user, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), action: 'POST', }, success: function (json) { result = json['result'] console.log(result,"maii mai maima maima a") if (result) { document.getElementById("is_following").innerHTML = '<a class="btn btn-success" id="follow-button" toggle="{{user.userprofile}}" type="submit">{% csrf_token %}UnFollow</a>' } else document.getElementById("is_following").innerHTML = '<a class="btn … -
How to get all field of a model for connected with Foreign Key?
I have two model like given in bellow; class tagReferenceLocationInfo (models.Model): tag = models.ForeignKey(tag,on_delete=models.CASCADE) ref = models.ForeignKey(mapReferencePoints, on_delete=models.CASCADE, related_name="refPoint") map = models.ForeignKey(map, on_delete=models.CASCADE, related_name="tag_ref_map") corX = models.IntegerField() corY = models.IntegerField() date = models.DateTimeField(auto_now=True) def __int__(self): return self.tag class mapReferencePoints (models.Model): referenceName = models.CharField(max_length=30) corX = models.IntegerField() corY = models.IntegerField() def __str__(self): return self.referenceName I want to use this queryset result as a json; queryset = tagReferenceLocationInfo.objects.select_related('ref').filter(tag_id__in=id_list, date__gte=startDate, date__lte=queryset) I use; data = serialize("json", queryset) I got only mapReferencePoints ids but ı want to get also "referenceName" field. How can serialize this queryset result to get "referenceName" filed of mapReferencePoints model. -
Why can't I upload a image by Django?
I'm going to make a book bulletin board using the django and put a picture of the book in it and post a post. But the text is going up, but the picture isn't going up. i add MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' in settings.py model.py class Book(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) title = models.TextField() author = models.TextField(max_length=50) content = models.TextField() image = models.ImageField(upload_to='image/',blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) like_user = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='like_book') def __str__(self): return self.title form.py class Book_Form(forms.ModelForm): class Meta: model = Book fields = ('title','author', 'content','image') widgets = { 'title': forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'title' } ), 'author': forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'author' } ), 'content': forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'content', } ), } create.html {% block content %} <form action="" method = 'POST' enctype="multipart/form-data" style= 'margin:40px; height:50px; width:80%;'> {% csrf_token %} {{form.as_p}} </div> <div class = "d-grid gap-2 col-4 mx-auto" style= 'margin:20px; height:50px;'> <input type="submit", class="btn btn-primary" value='제출'> </div> </form> {% endblock content %} view.py @login_required def create(request): if request.method == 'POST': book = Book_Form(request.POST, request.FILES) if book.is_valid(): book = book.save(commit=False) book.user = request.user book.save() return redirect('books:detail', book.pk) else: form = Book_Form() context = { 'form': form, } return render(request,'books/create.html',context) If I try … -
How to serialize parent and child model objects properly?
Here I am trying to return the children serializer data like this but this is not working. How to solve this issue ? model class Type(models.Model): name = models.CharField(max_length=200, unique=True) parent = models.ForeignKey( 'self', on_delete=models.PROTECT, null=True, blank=True) serializer class ListTypeSerializer(serializers.ModelSerializer): children = serializers.SerializerMethodField() class Meta: model = Menu fields = ['name', 'children'] # for some reason I can not do `return obj.type_set.values('name')` # since I have so many customized variable names. # I am displaying only name here in question. def get_children(self, obj): return ListTypeSerializer(obj.type_set.all(), many=True, context={'request': self.context['request']}).data Error: raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type Type is not JSON serializable -
Django doesn't submit my form if I using individual fields
I need to render my Django form fields individually because of design purposes. It looks good but if I hit submit It doesn't do anything just a short blink. If I render the whole {{ form }} it works well. I don't have any ideas about what am I doing wrong. Could you guys please help me? html <form method = "POST"> <div class="container w-75 bg-light rounded-3 pt-3"> <div class="form-group"> {% csrf_token %} {% comment %} {{ form }} {% endcomment %} <div class="row"> <div class="col-4 border-right border-primary p-3"> <h6 class="text-primary">1. text.</h6> {{ form.att_v001 }}<br> </div> <div class="col-4 border-primary pt-3 pl-4"> <h6 class="text-primary">2.text.</h6> {{ form.att_v002 }}<br> </div> <div class="col-4 border-left border-primary pt-3 pl-4"> <h6 class="text-primary">3. text.</h6> {{ form.att_v003 }}<br> </div> <div class="col-4 border-left border-primary pt-3 pl-4"> <h6 class="text-primary">4. text.</h6> {{ form.att_v004 }}<br> </div> <div class="col-4 border-left border-primary pt-3 pl-4"> <h6 class="text-primary">5. text.</h6> {{ form.att_v005 }}<br> </div> <div class="col-4 border-left border-primary pt-3 pl-4"> <h6 class="text-primary">6. text.</h6> {{ form.att_v006 }}<br> </div> </div> <button class="btn btn-large btn-primary" type="submit">Mentés</button> models.py class Attitud(models.Model): def __str__(self): return str(self.user_name) class question(models.IntegerChoices): Nem_jellemző = 0 Néha_jellemző = 1 Nagyon_jellemző = 2 user_name = models.ForeignKey(User, on_delete=models.CASCADE, default=1) att_v001 = models.IntegerField(default=0, null=True, blank=False, choices=question.choices) att_v002 = models.IntegerField(default=0, null=True, blank=False, choices=question.choices) … -
error in django rest api and react in production
i have built rest api with django and deploy it to server , the problem is when i call the api from react in my local machine it works but when i run npm run build and deploy react and django together , i got alot of errors in api like error connection refused and 403 note that i have disabled all security and installed django-cors-headers and i set origin to allow all . so whats the problem now . thank you in advanced -
Refactoring Django model setup advice
As a learning exercise I am creating a way for generate Student Report Cards. I was able to create the desired outcome in the current version by hardcoding each Standard as its own field in the model but there was a lot of repetition and was hoping to improve it. Sample of current models.py with lots of repetition Sample of current forms.py with lots of repetition Current Front-End How can I re-create the formset above with less code? Here's what I'm trying so far but I've come across some issues I can't find a solution to. Any advice would be appreciated. #models.py class ReportCard(models.Model): PROGRESS_INDICATOR = [ ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('NA', 'NA') ] student_perm_number = models.CharField(max_length=51, default='123456789') reporting_year = models.CharField(max_length=10, default='2020-2021') # Grade Received each Trimester standard = models.ForeignKey('reportforms.Standard', on_delete=models.CASCADE, null=True) t1 = models.CharField(choices=PROGRESS_INDICATOR, max_length=3, blank=True, null=True) t2 = models.CharField(choices=PROGRESS_INDICATOR, max_length=3, blank=True, null=True) t3 = models.CharField(choices=PROGRESS_INDICATOR, max_length=3, blank=True, null=True) # Math, Language Arts etc... class Domain(models.Model): name = models.CharField(max_length=100, blank=False) grade = models.ForeignKey(Grade, on_delete=models.CASCADE, blank=True, null=True) # Shapes, Geometry etc... class Standard(models.Model): domain = models.ForeignKey('reportforms.Domain', on_delete=models.CASCADE, blank=True, null=True) name = models.CharField(max_length=100, blank=False, null=True) The form is pretty simple #forms.py class ReportCardForm(ReportCardForm): class Meta: model = … -
How to restrict Endpoint
I am creating a multi-vendor marketplace with django. I have an endpoint for retrieving, updating and deleting a product that belongs to a store like this: localhost:8000/name-of-store/int:product_id. Note: "name-of-code" is the slug of the store. This is the code below: class EditItemAPIView(generics.RetrieveUpdateDestroyAPIView): serializer_class = ItemSerializer permission_classes = (IsAuthenticated,) def get_queryset(self): item = Item.objects.filter(pk=self.kwargs['pk']) print(item) return item With this code, if I append the id of a product that does not belong to a particular store in the url above i.e I do localhost:8000/name-of-store/5, where 5 is the id of a product that belongs to another store, it gets the product. How do I implement some kind of restriction such that if I try append the id of a product not belonging to the shop whose slug is in the url I get a 401 message? Any help will be greatly appreciated.