Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model business rules
what's the best place to make my model validation rules, example i have an entity model where a field is validated by another field assert field1 == 2*feidl2 since drf3 is not executing full_clean() method, and in my application there many logic and many places where the model is created i can't use serializer in all places ,this why validation in serializer will not works fine for my case , for the momen replicate validation works fine (in serializer and clean method) I'm looking for the best practice to do that thanks -
GraphQLTestCase self.query query() got an unexpected keyword argument 'op_name'
I have the following GraphQLTestCase def test_create_foo(self): response = self.query( """ mutation createFoo($input: MutationInput!) { createFoo(input: $input) { foo { id title } } } """, op_name="createFoo", input_data={"title": "Title Test"}, ) When I ran, I got the error: response = self.query( TypeError: query() got an unexpected keyword argument 'op_name' I am using: graphene 3.1.1 graphene-django 3.0.0 What can be? -
How to make paginator to loop over a query set
I'm using Paginator class on a page which displays each post posted by the users that the logged-in user follows. I'm having trouble showing the correct number of pages. I think the problem is at post_list = all_posts but I couldn't figure out how to solve this. all_posts is a list of query sets, do I need to loop over this list and assign the query sets to the post_list? If so, how can I do that? views.py: def following(request, username): try: all_posts = [] follow_item = Follow.objects.filter(follower = request.user) for item in follow_item: posted_by = item.following posts = AllPost.objects.filter(user = posted_by).order_by("date").reverse() all_posts.append(posts) post_list = all_posts paginator = Paginator(post_list, 10) # Show 10 posts per page. page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, "network/following.html",{ "page_obj":page_obj, "follow_item": follow_item }) except: follow_item = False return render(request,"network/following.html",{ "posts": post_list }) following.html: {% extends "network/layout.html" %} {% block body %} {% if follow_item %} {% for object in page_obj %} {{ post.full_name|upper }}<br> {% for post in object %} <div class="frame"> <h4><a href="{% url 'profile' post.user.username %}" style="color: black;">{{post.user.username}}</a></h4> <div>{{post.content}}</div> <div id="grey">{{post.date}}</div> <div id="grey">{{post.likes}}</div> <a href="#" style="color: grey;">Comment</a> </div> {% endfor %} {% endfor %} {% else %} <div class="alert alert-warning" role="alert"> You … -
failed to resolve image name: short-name "caddy:2-alpine"
I get this error when running docker-compose up: ERROR: failed to resolve image name: short-name "caddy:2-alpine" did not resolve to an alias and no unqualified-search registries are defined in "/etc/containers/registries.conf" Here is my docker-compose.yaml file: version: "3" #networks: # web: # external: true # bridge: # driver: bridge services: # CaddyServer reverse proxy caddy: restart: always image: caddy:2-alpine ports: - "443:443" command: caddy reverse-proxy --from https://xxxxxx.com --to http://0.0.0.0:8000 #volumes: # - /local/path/to/Caddyfile:/path/inside/continer/to/Caddyfile # networks: # - web # - bridge # Django web app django: restart: always build: . ports: - "80:8000" depends_on: - pgdb #environment: # - url=https://api.backend.example.com #command: "gunicorn config.wsgi:application --bind 0.0.0.0:8000" #networks: # - bridge pgdb: image: postgres container_name: pgdb environment: - POSTGRES_DB=xxxxx - POSTGRES_USER=xxxx - POSTGRES_PASSWORD=xxxx volumes: - pg-data:/var/lib/postgresql/data/ volumes: pg-data: -
Get ID from submitted form in Django
I'm using React and Django and have created a form for user input. On submit I would like the ID of the post to be returned so the page can automatically load the next step using the ID in the URL. Currently the post is added to the database just fine but I'm having trouble with what happens after. views.py class CreateArticle(generics.CreateAPIView): queryset = Article.objects.all() serializer_class = CreateArticleSerializer def article(self, request, format=None): serializer = self.serializer_class(data=request.data) if(serializer.is_valid()): title = serializer.data.get('title') p = Article(title=title) p.save() return Response(ArticleSerializer(p).data, status=status.HTTP_200_OK) return Response(status=status.HTTP_400_BAD_REQUEST) serializer.py class CreateArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = ('title') models.py def generate_unique_id(): return(uuid.uuid4()) class Article(models.Model): id = models.CharField(max_length=36, default=generate_unique_id(), primary_key=True) title = models.CharField(max_length=50) def __str__(self): return self.title CreateArticle.jsx try { API.post("/create/", { ...article }).then((response) => console.log(response)) } catch (err) { console.log(err) } I understand views can only return HTTP requests but I am new to Django and lost here. I've tried creating the ID in the view and returning that as a response but it does not appear within the usual Axios data. Any direction would be appreciated. Thank you -
TypeError: Query fields cannot be resolved. The type QuestionnaireType doesn't have a connection
I have the following schema: class Query(graphene.ObjectType): all_questionnaires = DjangoFilterConnectionField(QuestionnaireType) I got the error when running the tests TypeError: Query fields cannot be resolved. The type QuestionnaireType doesn't have a connection What can be? -
Do User tests for every url?
I have urls like this: in main: path('admin/', ...), path('forstaff/', include("myapp.urls"), path('forusers/', include("anotherapp.urls"), If a user is is_staff=True, they can access forstaff/, if not, they get redirected to `forusers/'. I know that I can do this: class StaffRequiredMixin(LoginRequiredMixin, UserPassesTestMixin): def test_func(self): return self.request.user.is_staff but I have to add this StaffRequiredMixin to every single class based view in myapp.urls, and also can not use it with function based classes. Is there a way I can tell Django to apply this "rule" to every single view of the app? -
How to get User Email from User model in a function Django
Hi Iam newbie to Django, I written an function to send email from any user who need to know more info about the trip. I didn't know to how to collect posted user email id from user database. need help. def PostDetailView(request, pk): context = {} context["data"] = Post.objects.get(id=pk) if request.method == "POST": name = request.POST['uName'] # phone = request.POST["phone"] email = request.POST['uEmail'] desc = request.POST['uDes'] userEmail = I need to assign email id of this trip posted user subject = 'Iam Interested in your Trip' message = f'Hi Iam {name}, Iam Interested you trip. Please share more details on {email} {desc}' email_from = email recipient_list = [userEmail, ] send_mail( subject, message, email_from, recipient_list, desc ) messages.success(request, 'Message Sent Successfully.') return render(request, 'ads/detail.html',context) return render(request, 'ads/detail.html',context) Need help to fix this. -
dependent list show in templets in Django python
I want to add dependent list in templets in Django . their are 2 table and the forgin key in 2nd table now I want to show in templets like shown as in image. -
django orm limit before annotation
I want to limit queryset befor annotation! This ins my django orm code : ProductDB.objects.prefetch_related('media').select_related("cover", 'category').filter(**variants_filter)[offset:offset + limit].annotate( variants_count=Count('product_variants')) this is query that django generates: SELECT "shop_product"."id", "shop_product"."is_deleted", "shop_product"."created_at", "shop_product"."updated_at", "shop_product"."approval_status", "shop_product"."name", "shop_product"."name_en", "shop_product"."slug", "shop_product"."source_name", "shop_product"."source_id", "shop_product"."default_variant_id", "shop_product"."phone_id", "shop_product"."phone_model_id", "shop_product"."category_id", "shop_product"."brand_id", "shop_product"."source_price", "shop_product"."cover_id", "shop_product"."attributes", "shop_product"."extra_data", COUNT(T3."id") AS "variants_count", "shop_category"."id", "shop_category"."is_deleted", "shop_category"."created_at", "shop_category"."updated_at", "shop_category"."name", "shop_category"."name_en", "shop_category"."slug", "shop_category"."order", "shop_category"."parent_id", "account_file"."id", "account_file"."is_deleted", "account_file"."created_at", "account_file"."updated_at", "account_file"."file", "account_file"."normal", "account_file"."thumbnail", "account_file"."name", "account_file"."type", "account_file"."user_id", "account_file"."source" FROM "shop_product" LEFT OUTER JOIN "shop_variant" T3 ON ("shop_product"."id" = T3."product_id") LEFT OUTER JOIN "shop_category" ON ("shop_product"."category_id" = "shop_category"."id") LEFT OUTER JOIN "account_file" ON ("shop_product"."cover_id" = "account_file"."id") WHERE "shop_product"."default_variant_id" IS NOT NULL GROUP BY "shop_product"."id", "shop_category"."id", "account_file"."id" LIMIT 5 Django puts the limit after all selects and it's very slow: If i put limit on select its very fast: Just by replacing (select * from "shop_product" limit 5) instead of FROM "shop_product" Am i doing it wrong?? How can i implement this by orm -
How to translate fields in django models
I try to translate fields in model like this: my model: class CompletedWork(models.Model): period = models.ForeignKey(directory.Period, on_delete=models.SET('deleted date'), verbose_name=_("Period"), ) worker = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET('deleted worker'), related_name='worker_do', verbose_name=_('Worker'), default=settings.AUTH_USER_MODEL ) work_done = models.ForeignKey(directory.WorksType, on_delete=models.SET('deleted works type'), verbose_name=_('Work done') ) work_scope = models.FloatField(_("Work scope"), blank=True, null=True) work_notes = models.CharField(_("Comments"), max_length=70, blank=True, null=True, ) record_author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET('deleted user'), related_name='record_author', auto_created=True, ) record_date = models.DateTimeField(auto_now=True) checked_by_head = models.BooleanField(default=False) active = models.BooleanField(default=True) I don't understand why worker and work_done fields doesn't translated. in my locale: msgid "Add record" msgstr "Додати запис" msgid "Period" msgstr "Період" msgid "Worker" msgstr "Працівник" msgid "Work done" msgstr "Виконана робота" msgid "Work scope" msgstr "Обсяг роботи" So I see that: period - translated worker - not translated work_done - not translated work_scope - translated work_notes - translated in documentation says that you can mark names of ForeignKey, ManyToManyField or OneToOneField relationship as translatable by using their verbose_name options: class MyThing(models.Model): kind = models.ForeignKey( ThingKind, on_delete=models.CASCADE, related_name='kinds', verbose_name=_('kind'), ) Why it doesn't work right in my situation? -
Why can not this function be hooked on the `QuerySet` in django?
I want to hook some functions on Models.Manager. To implements the feature that appear to be signals. But when I use demo_1() to call the update(). It will call the QuerySet.update() The hook_func() will not be called. How to fix it? # manangers.py import functools from django.db.models import Manager def bulk_operation_decorator(func, obj, original_func): @functools.wraps(original_func) def wrapper(*args, **kwargs): res = original_func(*args, **kwargs) func(obj) return res return wrapper class BulkLinkageManager(Manager): def __init__(self, func, linkages=None, *args, **kwargs): super(BulkLinkageManager, self).__init__(*args, **kwargs) if not linkages: linkages = [] self.linkages = linkages self.__hook_func = func def __hook(self, target=None): if not target: target = self for linkage in self.linkages: original_func = getattr(target, linkage, None) if callable(original_func): setattr(target, linkage, bulk_operation_decorator( self.__hook_func, target, original_func )) def get_queryset(self): queryset = super(BulkLinkageManager, self).get_queryset() self.__hook(target=queryset) return queryset # models.py class MyModel(models.Model): objects = BulkLinkageManager(hook_func, ['update']) x = models.IntegerField() # hooks.py def hook_func(queryset): logging.info('success') # demo.py import logging import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'LHSCM.settings') django.setup() from models import MyModel def demo_1(): # `hook_func()` will not be called my_models = MyModel.objects.filter(x = 1) pes.update(x=6) def demo_2(): # `hook_func()` will be called my_models = MyModel.objects.all() pes.update(x=6) def main(): for i in range(20): x = i % 4 MyModel.objects.create(x = x) if __name__ == '__main__': main() -
How can I get the user's username and use it in a SQL query?
I have a Student table and I would like to get the current logged-in user's username and compare it with all the usernames in the Student table and then return the student_id if the username is found. I've got: SELECT student_id from Student WHERE username = <something> What am I supposed to write in the place of <something> to get the logged-in user's username? -
Page not found (404) No Invoice matches the given query
I am building a store in django. And I connected the store to a test payment gateway, and I can add products to the shopping cart, and do the test payment locally. But the problem occurs when I do a test payment and I have to be redirected to the callback.html page and I get an error. Image of the error that occurred Error image views.py file in the shop application: # Views.py in shop app import decimal from decimal import Decimal from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.shortcuts import render, get_object_or_404, redirect from . import models from cart.forms import CartAddProductForm from cart.cart import Cart from zeep import Client, client import requests import json # Index function def index(request): product_list = models.Product.objects.all()[:5] return render(request, 'index.html', {'product_list': product_list}) # Checkout function @login_required def checkout(request): cart = Cart(request) if request.method == 'POST': order = models.Order.objects.create(customer=request.user) for item in cart: models.OrderItem.objects.create(order=order, product=item['product'], product_price=item['price'], product_count=item['product_count'], product_cost=Decimal(item['product_count']) * Decimal(item['price'])) order.customer = request.user order.save() cart.clear() return render(request, 'order_detail.html', {'order': order}) return render(request, 'checkout.html', {'cart': cart}) # Product function def product(request, pk): product_detail = get_object_or_404(models.Product, id=pk) cart_add_product_form = CartAddProductForm() return render(request, 'product.html', {'product_detail': product_detail, 'cart_add_product_form': cart_add_product_form}) # Store function def store(request): return render(request, 'store.html') … -
How can use the ability to limit ip in Django?
I am using django 4.1 and I curious about how can use IP restriction in django .I have some experience about using packages like django-block-ip and Django-ip-restriction and Django-iprestrict . All of these packages old and do not work properly with django 4.1 version.is there any updated package for doing this ? I will appreciate your help very much -
In Django, how one employee could add the event(task) to his work_plan list?
I have an application that allows different organisers to publish their events (job vacancies) to potential workers(children tutors in this case). BTW, one event need only one tutor. A tutor can reserve the event but can not remove it without admin/organiser's permission. Also a tutor could not take another event that happens on the same day. I have already successed to show all published events in a list view. But I've got stuck on how a tutor could reserve that event, then add event to his/her own work plan list. Some codes may have typo as I modified many times. But hopefully you got my idea. Thanks. Here are a couple of pictures for a better understaning: I've tried the following code, after clicked the reserve button, it shows nothing. here is the view @login_required @is_tutor def work_plan(request): user=request.user work_plan=work_plan.objects.all() context={'work_plan':work_plan} return render(request,'work_plan.html',context) @login_required #reserve event @is_tutor def add_to_work_plan(request,pk): event =Summer_event.objects.get(id=pk) if request.method == "POST": if request.session.get("add_to_work_plan"): requst.session['add_to_work_plan'].append(pk) else: requst.session['add_to_work_plan']=[pk] work_plan.save() messages.success(request, "Work plan updated!") return redirect('work_plan') Model: class Work_plan(Summerevent): user=models.ForeignKey(get_user_model(),on_delete=models.CASCADE) reserved_date = models.DateField(null=True,auto_now_add=True) Url: path('work_plan/', views.work_plan, name="work_plan"), path('add_to_work_plan/<str:pk>/', views.add_to_work_plan, name="add_to_work_plan"), html template {% extends "header.html" %} {% block title %}{{section.title}}"{% endblock %} {% block content %} {% if events … -
Cant find out how can I compare two manytomany fields and show the result in context
So, I am doing a project where there are posts of 3 categories (movies(model name="List"), music(model name="MusicList"), books(model name="BookList")) each category is a model. and each model has its own genre set model (Genre, MusicGenre, BookGenre). There is a profile model which has - favourite_music_genre, favourite_movie_genre & favourite_book_genre. So now in my all(homepage) function in views I want to have some codes that will compare current logged in users favourite_music_genre, favourite_movie_genre & favourite_book_genre and show only the List, MusicList & BookList of the matched genres. For example if a users selected fav_genre is Action & Comedy. It will only show the lists which has Action & Comedy genre. Im new to python/django. Been scratching my head for past 4/6 days. couldn't figure out the way. In my Models.py class MusicList(models.Model): title = models.CharField(max_length=120) genre = models.ManyToManyField('MusicGenre') creator = models.ForeignKey(User,on_delete=models.SET_NULL,blank=True, null=True) posted = models.DateTimeField(auto_now_add=True) content = RichTextField(null=True,default=' ') type = models.CharField(max_length=10,default="Music") slug = models.SlugField(max_length= 300,null=True, blank = True, unique=True) def __str__(self): return f'{self.title}|{self.creator}' def save(self, *args, **kwargs): self.slug = slugify(self.title + str(self.posted)) super(MusicList,self).save(*args, **kwargs) class MusicGenre(models.Model): name = models.CharField(max_length=150) def __str__(self): return self.name class BookList(models.Model): title = models.CharField(max_length=120) creator = models.ForeignKey(User,on_delete=models.SET_NULL,blank=True, null=True) genre = models.ManyToManyField('BookGenre') posted = models.DateTimeField(auto_now_add=True) spoiler_choices = [(False, … -
How to pass a list of tuples in template file from views so I can separately iterate each data member in template?
I'm working on a django project , I got a list of tuples accessed from postgres database using psycopg2. Now I want to pass this list of tuples to my template file in such way that I can access each element of individual tuple. As I have to put this data into a html table. views.py file : def search_owner_prop(request): if request.method == 'POST': o_no = request.POST.get('owner_num') conn = psycopg2.connect(database="dreamhomeproperty", user="postgres", password="****", host="*****", port="****") cur = conn.cursor() cur.execute(f''' SELECT property_for_rent.property_n,private_owner.fname,property_for_rent.street,property_for_rent.rooms,property_for_rent.typee FROM dreamhome_schema.property_for_rent INNER JOIN dreamhome_schema.private_owner ON property_for_rent.owner_number={o_no} AND private_owner.owner_no={o_no}''') rows = cur.fetchall() conn.close() return render(request,'owner_with_prop.html') else: return render(request, 'search_owner_prop.html') -
Django - Automatically Create Model When Creating User
I have a Student Model, which should extend the Base User Model. Now I did this with a One to One Relation, but once my WebApp is done, I'd like to be able to create all the Users fast. Is there a way of adding all the fields of the Student Model into the User Creating Panel in /admin/? Here is my User Model for anyone wondering: class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birth = models.DateField(default=datetime.date.today) street = models.CharField(max_length=25) street_number = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(99)]) city = models.CharField(max_length=20) province = models.CharField(max_length=20) code = models.IntegerField(validators=[MinValueValidator(0, MaxValueValidator(9999))]) def return_address(self): address = self.street + ' ' + str(self.street_number) + ' ' + self.city + ' ' + str(self.code) + ' ' + self.province return address def __str__(self): address = self.return_address() return f'Adresse: {address}' -
Configuring django channels
It is my first time working with channels in django. I am trying to establish a websocket connection with my server for a chat application. The javascript code on the html page is <body> <div id="user-hello"></div> {{ room_name|json_script:"room-name" }} <script> const roomName = JSON.parse(document.getElementById('room-name').textContent); const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/' ); chatSocket.onmessage = function (e) { const data = JSON.parse(e.data) console.log(data) document.querySelector('#user-hello').innerHTML =(data.tester) } </script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script> </body> When javascript tries to establish a connection to the websocket it throws an error, it cant find the url. My settings file is as follows INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'channels', 'chat' ] ASGI_APPLICATION = 'config.routing.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } The routing.py file being referenced by ASGI_APPLICATION is from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import chat.routing application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ), }) Routing.py file in the chat app from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatRoomConsumer.as_asgi()), ] Finally consumer.py is import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( … -
DjangoDash How to use django pure html with dash callbacks
I was wondering, my team and I are considering using Django with Dash and React to build our application! Django - backend React - frontend Dash - dashboards (also frontend) So one thing I was trying to find out how to do but couldn’t is using pure HTML in a Django template, create an element, give it an id, and use that element inside a dash callback. for example: inside an HTML file I would have: inside the python dash file, we will have a callback returning value to that element Output(“hello”, “children”) Anyone knows a way to do this? / a repo with an example would be awesome! -
DjangoAapp keeps logging out for standard user and admin (staff) - cookies issue
Have a working Django app in production, there are several issues that appear while logging in, moving to sites that are for staff only (using decorators), etc. When logging in, I sometimes need to do it 2x, 3x times, or more, just repeat the username & password, so the user can get inside the portal (no error is thrown) When logging in as "staff", have some sites on the Portal which are restricted, often it asks to enter the password again (and shows the standard Django admin login page although still working on the app) - like the web browser does not remember that "staff" logged in already When already re-logged as the staff (above point), while continuing to do some actions on the page, like adding posts when hitting the "post" button it asks for the password again (note, I created an admin page on the website, to add posts, manage users, etc.) I suspect this is related to either: My Cookie setup Decorators used, restricting access to logged-in users or staff only Appreciate your help! settings.py SESSION_EXPIRE_AT_BROWSER_CLOSE = True SESSION_ENGINE = 'django.contrib.sessions.backends.cache' SESSION_COOKIE_AGE = 24*60*60*7 #1 week SESSION_COOKIE_SECURE = True SESSION_COOKIE_NAME = 'www.mywebsite.com' CSRF_COOKIE_SECURE = True SECURE_HSTS_SECONDS = … -
Django forms: queryset and custom choices in ModelChoiceField
I am trying to create a choice field in a form, where the user will select the location of the item in the list. In the form, user selects one of existing items and places new item before that or the empty_label, which places the item to the end of the list. What I would like is to place the empty_label as a last selection in the choices. Other option is to hide the empty_label (empty_label=None) and add a choice after the queryset with a label 'Add to the end of the list'. I cannot get either one of these to work. Here is a code for the form. class NewItem(forms.ModelForm): def __init__(self, *args, **kwargs): super(NewItem, self).__init__(*args, **kwargs) addbefore = ModelChoiceField( queryset=Items.objects.all().order_by('order'), empty_label='Add to the end of the list', label="Item location in the list / before item:", ) class Meta: model = Item fields = [ 'name', 'description', 'addbefore', ] So with this I get a choices where the 'Add to the end of the list' is the first selection, which is not logical. Is there a way to place the empty_label at the end of the choices or add custom choices after queryset? -
FieldError: Related Field got invalid lookup: contains
I am trying to implement a simple search where the user enters any string in the search input and the entire table is checked for the presence of string. My model class S_Owner_Master(models.Model): User= settings.AUTH_USER_MODEL flat_status = (('0', "Vacant"), ('1', "Occupied")) occupants = (('0', "Vacant"), ('1', "Owner"), ('2', "Tenant")) society = models.ForeignKey(S_Society_Master, related_name='society', null = True, on_delete=models.CASCADE) owner_id = models.AutoField(verbose_name = "Owner ID", primary_key=True, unique=True) owner_name = models.CharField(verbose_name = "Owner Name", max_length=100, blank=True, null=True) owner_email_id = models.EmailField(verbose_name = "Owner Email", max_length=100) owner_contact_number = models.CharField(verbose_name="Phone Number", max_length=15) owner_flat_number = models.CharField(verbose_name="Flat No.", max_length=20) owner_flat_registration_date = models.DateField(verbose_name = "Owner Flat Regn. Date") owner_flat_transfer_date = models.DateField(verbose_name = "Owner Flat Transfer Date") flat_area_in_sqft = models.DecimalField(verbose_name="Flat Area", max_digits=10, decimal_places=2) flat_occupancy_status = models.CharField(verbose_name="Occupancy Status", max_length = 50, choices=flat_status) occupied_by = models.CharField(verbose_name="Occupied By", max_length = 50, choices=occupants) deld_in_src_ind = models.CharField(max_length=20, choices=[("yes", "Yes"), ("no", "No")], default = "no", blank=True, null=True) created_date = models.DateField(verbose_name = "Created Date", auto_now_add = True) created_by = models.ForeignKey(User, related_name = "+", on_delete = models.SET_NULL, verbose_name="Created By", max_length=100, blank=True, null=True) updated_date = models.DateField(verbose_name = "Last Updated Date", auto_now_add = True, blank=True, null=True) updated_by = models.ForeignKey(User, related_name = "+", on_delete = models.SET_NULL, verbose_name="Updated By", max_length=100, blank=True, null=True) views.py def owner_simple_search(request): search_text = request.GET.get('search_field', None) if search_text is … -
How to make sure random string in django python model will unique
I have a question with the random string in python django. I have created a django model class Post(models.Model): slug = models.SlugField(unique=True,blank=True) title = models.CharField(max_length=200) description = models.TextField() def save(self, *args, **kwargs): str_ran = "abcdefghijklmnopqrstuvwxyz" slug = "" for i in range(5) : slug += random.choice(str_ran) self.slug = slug super(Post, self).save(*args, **kwargs) But sometimes that's have some error because the slug field is not unique by python random isn't random a unique string. What should i do? Do you have some recommend for random these string to make sure it will be unique?