Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: module 'random' has no attribute 'choise' Django
so i'm kinda new to this world of programming and I took the Udemy course called Python and Django Full Stack Web Developer. Now i'm on the last part where we are using Django. I watched the video and followed his code and tried to run it bymyself. But then I encountered by this error. I looked after a solution online and in here also, but I saw solution that offer to check if there is another function or module with the same name by mistake or something, and I have not.. this is my code: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_project.settings') import django django.setup() import random from first_app.models import AccessRecord, Webpage, Topic from faker import Faker fakegen = Faker() topics = ['Search', 'Social', 'Marketplace', 'News', 'Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choise(topics))[0] t.save() return t def populate(N=5): for entry in range(N): top = add_topic() fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() webpg.objects.get_or_create(topic=top, url=fake_url, name=fake_name)[0] acc_rec = AccessRecord.objects.get_or_create(name=webpg, date=fake_date)[0] if __name__ == '__main__': print("populating script!") populate(20) print("populating complete!") and I refer to the models.py code also: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_project.settings') import django django.setup() import random from first_app.models import AccessRecord, Webpage, Topic from faker import Faker fakegen = Faker() topics = ['Search', … -
Complex M2M filtering using Django's ORM
I have the following models: class Sauce(models.Model): ... class Topping(models.Model): ... class Pizza(models.Model): sauces = models.ManyToManyField(Sauce, related_name='pizzas') toppings = models.ManyToManyField(Topping, related_name='pizzas') Now, lets say I want to query all the pizzas given a list of toppings and sauces. For example: sauces_ids = [1, 2] toppings_ids = [1, 2] What I am doing right now in my API view is as follows: pizzas = Pizza.objects.filter(restaurant=restaurant) if request.data.get('sauces_ids', []): pizzas = pizzas.filter( sauces__in= request.data['sauces_ids'] ) if request.data.get('toppings_ids', []): pizzas = pizzas.filter( toppings__in= request.data['toppings_ids'] ) return pizzas.distinct() There was a duplication problem which I solved using the distinct() function. However, now I am facing a different issue. I have 2 pizzas in my database: Pizza 1 with sauces = [1, 2], toppings = [1, 2] Pizza 2 with sauces = [1, 2], toppings = [1] With my above query parameters, I would like to return only Pizza 1 as the 2 M2M lists match exactly. However, the query I wrote is returning both the pizzas. How do I solve this? Thanks for any help. Moreover, is this an efficient way to do this? -
How to fix this TemplateSyntaxError at error in django
I get this error TemplateSyntaxError at / add requires 2 arguments, 1 provided Screenshot: ERROR SCREENSHOT I want to add pagination there but i get this error again and again Here is my html file <div class="pagination"> {% if buy_list.has_previous %} <li class="page-item"><a class="page-link" href="?page=1"></a></li> <li class="page-item"><a class="page-link" href="?page={{ buy_list.previous_page_number }}"></a></li> {% endif %} {% for num in buy_list.paginator.page_range %} {% if buy_list.number == num %} <strong>{{ num }}</strong> {% elif num > buy_list.number|add: '-3' and num < buy_list.number|add: '3' %} {{num}} {% endif %} {% endfor %} {% if buy_list.has_next %} <li class="page-item"><a class="page-link" href="?page={{ buy_list.next_page_number }}"></a></li> <li class="page-item"><a class="page-link" href="?page={{ buy_list.paginator.num_pages }}"></a></li> {% endif %} Thanks -
Uploading cropped picture fails with cropper.js and Django 2.2.7
I am trying to make a form that views users profile and displays a picture of a user. I have made a custom user class and added new field with profile picture (avatar). Idea is that when user is looking at the profile he can click on his picture and modal form pops up with displayed current picture (or default picture that looks like anonymous user). Then the user can click on upload new picture of any size and crop it using cropper.js to a standard format being set at 220 x 300 pixels. To develop this I took couple of examples on the Internet and made a mix of them. It works flawlessly until I wish to save the new picture in user database, this is just ignored with no error displayed whatsoever. Of course, when I do this from Admin interface and upload a picture it works every time. So, the part when I wish to save picture is triggered from modal form and it is part written in javascript to take data from cropper.js: $(".js-crop-and-upload").click(function () { var cropData = $image.cropper("getData"); $("#id_x").val(cropData["x"]); $("#id_y").val(cropData["y"]); $("#id_height").val(cropData["height"]); $("#id_width").val(cropData["width"]); $("#formUpload").submit(); console.log("BIO C&U"); $("#modalCrop").modal("hide") }); I have made a new save function … -
Unhandled exception in thread started by <function wrapper at 0x7f18aef9a758> Traceback (most recent call last):
Unhandled exception in thread started by Traceback (most recent call last): File "/var/www/html/patient_share/myenv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/var/www/html/patient_share/myenv/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run autoreload.raise_last_exception() File "/var/www/html/patient_share/myenv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "/var/www/html/patient_share/myenv/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/var/www/html/patient_share/myenv/local/lib/python2.7/site-packages/django/init.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/var/www/html/patient_share/myenv/local/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/var/www/html/patient_share/myenv/local/lib/python2.7/site-packages/django/apps/config.py", line 94, in create module = import_module(entry) File "/usr/lib/python2.7/importlib/init.py", line 37, in import_module import(name) ImportError: No module named rest_framework -
How to Create a plugin based website to manage the access control and feature access for client?
I am working on a product that was very simpler in its initial phase but as the product is growing we are continuously working on new functionality and we are releasing 2-3 minor/major functionality every month. So working with access control and feature with access with the same huge codebase is going harder every day, and it is also affecting product stability. So we are thinking about the plugging based website like our current project will be the core app new feature we will be created as a plugin and based on the client feature access we will plug/unplug on our core app. Can someone help me a bit of design its architecture? Please share a link if anyone has a blog or other stuff. Technology We are using: Django React ES & Redis for search and caching respectively Please help me. Thanks in Advance. -
Read a csv file and fill in database with it's data in django application
in my Django application, i created a form which permit user to upload csv file. What i want is when user upload the csv file, the contained data is read and database is filled in with them. It works but not correctly. data are saved as tuples. Here's my code forms.py class SupplierCSVForm(forms.ModelForm): class Meta: model = SuplierCsv fields = '__all__' exclude = ('slug',) views.py @login_required def l_supplier(request): suppliers_list = Supplier.objects.all() paginator = Paginator(suppliers_list, 3, 2) page = request.GET.get('page') suppliers = paginator.get_page(page) # Supplier csv form if request.method == 'POST': form = SupplierCSVForm(request.POST, request.FILES) if form.is_valid(): uploaded_file = request.FILES['csvfile'] with open('f.csv', 'wb') as destination: for chunk in uploaded_file.chunks(): destination.write(chunk) destination.close() #csvfile = io.TextIOWrapper(open('f.csv', 'rb')) with open('f.csv', 'r') as the_source: source_reader = csv.reader(sthe_source) next(source_reader) for Name, Email, Contact, City, Website, Activity, Cc, slug in source_reader: new_supplier = Supplier() new_supplier.name=Name, new_supplier.email=Email, new_supplier.contact=Contact, new_supplier.city=City, new_supplier.website=Website, new_supplier.activity=Activity, new_supplier.cc=Cc, new_supplier.slug=slug, new_supplier.save() return redirect('good:l_good') else: form = SupplierCSVForm() context = { 'suppliers': suppliers, 'form': form, } return render(request, 'supplier/l_supplier.html', context) -
Remain logged in even if user closes tab and reopens it (not browser close) - using Django and Pyrebase
I was wondering if there is a way to let the user remain logged in without having to sign in again if a user decides to close current tab and reopen it again. I am using Django and Python and here is the code I am using for signing in: def postsign(request): email = request.POST.get('email') passw = request.POST.get("password") try: user = auth.sign_in_with_email_and_password(email,passw) success = 1 except: success = 0 message = "invalid cerediantials" return render(request,"dashboard.html") session_id = user['idToken'] request.session['uid'] = str(session_id) context = { "success": success, "email": email, } return render(request, "dashboard.html", context) -
TypeError at /friend/accept_friend_requestPHByb3BlcnR5IG9iamVjdCBhdCAweDdmNTlhZTEzODI3OD4/status/
Error in the line as below: int() argument must be a string, a bytes-like object or a number, not 'ForwardManyToOneDescriptor' friend_user = User.objects.get(pk=Friend.to_user.id) -
How to create a new manytomany object and save it to a model in one view
I have a model repairOrders with 2 manytomany fields: class RepairOrder(models.Model): >>> labor = models.ManyToManyField(Labor) parts = models.ManyToManyField(Parts) I have the repairOrder displayed and have a button to create a new labor object by using the Labor modelForm. what I want to happen is after I create that obj I want it added to the manytomany field of the RepairOrder. how do I define that in the view? this is what I have now: def repairOrder_detail(request, pk): if request.method == "POST": form = laborForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.save() return redirect('repairOrder_detail', pk=pk) else: repairs = get_object_or_404(RepairOrder, pk=pk) form = repairOrderForm() labor = laborForm() return render(request, 'repairOrders/repairOrder_detail.html', {'repairs': repairs, 'form': form, 'labor': labor}) Right now I can create as many labor obj as I want but they are not added to the repairOrder model. I don't know what I need to call to save the labor instance to the repairOrder.labor field. I would like for this all to happen in one step for the end user. -
SweetAlert2 implementation in django
My problem is that I need to do a click on the button that address you to an url that has an int:pk I don't know about javascript and I don't know how to do the redirect when I click, I was searching and I didn't find a way to do it with an int:pk HTML code <button onclick="sweet();"> Delete Student </button> VIEWS.PY CODE def delete_student(request, pk, template_name="main/delete_student.html"): student = get_object_or_404( Student , pk = pk ) student.delete() return redirect("index") return render(request, template_name, {"student": student}) JS code (SWEETALERT2) function sweet(){ Swal.fire({ title: 'Are you sure?', text: "You won't be able to revert this!", icon: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Yes, delete it!' }).then((result) => { if (result.value == False){ } if (result.value) { Swal.fire( 'Deleted!', 'Your file has been deleted.', 'success' )})} -
Facing Issue With Django Machina Templates
I am Working on Rating Professor Website Using Django Framework.So That's Why I am Using Machina Forum But Facing Templates Issue In Settings .Loaders Are Not Working 'APP_DIRS': True, But When I Change 'APP_DIRS': False ,And Add MACHINA_MAIN_TEMPLATE_DIR To Templates Directory Machina Website Forum Works Fine But My Actual Website Goes Off Because of No Templates Exits Error. Question is That Can i Use Both Machina And My Template Directory at Same time And how ? If I add Machina Templates to Pycharm Project Templates and Make them as Templates then it's Work Or not ? There is Only Issue With Machina Templates Everything is Working Excellent . I Just Wanted Both Templates to Work On My Website . Setting.py import os from machina import MACHINA_MAIN_TEMPLATE_DIR from machina import MACHINA_MAIN_STATIC_DIR # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'SECRET_KEY' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'djangoproject.apps.DjangoprojectConfig', … -
Django: Getting 404 Error After Adding Views, Models and URLs Correctly
I am a beginner in Django. Right now, I am doing a simple app, called GameReview. It will allow the users to add the reviews of their favorite games. Right now, I am facing a 404 error. It looks like this: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/gamereview/ Using the URLconf defined in gamerevs.urls, Django tried these URL patterns, in this order: admin/ [name='hw'] gamereview [name='gamelist'] The current path, gamereview/, didn't match any of these. Here are my codes of models.py inside gamereview folder: from django.db import models from django.template.defaultfilters import slugify # Create your models here. class Tag(models.Model): label = models.CharField(max_length=20) def __str__(self): return self.label class Game(models.Model): title = models.CharField(max_length=100) developer = models.CharField(max_length=100) platform = models.CharField(max_length=50, default='null') label_tag = models.ManyToManyField(Tag) slug = models.SlugField(max_length=150, default='null') def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super().save(*args, **kwargs) class Review(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) review = models.CharField(max_length=1000) date = models.DateField(auto_now=True) slug = models.SlugField(max_length=150, default='null') def __str__(self): return self.review def save(self): super(Review, self).save() self.slug = '%i-%s' % ( self.id, slugify(self.game.title) ) super(Review, self).save() Here are my codes of urls.py inside gamereview folder: from . import views from django.urls import path urlpatterns = [ path('gamereview', views.gamelist, name='gamelist'), ] Here … -
Best practice to insure the connection and response from external API results
I have this code in python (using django firmware) that connects to an external API and update some values in that service. Each step depends on the previous step (for step 2 to work step 1 must return True and so forth that include a valid connection to the API). How can I insure that all of these steps takes place at the same time and if a single step fails how can I rollback and run all them at once in another try. here is the code. note that each class method do something in that external service. # 1. add new value to account if cls.add_balance(subscription_code, increase_amount): # 2. set new base balance if cls.set_topup_reset_action( subscription_code, new_base_balance, ): # 3. renew filters new_base_balance_20_percent = math.floor((Decimal( new_base_balance) * Decimal(20)) / Decimal(100)) if cls.set_filter_80_percent( subscription_code, new_base_balance_20_percent, ) and cls.set_filter_100_percent( subscription_code, ): # 4. renew thresholds if cls.set_threshold_profile_80_percent( subscription_code, ) and cls.set_threshold_profile_100_percent( subscription_code, ): return True return False -
creating custom or modified url using router for retrive method of ModelViewSet
I want to create a custom or modified url using router for ModelViewSet. Current scenario: /models.py class BlogPost(models.Model): title = models.CharField(max_length=300) description = models.TextField() slug = models.SlugField(max_length=300, unique=True) /serializers.py class BlogListSerializer(serializers.ModelSerializer): class Meta: model = BlogPost exclude = ('id',) /views.py class BlogViewSet(ModelViewSet): queryset = BlogPost.objects.all() serializer_class = BlogListSerializer /urls.py router = DefaultRouter() router.register(r'blog', BlogViewSet, basename='blog') urlpatterns = router.urls Now, I can access the url as below: list https://localhost:8000/blog retrieve https://localhost:8000/blog/1 As You can see that the retrieve url can be called using the pk or id. But I have created a model field called slug and its unique. My question is that how do I modify the retrieve url so that I can call the retrieve url using the slug field. For example: https://localhost:8000/blog/test-slug Note: Why do I want to create a url using slug? Answer: I want to use the urls for sitemap. -
Django static in if statement
I am trying to display either or (<img> or <h1>) if an image is retrieved from a static URL. So if this fails to load an image. {%for team in object_list|slice:":1"%} <img src="{% static "/img/Teams/" %}{{team.teamname}}.png" class="mx-auto mb-1" alt="{{team.teamname}}"> {%endfor%} I would like to display a <h1> and have none of the code above loaded. {%for team in object_list|slice:":1"%} <h1>{{team.teamname}}</h1> {%endfor%} Im really unsure about the best way to go about resolving this condition. Is it possible to use a {% if ...%} or some type of javascript? Thank you for any input. -
Positional Argument missing "status"
In Django: re_path(r'^accept_friend_request(?P<uidb64>[0-9A-Za-z_\-]+)/$', accept_friend_request, name = 'accept_friend_request') How do I add status as parameter in url pattern of string in template as well as in re_path? <a class="btn btn-primary" href="{% url 'accept_friend_request' uidb64=uid %}">Yes</a> def accept_friend_request(request, uidb64, status): uid= urlsafe_base64_decode(uidb64).decode() friend_user = User.objects.get(pk=Friend.to_user.id) f = Friend.objects.filter(friend_id = friend_user) if f: f.status=status f.save() return request, "users/friend_list.html", {"uid":uidb64, "status":status} -
Update partial serializer data
I am manually creating a model instance with Job.objects.create() but I want to use self.serializer.create() but I don't know how to add remaining partial data. Now I just want class JobCreationView(generics.CreateAPIView): queryset = Job.objects.all() serializer_class = JobCreatorSerializer def create(self, request, *args, **kwargs): rounds = RoundSerializer(data=request.data['rounds'], many=True) rounds.is_valid(raise_exception=True) eligibility = EligibilitySerializer(data=request.data['eligibility']) eligibility.is_valid(raise_exception=True) job = self.serializer_class(data=request.data['basic'], partial=True) job.is_valid(raise_exception=True) # after running all `is_valid` we confirm that there is no error data = dict(request.data) del data['rounds'] del data['eligibility'] job = Job.objects.create( **data['basic], # company can't be null company=request.user.account.company, # eligibility can't be null eligibility=eligibility.save() ) job.rounds.set(rounds.save()) return Response({ 'detail': f'Created Job {job.id}' }, status=201) I want something like this rounds = RoundSerializer(data=request.data['rounds'], many=True) rounds.is_valid(raise_exception=True) eligibility = EligibilitySerializer(data=request.data['eligibility']) eligibility.is_valid(raise_exception=True) job = self.serializer_class(data=request.data['basic'], partial=True) job.is_valid(raise_exception=True) job.validated_data['eligibility'] = eligibility.save() job.save() job.rounds.set(rounds.save()) The actual question that how to update serializer data after checking is_valid. -
How to pass kwargs from ModelAdmin to ModelForm
I have a ModelForm named MemoForm which gets passed the user from a view but I am not sure how to pass the user from the ModelAdmin to the MemoForm. MemoForm: class MemoForm(forms.ModelForm): title = forms.CharField() content = forms.CharField(widget=forms.Textarea) important = forms.CheckboxInput() receiver = forms.ModelMultipleChoiceField( queryset=None, required=True, widget=forms.CheckboxSelectMultiple ) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') # passing in the user super(MemoForm, self).__init__(*args, **kwargs) self.fields['receiver'].queryset = EmployeeType.objects.filter( casino=self.user.casino ) ModelAdmin: class CustomMemoAdmin(admin.ModelAdmin): form = MemoForm def get_form(self, request, obj=None, **kwargs): form = super().get_form(request, obj, **kwargs) if not request.user.is_superuser: self.fields = ( 'title', 'content', 'important', 'receiver', 'read', 'unread', 'word_file', ) self.filter_horizontal = ('casino',) return form(user=request.user) # passing the user through the form here. I have a couple questions: Both the view and the admin can use the same form, correct? If so, how do I pass the user to the MemoForm from the ModelAdmin? This is the error I get when I try to add a memo from the Admin panel with these settings: TypeError at /admin/memos/memo/add/ 'MemoForm' object is not callable -
Django: What is the escape() function used for?
I am trying to make a calendar in Django, and in one of the tutorials I am reading there is the following line of code: from django.utils.html import conditional_escape as esc In the Django documentation it says that conditional_escape() is ' Similar to escape(), except that it doesn't operate on pre-escaped strings'. The documentation for escape() says: 'Returns the given text with ampersands, quotes and angle brackets encoded for use in HTML'. I have found an example usage of escape(): from django.utils.html import escape escape("<strong style='font-size: 12px'>escaped html</strong>") Output: '&lt;strong style=&#39;font-size: 12px&#39;&gt;escaped html&lt;/strong&gt;' What is the purpose of the escape() function? I have searched online but all the sites just talk about what it does. I am not sure why one would want to use this function. Any insights are appreciated. -
How to pass a value coming from "POST" into excel or csv using Django
I'm trying to get a value coming from a POST method into excel or csv using xlwings, at this point I do not care much which excel library to use, here some example: <form action="{% url 'contact' %}" method="post"> {% csrf_token %} <input type="text" name="test123"> <input type="submit" value="uPLOAD"> </form> def upload(request): if request.method=='POST': file1 = request.FILES["document"] df = tabula.read_pdf(file1, lattice=True, pages='all', multiple_tables=True) #would like to pass "df" value to an excel or csv file but also display it as below return render(request, 'main.html', {"TEST2": file1.name, "content": df[1]}) else: return redirect(request, 'home.html') Either passing the value of "df" to excel-csv file, or set a button in the display page to download the value into excel-csv, any help?? -
Error happened just for the first time when connecting to a db via django
I have been trying to connect to a db via django. Here is a part of my code inside a view function: >>> from django.db import connections >>> conn = connections['example_conn'] Everything is fine until (I've truncated a little bit): >>> conn.cursor() Traceback (most recent call last): File "<console>", line 1, in <module> in cursor return self._cursor() in _cursor self.ensure_connection() in ensure_connection self.connect() in connect self.init_connection_state() in init_connection_state if self.features.is_sql_auto_is_null_enabled: in __get__ res = instance.__dict__[self.name] = self.func(instance) in is_sql_auto_is_null_enabled cursor.execute('SELECT @@SQL_AUTO_IS_NULL') in execute return super().execute(sql, params) in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) in _execute_with_wrappers return executor(sql, params, many, context) in _execute return self.cursor.execute(sql) in execute return self.cursor.execute(query, args) in execute res = self._query(query) in _query self._post_get_result() in _post_get_result self._rows = self._fetch_row(0) in _fetch_row return self._result.fetch_row(size, self._fetch_type) ValueError: invalid literal for int() with base 10: '' But something more weirder has happened: >>> conn.cursor() <django.db.backends.utils.CursorDebugWrapper object at 0x1064fb668> I have no idea why running the same command the second time would operate normally(and all other tries after the first one is fine), can anyone help me please? Note Django version: 2.2.4 Python3 version: 3.6.5 -
Django Prevent Customers From Buying A Different Paid Membership If They Currently Have One
I am having trouble figuring out the logic of my code to be able to prevent customers from buying another membership if they currently have one already (see image links below). For example, if they are paying for a Professional Membership, I do not want them to be able to click the Select button for Enterprise. If they are an Enterprise paying customer, I do not want them to be able to pay for a Professional Membership. I also do not want customers to be able to type into the address bar /memberships/payment/ payment page to be able to pay for a different membership. membership_list.html or /memberships/ url code: {% for object in object_list %} <div class="col-sm-4 col-md-4"> <h2>{{ object.membership_type }}</h2> <p>Price: ${{ object.price }}<small>/month</small></p> <h4>Included Courses</h4> <ul> {% for course in object.course_set.all %} <li>{{ course.title }}</li> {% endfor %} </ul> {% if object.membership_type != 'Free' %} <form method="POST" action="{% url 'memberships:select' %}"> {% csrf_token %} {% if object.membership_type != current_membership %} <button class="btn btn-primary">Select</button> {% else %} <small>This is your current membership</small> {% endif %} <input type="hidden" name="membership_type" value="{{ object.membership_type }}"> </form> {% endif %} </div> {% endfor %} Images: https://imgur.com/a/Io2hhOW https://imgur.com/a/K2mfY4v Views.py and models.py code: https://dpaste.de/3j53 I would … -
Django: apply validator at model level instead of column level
Let's say I have the following Django model: class PersonClub(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) club = models.ForeignKey(Club, on_delete=models.CASCADE) year = models.PositiveSmallIntegerField() class Meta: unique_together = ("person", "club", "year") I need to apply a validator at the model level that enforces this rule: A person can belong to only 3 different clubs in a given year. What's the best way to do this? I imagine my validator should look something like this, but I have no idea where to put it: from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ def validate_annual_clubs_per_person(obj): count = PersonClub.objects.filter(person=obj.person, year=obj.year).count() if count >= 3: raise ValidationError( _("%(person)s has exceeded max clubs for %(year)s"), params={"person": obj.person, "year": obj.year}, ) -
Django Forms throwing ValueError
I have two functions: create_questions and edit_questions; however, the former throws an error stating invalid literal for int() with base 10: 'create_question' while the latter just works fine. I cannot understand why this is happening because they are basically the same function. views.py def create_question(request): form = QuestionForm() if request.method == "POST": form = QuestionForm(request.POST) if form.is_valid: question = form.save(commit=False) question.author = request.user question.save() messages.success(request, "Question created successfully") return HttpResponseRedirect(reverse_lazy('questions:question_detail', kwargs={'pk': question.pk})) return render(request, 'questions/question_form.html', {'form': form}) def edit_question(request, pk): question = get_object_or_404(models.Question, pk=pk) form_class = QuestionForm form = form_class(instance=question) if request.method == "POST": form = form_class(request.POST, instance=question) if form.is_valid: form.save() messages.success(request, "Question updated successfully") return HttpResponseRedirect(reverse_lazy('questions:question_detail', kwargs={'pk': question.pk})) return render(request, 'questions/question_form.html', { 'form': form, 'question': question }) forms.py class QuestionForm(forms.ModelForm): class Meta: model = models.Question fields = [ 'title', 'body', 'tags' ] models.py class Question(models.Model): author = models.ForeignKey(Postechian, on_delete=models.CASCADE) title = models.CharField(max_length=255, default="", null=True) tags = models.ManyToManyField(Tags(), blank=True) body = models.TextField(default='') rank = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ["-created_at", "-updated_at"] def __str__(self): return self.title urls.py path('create_question/', views.create_question, name="create_question"), path('edit_question/<pk>', views.edit_question, name="edit_question"), I would appreciate any help.