Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When I do "makemigrations" I get do "makemigrations"
I removed all migration files from my django project and now when i want to re-create i get this ./manage.py makemigrations INFO: AXES: BEGIN LOG :: [axes.apps] 2022-09-15 16:51:59,923 - /home/mixnosha/work_MVD/MVD_LTP/MVD_LTP-ltp/venv/lib/python3.10/site- packages/axes/apps.py:33 INFO: AXES: Using django-axes version 5.31.0 :: [axes.apps] 2022-09-15 16:51:59,926 - /home/mixnosha/work_MVD/MVD_LTP/MVD_LTP-ltp/venv/lib/python3.10/site- packages/axes/apps.py:34 INFO: AXES: blocking by IP only. :: [axes.apps] 2022-09-15 16:51:59,927 - /home/mixnosha/work_MVD/MVD_LTP/MVD_LTP-ltp/venv/lib/python3.10/site- packages/axes/apps.py:46 No changes detected ./manage.py migrate Operations to perform: Apply all migrations: admin, auth, axes, base_information, contenttypes, django_celery_beat, sessions Running migrations: No migrations to apply. Your models in app(s): 'admin', 'auth', 'axes', 'contenttypes', 'sessions' have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. Recommend something -
Django admin prefetch related on property
I have models Merchant and PhoneNumber. PhoneNumber has a foreign key to Merchant, and Merchant has property business_phone_number which fetches the first phone number in the set of the phone numbers. In Django admin, for the Merchant model, I have business_phone_number in list_display. Although I've put prefetch_related(phonenumber_set), it still queries PhoneNumber 100 times. What am I doing wrong? Here's the simplified code: class PhoneNumber(models.Model): ... merchant = models.ForeignKey("merchant.Merchant", on_delete=models.SET_NULL, null=True, blank=True) ... class Merchant(models.Model): ... ... @property def business_phone_number(self): number = self.phonenumber_set.first() if number: return number.phone_number return None and then in Django admin I have: @admin.register(Merchant) class MerchantAdmin(admin.ModelAdmin): list_display = ("name", "business_phone_number", ...) ... I've put in get_queryset: def get_queryset(self, request): return super().get_queryset(request).prefetch_related("phonenumber_set")... -
ManyToManyField Data not showing up
Good day, i have got a problem with adding a listing to the watchlist of a specific user. Any tips on how i could fix this? I have tried to create a seperate model and that inherits from the listing model. The model structure class Listing(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT, default='', null=True ) title = models.CharField(max_length=200) description = models.TextField() image = models.ImageField(upload_to='media/') price = models.FloatField() category = models.ForeignKey(Category,on_delete=models.CASCADE,default='') # a listing can have multiple watchers and a watcher can have multiple listings watchers = models.ManyToManyField(User,blank=True,null=True,related_name="listings") def __str__(self): return "%s" % (self.title) Code of the view def listing(request, id): comment_form = AddComment() bid_form = AddBid() listing = Listing.objects.get(id=id) if request.method == "POST": if "watchlistBtn" in request.POST: listing.watchers.add(request.user) listing.save() return render(request, "auctions/listing.html", { "listing": listing, "comment_form": comment_form, "bid_form": bid_form }) # watchlist @login_required(login_url='/login') def watchlist(request): listings = request.user.listings.all() return render(request,"auctions/watchlist.html", { "listings": listings }) The code of the form template <form action="{% url 'watchlist' %}" method="post"> {% csrf_token %} <input type="submit" value="Add to Watchlist" class="btn btn-primary" name="watchlistBtn"> </form> -
STATIC CONTENTS DOESNT DISPLAYING EVEN AFTER LOADING IT IN DJANGO
Html code of the program i have collected static files and stored it in ASSET and gave load static in every img and a tags but still didnt able to get the static files in browser {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'STYLES.css' %}"> <link rel="shortcut icon" href="{% static 'favicon-32x32.png' %}" type="image/x-icon"> <title>HOMEPAGE</title> </head> <body> <div class="TOP"> <table> <tr> <td><img class='LOGO' src="{% static 'LOGO.png' %}" alt="LOGO" width="150px" height="150px"></td> <td><p class="COMPANY">SJ-EVENTS</p></td> <td class="BUTTONS"> <ul class="BUTTONS"> <li class="LINK"><a href="{% url 'SERVICE' %}" target="_blank">SERVICES</a></li> <li class="LINK"><a href="{% url 'CONTACT' %}" target="_blank">CONTACT</a> </li> <li class="LINK"><a href="#ABOUT">ABOUT</a></li> </ul> </td> </tr> </table> </div> <br><br><br> <br><br><br> <div class="TOP1"> <p>EVENT SERVICES</p> <h1>Flawless Event Management</h1> <h2>Whether planning an in-person, virtual, or hybrid event, there is an exciting new world of opportunities available — but also new complexity.</h2> <br><br><br> </div> <img class="PICTURE1" src="{% static 'HOMEPAGE1.jpg' %}" alt="HOMEPAGE" width="1250px" height="550px"> <br><br><br><br> <hr class="LINE"> <div class="MIDDLE"> <p>Pull your event together effortlessly with expert assistance from the leading event management company.</p> <br> <p> We work behind the scenes to keep everything moving and on time for our customers. Our simplified, smart solutions make it easy for exhibitors … -
connection to /run/my.sock failed: [Errno 13] Permission denied
After I've updated code on my Django project and tried restarting the servise, I've started getting this errror: 2022-09-15 16:33:35 +0000] [695873] [INFO] Starting gunicorn 20.1.0 [2022-09-15 16:33:35 +0000] [695873] [DEBUG] connection to /run/my.sock failed: [Errno 13] Permission denied [2022-09-15 16:33:35 +0000] [695873] [ERROR] Retrying in 1 second. [2022-09-15 16:33:36 +0000] [695873] [DEBUG] connection to /run/my.sock failed: [Errno ... [2022-09-15 16:33:39 +0000] [695873] [ERROR] Retrying in 1 second. [2022-09-15 16:33:40 +0000] [695873] [ERROR] Can't connect to /run/my.sock How do I diagnose the problem? Gunicorn logs don't say what's causing it. I didn't change configs. If I maid a mistake in the project folder, it still should have started. But there's no socket file in the run folder. -
Implement Unit Test for OAuth Flow in Django app
I integrated OAuth into my Django app. OAuth has 2 steps: Redirect to OAuth provider domain name Callback to Django app with token I would like to implement TestCase units for the above flow. Here is what I wrote for testing step 1: def test_connect_with_oauth_provider(self): """Test connecting with OAuth provider.""" url = signin_url("oauth-provider") res = self.client.get(url) self.assertEqual(res.status_code, status.HTTP_200_OK) However, the test uses testcase domain not my real domain and thus the test fails. Can you please help me implement tests for both steps? Thanks! -
How do I create if statement on django template?
enter image description here If there are not projects created, projects is the name of my viewclass for my model, then I need it to create a message, but I do not know how to create the right if statement. -
How to create property methods in django models dynamically?
I am creating property methods for every model where the model attribute includes ImageField or FileField. So, I decided to make an abstract model where I check the fields in the model and if there are any ImageField and FileField in the model the property method creates it automatically by itself. I usually add '_url' to the attribute when I create the method Below is what I do usually class MyModel(models.Model): image = ImageField(...) file = FileField(...) ... @property def image_url(self): if self.image and hasattr(self.image, 'url'): return self.image.url @property def file_url(self): if self.file and hasattr(self.file, 'url'): return self.file.url ... Below what I did so far class MyModel(models.Model): ... def __new__(cls, value): fields = self._meta.get_fields() for field in fields: if isinstance(field, ImageField) or isinstance(field, FileField): ??? Any suggestions? -
Best way to handle temporary user-uploads in web-development?
Hello on the overflow, I am fairly new to web development so please don't crucify me. I am currently in the process of laying out the foundation for a web-app (using Django as backend) that will involve user uploads (blob-files). The application will perform some machine learning on the upload and present the output to the user in the browser. Once presented with the output, the user will have the option to save the upload to that particular user's subfolder in the bucket (assuming cloud storage will be used). How do I best deal with the upload while it is temporary, that is, before the user has decided to save it to storage? The above may reveal a crucial misunderstanding of mine in how the user interacts with the server, however, I can see this as one solution: Creating a temporary folder for each user in the bucket, where an upload is stored until the user either decides to save it (move to proper folder) or not to save it (delete it from temporary folder). Is this solution totally bonkers and is there a much easier one? I look forward to any replies. Sincerely, an aspiring web developer -
Static files in django when extending from template
So i am having trouble loading my static files (images) in my template when extending from my base.html, so in my base.html the static files are working for example my favicon and my style are all loading. But when i want to load an image in my charts.html it does not work. To be clear the problem lies with the barchart_coins.png file. This is my charts.html file {% extends "main/base.html" %} {% load static %} {% block title %}Charts{% endblock %} {% block subtitle %}<h1 class="h1">Welcome to your crypto wallet visualized</h1>{% endblock %} {% block content %} <img type="image/png" src"{% static "images/barchart_coins.png" %}" alt="barchart"> {% endblock %} This is my base.html file {% load static %} <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'main/css/style.css' %}"> <title> {% block title %}<h1>You forgot to place a title in your file<h1>{% endblock %} </title> <link rel="icon" type="image/png" href="{% static 'main/images/bitcoin_fav.png' %}"> </head> <body> <header> <nav> <ul> <li><a href="/">Home</a></li> <li><a href="/overview">Overview</a></li> <li><a href="/data">General data</a></li> </ul> </nav> </header> <div class="body"> {% block subtitle %}<h2>>ou forgot to place a subtitle in your file<h2>{% endblock %} {% block form %}<p>You forgot to … -
Array field in not storing array in django?
I'm using django. In my model i used array field. Now the problem is when i hit the api on postman with following body. I get following error. I don't know why this is happening. I'm trying to send array to store in array field but this is not happening. models.py class Booking(models.Model): user = models.ForeignKey(User, related_query_name="user_booking", on_delete=models.CASCADE) booking_hours = ArrayField(models.CharField(max_length=512),null=True,blank=True) create_time = models.DateTimeField(_("Create time"), default=timezone.now) here is body sending from postman. { "booking_hours":["12:00:00 - 13:00:00","13:00:00 - 14:00:00","14:00:00 - 15:00:00"] } response : { "booking_hours": { "0": [ "Not a valid string." ] } } serializers.py class GroundBookingSerializer(serializers.ModelSerializer): class Meta: model = Booking fields = "__all__" -
Django model field bug? "value too long for type character varying(3)" error
I am declaring two choice fields for my django model in the same manner but one of them somehow bugs into having maxlength=3. I am using a PostgreSQL database. Here is how I declare the fields: class AssignmentAd(models.Model): class FieldChoices(models.TextChoices): JFS = "JFS" JAVA = "Java" CLOUD = "Cloud" __empty__ = _('(Unknown)') class RemoteChoices(models.TextChoices): JFS = "JFS" JAVA = "Java" CLOUD = "Cloud" __empty__ = _('(Unknown)') remote = models.CharField(max_length=20, choices=RemoteChoices.choices, blank=True,) field = models.CharField(max_length=20, choices=FieldChoices.choices, blank=True,) After declaring these two fields in my model, I can create an instance through admin by choosing "JFS" for both these fields (since it is 3 chars long) but if I choose any other option that is longer than 3 chars for the remote field, I get this "value too long for type character varying(3)" error. I don't get this error for the "field" field only for the "remote" field. What gives? Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/track/assignmentad/2/change/ Django Version: 4.1 Python Version: 3.10.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'members', 'track'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python310\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) The above exception (value too long … -
How to deploy a Django+React App to Herocu?
I've tried many tutorials but I failed to deploy my application specially with handling the static files, can you recommend me a good working tutorial. Thanks alot. -
Unique together causes IntegrityError
Django==4.1 I have stipulated a unique together constraint. Then I try to check whether it really works. But I have an IntegrityError. I hoped that a unique together constraint will raise ValidationError. But it didn't happen. Could you help me understand whether I'm wrong with my supposition about ValidationError in this case. And how to cope with this problem (which method to redefine and how)? Model class Task(PriorityMixin, CommentMixin, ): # n-fipi cypher = models.CharField( max_length=255, null=False, default="", ) fipi_section = models.ForeignKey("fipi_site_sections.FipiSection", on_delete=models.CASCADE, null=False, blank=False) page = models.PositiveIntegerField(null=False, blank=False, default=0) task_description = models.ForeignKey("fipi_task_descriptions.TaskDescription", on_delete=models.CASCADE, null=False, blank=False) def __str__(self): return self.cypher class Meta: ordering = ['fipi_section', 'page', 'priority', ] constraints = [ models.UniqueConstraint(fields=['fipi_section', 'page', 'priority', ], name='fipi_section-page-priority') ] Traceback Environment: Request Method: POST Request URL: https://aux.academic.gift/whibrsp1tapre4rl/fipi_tasks/task/add/ Django Version: 4.1 Python Version: 3.10.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'isbn_field', 'general', 'fipi_exam_parts', 'fipi_exam_sections', 'fipi_site_sections', 'fipi_task_descriptions', 'fipi_tasks', 'fipi_options', 'vocabulary_sources', 'vocabulary_units', 'vocabulary_exercises', 'vocabulary_phrases', 'vocabulary_videos', 'vocabulary_options'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/home/g/grablmz2/aux.academic.gift/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/home/g/grablmz2/aux.academic.gift/venv/lib/python3.10/site-packages/django/db/backends/mysql/base.py", line 75, in execute return self.cursor.execute(query, args) File "/home/g/grablmz2/aux.academic.gift/venv/lib/python3.10/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "/home/g/grablmz2/aux.academic.gift/venv/lib/python3.10/site-packages/MySQLdb/cursors.py", line 319, in _query … -
django: How add to database by loop corectly?
I am trying to save in the database all fights for a given group (everyone with everyone) at the same time from the form taking the number of rounds for each of the fights, so far the function does not add anything to the database. I am not sure if it can be added in a loop like this following the list of pairs: [(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4 ), (2, 5), (3, 4), (3, 5), (4, 5)] and refer to the indexes of list items when creating combat objects to save def add_fights(request, group_id): group = Group.objects.get(pk=group_id) tournament = group.tournament participants = group.participants.all() participants_ids = participants.values('id') only_ids_ls = [i.get('id', 0) for i in participants_ids] participants_pairs = list(itertools.combinations(only_ids_ls, 2)) group.fighters_one = [p[0] for p in participants_pairs] group.fighters_two = [p[1] for p in participants_pairs] print(participants_pairs) if request.user.is_authenticated: form = AddGroupForm(request.POST) if request.method == "POST" and form.is_valid(): rounds = form.cleaned_data['rounds'] obj = form.save(commit=False) if obj: for p in participants_pairs: obj.group = group obj.rounds = rounds obj.tournament = tournament obj.fighter_one = group.participants.get(id=p[0]) obj.fighter_two =group.participants.get(id=p[1]) obj.save() print("obj") print(obj) group.fights.create(group=group, rounds=rounds, tournament=tournament, fighter_one=obj.fighter_one, fighter_two=obj.fighter_two) return HttpResponseRedirect(reverse("tournaments:tournament_details", args=[group_id])) else: form = AddFightsForm return ( render(request, "add_fights.html", context={ 'form': form, … -
Bringing Select-Option values to Select-Option
I made a drop-down field that I created with select-option, after saving the data I selected here, when I enter the update form, I want the data selected in the save form to be selected again, can you help with this? insert.html <select name="healmedy_car_info" id="healmedy_car_info" class="form-select" aria-label="Default select example"> <option value="selectcar">Lütfen Araç Seçiniz</option> <option value="34SAS20">34 SAS 20</option> <option value="34SAS30">34 SAS 30</option> <option value="34BF2904">34 BF 2904</option> <option value="34TP0633">34 TP 0633</option> <option value="34BF9529">34 BF 9529</option> </select> update.html <select name="healmedy_car_info" id="healmedy_car_info" class="form-select" aria-label="Default select example"> <option value="selectcar">Lütfen Araç Seçiniz</option> <option value="34SAS20">34 SAS 20</option> <option value="34SAS30">34 SAS 30</option> <option value="34BF2904">34 BF 2904</option> <option value="34TP0633">34 TP 0633</option> <option value="34BF9529">34 BF 9529</option> </select> I pull the data with django and save it to the database, I just want the data I pulled here to be selected in update.html. -
Is it possible to use aggregate on a queryset annotation?
I am using annotate on a django queryset: class MyModel(models.Model): my_m2m = models.ManytoManyField() my_qs = MyModel.objects.all().annotate(total_m2m=Count('my_m2m')) This yields the desired result. E.g: >>> my_qs[0].total_m2m >>> 3 How do I use aggregate to count the total number of my_m2m in the queryset? E.g. >>> my_qs.aggregate_m2m >>> 9 -
Django DETAIL: Failing row contains (11, SG 553, BATTLE-SCARRED, CLASSIFIED, NORMAL, RIFLE, null, 6235.05)
task to create Weapon objects: def populate_weapon_objects(amount: int = 1) -> None: for _ in range(amount): weapon = Weapon.objects.create( name=_get_random_name(), exterior=_get_random_exterior(), quality=_get_random_quality(), category=_get_random_category(), price=_get_random_price(), ) Weapon model: class Weapon(models.Model): ... name = models.CharField(max_length=64, choices=WEAPONS, db_index=True) exterior = models.CharField(max_length=64, choices=EXTERIOR, default=EXTERIOR_FACTORY_NEW, db_index=True) quality = models.CharField(max_length=64, choices=QUALITY, default=QUALITY_CONSUMER_GRADE, db_index=True) category = models.CharField(max_length=64, choices=CATEGORY, default=CATEGORY_NORMAL, db_index=True) type = models.CharField(max_length=64, editable=False, db_index=True) slug = models.SlugField(max_length=64, editable=False, unique=True, db_index=True) price = models.FloatField(validators=[MinValueValidator(0), MaxValueValidator(10**4)], db_index=True) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) def save(self, *args, **kwargs): if not self.type: self.type = self._get_type_by_name() if not self.slug: self.slug = self._get_slug() return super().save(*args, **kwargs) def _get_type_by_name(self) -> str: return next(k for k, v in self.NAME_TO_TYPE_DICT.items() if self.name in v) def _get_slug(self) -> None: self.slug = generate_slug(self) generate_slug function: def generate_slug(weapon) -> str: name = weapon.name exterior = weapon.exterior quality = weapon.quality category = weapon.category sequence = [name, exterior, quality, category] slug = slugify(' '.join(sequence)) return slug This leads to: django.db.utils.IntegrityError: null value in column "slug" of relation "weapons_weapon" violates not-null constraint celery-worker | DETAIL: Failing row contains (14, PP-BIZON, MINIMAL WEAR, RESTRICTED, NORMAL, SMG, null, 7354.3, 2022-09-15 13:15:43.75499+00, 2022-09-15 13:15:43.754978+00). Why this happens? Why the type field is being filled when creating an Weapon objects and slug field keeps crashing … -
Yandex webvisor error peticiones cada 2 segundos
No se por que me aparecen unas peticiones a mi sitio que dicen Yandex webvisor, no he añadido nada que tenga que ver con Yandex, Yandex error peticiones Estas son las peticiones que se repiten cada 2 segundos: peticion yandex 2 peticion yandex 1 Me gustaria desactivarlas pero no encuentro nada de información en internet -
Filter records by lookup in the same table
Suppose we have a table: +--------------- ... | id | old_id | +--------------- ... | ... How do I select all values by some custom criteria except where id is found in column old_id? I've tried: records = MyRecords.objects\ .filter(<my custom criteria>)\ .exclude(id__in=models.OuterRef('old_id'))\ .order_by('-modified_at') and other variations, but to no avail. Basically, I am trying to achieve this behavior: select * from mytable where <custom criteria> and not id in (select old_id from mytable where 1) -
Which database would be best for simple e-commerce site?
I am newbie for designing and programming. I'm working personal project to make e-commerce site in django. Will MySql or Postgresql be better suit for a e-commerce website? As far I know reading data mysql is fast if there is read from database more. What would be best suit for e-commerce site? -
Django app gets stuck after sometime that the server is running
i am facing an issue with my Django application. After i build the container and i have my Django app working fine after some time in use, it just gets stuck. For example i try to log in and it is just loading infinitely and i have to restart the container in order to have the application up running again. Is this issue happening for any specific reason, and can someone help me so i avoid restarting the container anytime this happens? I have also tried changing the templates configuration in the settings.py file from: DIR:[] to 'DIRS': [os.path.join(BASE_DIR, 'templates')] but it still happens. -
Django app - Browse a dictionary with sub arrays
I would like to browse and display this dictionary which contains other sub-tables inside Here I would like to display the purchases of "fafa" only Views.py def app(request): dict= { "toto": "tata", "messages": [ { "mont": "ton", "fafa": "fki" } ], "commandes": [ { "numero": "h221g", "date": "14-07-22", "reference": "ref1", "name": "fafa", "purchases": [ { "article": "articlename", "designation": "laptop", "quantity": 2, "price": 133 }, { "article":"article2", "designation":"Dell" "quantity":3, "price":144 }, ... ] }, .... ] } mes_ventes=dict['commandes'] purchases=dict['commandes'][0]['purchases'] context={'commandes':mes_ventes,'lignes':mes_lignes} return render(request,'test/test.html',context) test.html {% for commande in commandes %} {% if commande.name == "fafa" %} {% for ligne in lignes %} <p>{{ligne.article}}<br>{{ligne.designation}}<br> {{ligne.quantity}}<br> {{ligne.price}}</p> {% endfor %} {% endif %} {% endfor %} It shows me purchases but that of "fafa" -
Handle Django Rest Framework permission when creating related objects
The has_object_permission method of a Permission on DRF obviously does not get executed on Create, since the object does not exist yet. However, there are use cases where the permission depends on a related object. For example: class Daddy(models.Model): name = models.CharField(max_length=20) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class Kiddy: title = models.CharField(max_length=12) daddy = models.ForeignKey(Daddy, on_delete=models.CASCADE) If we only want to allow the owner of Daddy to create Kiddy of that Daddy, we would have to validate that somewhere. I know this a really common discussion, also mentioned on this question and in many many more. It is also discussed on DRF GitHub itself where a docs update is done for that purpose, and referring to DRF docs it solves the problem here with the following sentence: ... In order to restrict object creation you need to implement the permission check either in your Serializer class or override the perform_create() method of your ViewSet class. So, referring to DRF docs, we could do one of the following solutions: class KiddySerializer(viewsets.ModelViewSet): validate_daddy(self, daddy): if not daddy.owner == self.context['request'].user: raise ValidationError("You cannot create Kiddies of that Daddy") return daddy or class KiddyViewSet(ModelViewSet): def perform_create(self, serializer): if (self.request.user != serializer.validated_data['daddy'].owner) raise ValidationError("You cannot create … -
How to get a value from the result of queryset and assign it
How to get a value from the result of queryset and assign it I've got a result of queryset <QueryDict: {'payment_id': ['KIAhwplaq0qgx8'], 'pay_order_id': ['order_KIAhsgbBDXth83'], 'result': ['5e5ab4f08a09915aa4791d25315b565beb62efe52fae71de877e2818d266f538']}> I want those values to be assigned like this payment_id = 'KIAhwplaq0qgx8' pay_order_id = 'order_KIAhsgbBDXth83' result = '5e5ab4f08a09915aa4791d25315b565beb62efe52fae71de877e2818d266f538' Even the queryset code to get a value AND ASSIGNING IT IS FINE BUT i Don't KNOW How. If anyone knows. Please share it. It would be Helpful