Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Query @property values in ManyToMany relationships
I need to query certain fields in a ManyToMany relationship. Here is the setup; class Yacht(models.Model): name = models.CharField(max_length=50) multiplier = models.DecimalField(max_digits=5, decimal_places=3) def __str__(self): return self.name class Event(models.Model): name = models.CharField(max_length=50) yachts = models.ManyToManyField(Yacht, through='Result') def __str__(self): return self.name class Result(models.Model): yacht = models.ForeignKey(Yacht, on_delete=models.CASCADE) event = models.ForeignKey(Event, on_delete=models.CASCADE) result = models.FloatField() @property def result_adjusted(self): # returns the adjusted result based on the yacht's multiplier return self.result * self.yacht.multiplier Question: How can I query the adjusted result for a given yacht in a given event? -
How do I access read and write access to the Django project database?
I want to read and write to the Django project database, but I don't know how to do it. A piece of code what I'm trying to do: def __init__(self): self.connection = sqlite3.connect(DB_PATH, password='1234') self.cursor = self.connection.cursor() Error: sqlite3.OperationalError: unable to open database file -
django admin new user registration fails
I have created a custom user model derieved from AbstractUser but for some reason when I am creating a new user from admin, it is failing. What could be the issue. models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.db.models.fields import CharField, BooleanField # Create your models here. class User(AbstractUser): email = models.CharField(unique=True,max_length=100) company = models.CharField(max_length=100) phone = models.CharField(max_length=10) emailVerified = models.BooleanField(default=False) phoneVerified = models.BooleanField(default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email','phone'] def __str__(self): return self.email forms.py from django import forms from .models import User from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, UserChangeForm class SignUpForm(UserCreationForm): email = forms.CharField(max_length=100,required=True) phone = forms.CharField(max_length=10,required=True) company = forms.CharField(max_length=100,required=True) class Meta(UserCreationForm.Meta): model = User fields = ('username','email','password1','password2','phone','company') class LoginForm(AuthenticationForm): email = forms.CharField(max_length=100,required=True) class Meta: model = User fields = ('email','password','username') class CustomChangeForm(UserChangeForm): email = forms.CharField(max_length=100,required=True) phone = forms.CharField(max_length=10,required=True,min_length=10) company = forms.CharField(max_length=100,required=True) class Meta(UserChangeForm.Meta): model = User fields = ('username','email','phone','company') admin.py from django.contrib import admin from .models import User from .forms import SignUpForm,CustomChangeForm from django.contrib.auth.admin import UserAdmin # Register your models here. class CustomUserAdmin(UserAdmin): add_form = SignUpForm form = CustomChangeForm model = User list_display = ['email', 'username','phone','company','emailVerified','phoneVerified'] fieldsets = UserAdmin.fieldsets +( ('Additional info', {'fields': ('phone', 'company','emailVerified','phoneVerified')}), ) #this will allow to change these fields in admin module … -
Django - How to access a python global variable in multiple pages?
In one of my Django application, I use a python global variable in a Django page (page One), as follows: global abc abc = test Now what I want is, I want to access that variable from another page (page Two). How can I access that? -
Difficulty Calculating Interest in django
I have asked this questions two times before and I didn't receive a good answer. Am putting the question forward again and I hope to get help this time. I want to calculate 8 percent of the amount in investment model in every 10 days. When the user deposit with any amount 8 percent of the amount deposited will be calculated and added to the user balance in every 10 days and it will continue to roll over every ten days continually. Look at my code below and help me. Models.py class Profile(models.Model): user = models.ForeignKey(UserModel, on_delete=models.CASCADE) balance = models.DecimalField(default=Decimal(0),max_digits=24,decimal_places=4) class Investment(FieldValidationMixin, models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) amount = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) fixed_price = models.DecimalField(max_digits=7, decimal_places=2, nulll=True, blank=True) percentageee = models.DecimalField(max_digits=3, decimal_places=0, nulll=True, blank=True) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) added = models.DateTime() def percentages_in_ten_days(self): return self.amount *0.08 I want to fetch the percentage of the user investment amount here Views.py def get_percentage(self, day=10): pef_of_amount = Investment.objects.filter([x for for x in get_percentage_ten_days]).annotate(day=Sum('x')) return get_percentage def percentile(self, days=10): percent=Investment.objects.filter(self.amount*self.percentage)/100 in days return percentile #get the percentage balance of the amount invested after ten days def get_current_balance(self,percentile): total_expenses = Profile.objects.all().aggregate(Sum('balance')).annonate(percentile) return get_current_balance Can someone help me retrieve 8 percent of the amount and … -
Add new field and value to the request - Django - Django Rest Framework (viewset, serializer)
i have a endpoint in django-rest-framework and receive a object name and date. I need include user (fk_model_user) in object before save my database, how save or update including new item in body request? Viewset: class MusicStylesViewSet( mixins.ListModelMixin, mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet ): permission_classes = [permissions.AllowAny] queryset = MusicStyleModel.objects.all() serializer_class = StyleSerializer Serializer: class StyleSerializer(ModelSerializer): class Meta: model = MusicStyleModel fields = ('id', 'name', 'date', 'user') Model: class MusicStyleModel(models.Model): id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False, null=False) name = models.CharField(max_length=150, null=False, blank=False) date = models.DateTimeField(null=False, blank=False) user = models.ForeignKey( CustomUser, null=True, blank=False, on_delete=models.CASCADE ) Example - Post Request: { "name": "test", "date": "2021-05-14T15:47:06.794639-03:00" } Example - Post Response: { "id": "810ae929-2f6d-411a-8d10-77c8f613a8ac", "name": "test", "date": "2021-05-14T15:47:06.794639-03:00", "user": "c6fbbfee-2f16-49f3-b4cd-b99e05a66ea8" } "id": "810ae929-2f6d-411a-8d10-77c8f613a8ac", automatically generated in the model "user": "c6fbbfee-2f16-49f3-b4cd-b99e05a66ea8" user id request intercepted, and save -
Struggling with queries through Django M2M field
I have these models, with a M2M field from WordCloud to Source through WordCloudSouce class Source(Model): source_id = models.AutoField(primary_key=True) source_name = models.CharField(max_length=64, default="foobar") class WordCloud(Model): cloud_id = models.AutoField(primary_key=True) cloud_name = models.CharField(max_length=125, unique=True) sources = models.ManyToManyField(Source, related_name="sources", through='WordCloudSource') class WordCloudSource(Model): wordcloud_sources_id = models.AutoField(primary_key=True) wordcloud = models.ForeignKey(WordCloud, on_delete=models.CASCADE) source = models.ForeignKey(Source, on_delete=models.CASCADE) I want to construct a query that finds a wordcloud that has cloud_name='frank' and sources as a list of strings (e.g ['a', 'b'] or ['a']). I am looking for something like: WordCloud.objects.filter(cloud_name='frank', sources=['a', 'b']) but I am unclear how to write a query that traverses the sources M2M field to get a list of the associated sources for a wordcloud. I have read through the Django docs for 3.0, and it still is not making any sense to me. I got as far as WordCloud.objects.filter(cloud_name='frank', sources__source_name__in=['aa', 'bb']) But it is not correct as it returns wordclouds named frank with both sources=['aa'] and sources=['aa', 'bb'], which is not what I want. Thanks! -
How do i append an array of objects inside an array of objects
@require_http_methods(["GET"]) @login_required def get_questions(request): res = {} questions = models.Questions.objects.raw( """ SELECT SELECT Q.question_id,Q.question,Q.description,Q.qn_total_mark,QP.part_desc, QP.part_total_marks, PMA.part_model_ans,PMA.part_answer_mark,PMA.part_answer_id FROM "QUESTIONS" Q LEFT JOIN "QUESTIONS_PART" QP ON QP.question_id = Q.question_id LEFT join "PART_MODEL_ANSWER" PMA ON PMA.part_id = QP.part_id """ ) for question in questions: if question.question_id not in res: res[question.question_id] = { "key": question.question_id, "question": question.question, "description": question.description, "qn_total_mark": question.qn_total_mark, "question_parts": [ { "part_desc": question.part_desc, "part_model_ans": question.part_model_ans, "part_guided_answer":[ { "part_answer_id":question.part_answer_id, "part_model_ans": question.part_model_ans, "part_answer_mark": question.part_answer_mark, } ], "part_total_marks": question.part_total_marks, } ] } else: res[question.question_id]["question_parts"].append( { "part_desc": question.part_desc, "part_model_ans": question.part_model_ans, #part guided answer is appended in here i think "part_total_marks": question.part_total_marks, } ) return success({"res": list(res.values())}) What am i trying to do is to append the array of part_guided_answer inside question parts for use but i do not think this is a good idea, is it possible to do it like this and if so how could it be done? Also is there a better alternative for it -
Django: Exclude apps from python manage.py migrate when using multiple databases
QUESTION : How to exclude the logs migrations from the default database, when using multiple databases in Django I've found that I need to remove the app from the INSTALLED_APP. Can this be done dynamically, or is there another way to achieve this ? I am using the default database for all models in my application and I need new database Logs, for only one model (the model is in different app - logs) I successfully connected the application with the both databases. Also I am using a Router to control the operations class LogRouter: route_app_labels = {'logs'} def db_for_read(self, model, **hints): ... def db_for_write(self, model, **hints): ... def allow_migrate(self, db, app_label, model_name=None, **hints): """ Make sure the logs app only appear in the 'logs' database. """ if app_label in self.route_app_labels: return db == 'logs' if db != 'default': """ If the database is not default, do not apply the migrations to the other database. """ return False return None With allow_migrate I am faking the logs migrations in the default database which is updating the table django_migrations with the logs migration. Also with if db != 'default': """ If the database is not default, do not apply the migrations … -
Rest Framework - Many 2 Many relation, include through model fields in API
I have 2 models connected via M2M model: class Person(models.Model): name = models.CharField(max_length=30) class Group(models.Model): name = models.CharField(max_length=100) members = models.ManyToManyField(Person, through='GroupPerson', related_name='groups') class GroupPerson(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) rank = models.CharField(max_length=100', default='New') and serializers class GroupPersonSerializer(serializers.ModelSerializer): class Meta: model = GroupPerson fields = '__all__' class GroupSerializer(serializers.ModelSerializer): members = serializers.PrimaryKeyRelatedField(many=True, queryset=Person.objects.all()) class Meta: model = Group fields = '__all__' class PersonSerializer(serializers.ModelSerializer): groups = serializers.PrimaryKeyRelatedField(many=True, queryset=Group.objects.all()) class Meta: model = Person fields = '__all__' And API go get a group returns [ { "name": "...", "members": [ IDs of all members ] } ] How do I get a response something like following: [ { "name": "...", "members": [ { "group_id": 1, "person_id": 1, "rank": "New" }] } ] I.e., I want to GET/POST/PATCH all fields of the through relation -
Blocking non ajax requests to API. Django. DRF
I have a decorator which allows only ajax requests to endpoints. AJAX_ONLY = os.getenv('AJAX_ONLY', 'False') == 'True' def only_ajax(): def wrapper(func): def decorator(request, *args, **kwargs): if not request.is_ajax() and AJAX_ONLY: return HttpResponseForbidden() return func(request, *args, **kwargs) return decorator return wrapper Then I use it as a method_decorator in controllers: @method_decorator(only_ajax(), name='dispatch') class SomeEndpoint(APIView): ... And it works perfectly good on localhost returning 403. But on the live servers it simply suggests user to log in displaying default DRF browsable api page afterwards. What am I missing? Thanks. -
'MovieViewSet' should either include a `serializer_class` attribute, or override the `get_serializer_class()` method
I am trying to build a project from a Youtube tutorial but I keep getting this error: AssertionError: 'MovieViewSet' should either include a `serializer_class` attribute, or override the `get_serializer_class()` method. Here is the views.py file class MovieViewSet(viewsets.ModelViewSet): queryset = Movie.objects.all() serializer_class = MovieSerializer def list(self, request, *args, **kwargs): movies = Movie.objects.all() serializer = MovieSerializer(movies, many=True) return Response(serializer.data) Also this is the serializer.py file: class MovieSerializer(serializers.ModelSerializer): class Meta: model = Movie fields = ('id', 'title', 'desc', 'year') What am I doing wrong? Because to me it looks like I am using serializers_class ... Thank you in advance! -
Query database in django based on specific foreignKey
please I'm having issue query database to get all the registered students under specific teacher Model.py class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.CharField(max_length=500, blank= True) teacher = 'teacher' admin = 'admin' user_types = [ (teacher, 'teacher'), (admin, 'admin'), ] user_type = models.CharField(max_length=10, choices=user_types, default=admin) def __str__(self): return self.user.username Student model.py class Student(models.Model): userprofile = models.ForeignKey(UserProfileInfo, on_delete=models.CASCADE, related_name='myuser') first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) profile_pic = models.ImageField(upload_to=student_image, verbose_name="ProfilePicture", blank=True) guardian_email = models.EmailField() guardian_phone = models.IntegerField() def __str__(self): return self.first_name I have registered some students on each teacher in the database. But whenever I queried the database to list all the students under specific a teacher, I got the list of the students in the database instead Here the views.py class StudentListView(ListView): template_name = 'data/student_lis.html' queryset = Student.objects.all().order_by("first_name") model= Student Student_list .html {% for instance in object_list %} <li><a href="{{ instance.get_absolute_url }} ">{{ forloop.counter }} - {{ instance.first_name }} {{ instance.last_name }}</a></li> {% endfor %} Thanks you all -
How to add a default filter inside Django FilterSet?
The Problem: I am trying to add an initial filter that gives a base queryset for other filters to further filter on. Things I've Tried: I tried overriding the qs property method, but overriding the qs made other filters unfunctional. I also tried to override the __init__ method but it was not called in my custom filter class. -
Realtime updates from Realtime Firebase database of HTML page with Ajax
I need to get live updates(lat and lng of the point) from Firebase realtime database for my django web project. I found this question on stackoverflow here: Realtime Update between Firebase and HTML Table. So I did the same in my code with replacing config of my firebase. But it did not work, cause I get such error: [Error][1] What can be the problem? [1]: https://i.stack.imgur.com/EtE3y.png HTML code: <html> <head> </head> <body > <table style="width:100%;width:100%;" id="ex-table"> <tr id="tr"> <th>Latitude/th> <th>Longitude</th> </table> <script src="https://www.gstatic.com/firebasejs/4.1.3/firebase.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script> // Initialize Firebase var config = { apiKey: "AIzaSyCEXETuWBXNzA0dTd0uSMOWmJjYORARn5Q", authDomain: "tracker-14.firebaseapp.com", databaseURL: "https://tracker-14-default-rtdb.europe-west1.firebaseio.com", projectId: "tracker-14", storageBucket: "tracker-14.appspot.com", messagingSenderId: "374752080087" }; firebase.initializeApp(config); var database = firebase.database(); database.ref().once('value', function(snapshot){ if(snapshot.exists()){ var content = ''; snapshot.forEach(function(data){ var val = data.val(); content +='<tr>'; content += '<td>' + val.lat + '</td>'; content += '<td>' + val.lng + '</td>'; content += '</tr>'; }); $('#ex-table').append(content); } }); </script> </body> </html> -
python django migrate エラー [closed]
django を始めたばかりでつまずいてしまいました。 ModuleNotFoundError: No module named 'widget_tewaks'と エラーが出ていたので pip3 install django-widgets-improved を実行 sttingsの確認(widget_tewaksを入れ忘れていないか)を行ったが記述されていた。 対処法がわかる方はアドバイスをお願いいたします。 (myvenv) (base) inoMacBook-Air:django irikunin$ python3 manage.py makemigrations Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/irikunin/Desktop/django/myvenv/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/Users/irikunin/Desktop/django/myvenv/lib/python3.8/site-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/Users/irikunin/Desktop/django/myvenv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/irikunin/Desktop/django/myvenv/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/irikunin/Desktop/django/myvenv/lib/python3.8/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/opt/anaconda3/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'widget_tewaks' -
How to set read_only dynamically in django rest framework?
I am trying to check if the user id not equal to 1 then he should not be able to update few fields. I tried something similar to the following code but it did not work because of the following issues self.user.id don't actually return the user I need to get the authenticated user in different why? the def function maybe should have a different name like update? also the general way maybe wrong? class ForAdmins(serializers.ModelSerializer)): class Meta: model = User fields = '__all__' class ForUsers(serializers.ModelSerializer)): class Meta: read_only_fields = ['email','is_role_veryfied','is_email_veryfied'] model = User fields = '__all__' class UsersSerializer(QueryFieldsMixin, serializers.ModelSerializer): def customize_read_only(self, instance, validated_data): if (self.user.id==1): return ForAdmins else: return ForUsers class Meta: # read_only_fields = ['username'] model = User fields = '__all__' -
How to add poll code to the django-cms url.py file?
I am new to Django-cms but I couldn't add the poll url code to the url.py file. I follow every step in the Django-cms documentation but I still couldn't succeed can anyone help me with it. This the documentation of the Django-cms: integrating_applications Install the application from its GitHub repository using pip: pip install git+http://git@github.com/divio/django-polls.git#egg=polls Let’s add this application to our project. Add 'polls' to the end of INSTALLED_APPS in your project’s settings.py (see the note on The INSTALLED_APPS setting about ordering ). Add the poll URL configuration to urlpatterns in the project’s urls.py: urlpatterns += i18n_patterns( re_path(r'^admin/', include(admin.site.urls)), re_path(r'^polls/', include('polls.urls')), re_path(r'^', include('cms.urls')), ) Note that it must be included before the line for the django CMS URLs. django CMS’s URL pattern needs to be last, because it “swallows up” anything that hasn’t already been matched by a previous pattern. I had added the "polls" in the setting into the installation app code. But--- My question is where or how will put this code to the urls.py file. -- my urls.py file looks like this: from cms.sitemaps import CMSSitemap from django.conf import settings from django.conf.urls.i18n import i18n_patterns from django.conf.urls.static import static from django.contrib import admin from django.contrib.sitemaps.views import sitemap from … -
Error "Reverse for 'login' not found" when creating url path in Django
I'm new to Django, and today when I tried to publish my Django application to Heroku, I always encountered an error Reverse for 'login' not found. 'login' is not a valid view function or pattern name. I know where I'm wrong. The problem came in urls.py, so here is my code: urlpatterns = [ path('', include('users.urls', 'login')), path('admin/', admin.site.urls), path('jet/', include('jet.urls', 'jet')), path('citizens/', include('citizens.urls', namespace='citizens')), path('users/', include('users.urls', namespace='users')), #path('accounts/', include('django.contrib.auth.urls')), ] Here is my urls.py inside users: from django.urls import path from . import views app_name = 'users' urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), ] In my project, the login page stay at URL "127.0.0.1:8000/users/login". It means when you typed only "127.0.0.1:8000/users", the page will notice an error: Reverse for 'login' not found. 'login' is not a valid view function or pattern name. I want my path will directly go to users/login, but I don't know how to do it. I have tried path('', include('users.urls', 'login')), or path('', include('users.urls/login', namespace='user')), or path('', include('users.urls.login', namespace='user')), but nothing works. Thank you. -
Function calls in Django model class using data from other model class
I have two model classes and I need to write some logic that uses both. Not sure where I should be adding this logic, and how to implement. This is a highly simplified version; class Yacth(models.Model): name = models.CharField(max_length=50) adjuster = models.IntegerField(default=1) class Result(models.Model): yacht = models.ForeignKey(Yacht, on_delete=models.CASCADE) result = models.DecimalField(null=TRUE) adjusted_result = # I want to populate this field with adjusted result def result_adjusted(self): a = self.result b= self.yacht.adjuster # can I call values from another class like this? adjusted_result = (a * b) return adjusted_result I need the result to be multiplied by the adjuster as shown in the simple draft method (result_adjusted) above. How can I implement this so that the adjusted result in the model class is populated with the method return? Thank you -
Custom Form ValidationErrors render differently than those rendered by Django
Referring to the image below, I have a hard time figuring out from resources and Django's source code on why the ValidationError we raise our own (from our own cleaning/validation) are rendered differently from ValidationErrors rendered by the form (Django) itself. Field ValidationErrors raised by Django are rendered in a 'floating bubble' while ValidationErrors I raised are rendered as red text. The method I used to raise ValidationErrors are as per Django's documentation here, while how I render the form in the template is simply by calling {{form}} as provided by Django's Template engine - albeit by also using crispy but I've verified that it has no effect here other than styling the error message to be red in colour instead of a plain, bold black text under the field. Ideally, I would like to know how or what I should do in order to make all ValidationError (Django's default and my own) display uniformly to prevent inconsistent design across fields in a form. Preferably, as red text. Any help I can get are much appreciated! Image of the errors in the form ValidationError Forms class AbstractUserForm(forms.ModelForm): mail = forms.EmailField() mobile = forms.CharField( widget=forms.NumberInput, required=True ) class Meta: model = … -
Stripe Payouts Django
I have already implemented payouts in my django project using PayPal but now I want to switch to stripe Payouts. Stripe documentation is now helping me in programmatical terms. -
Editing data via post request in join table model in Django
I have created model with many to many relationship and I have join table when I keep additional variable for it: class BorderStatus(models.Model): STATUS_CHOICES = [("OP", "OPEN"), ("SEMI", "CAUTION"), ("CLOSED", "CLOSED")] origin_country = models.ForeignKey(OriginCountry, on_delete=models.CASCADE, default="0") destination = models.ForeignKey(Country, on_delete=models.CASCADE, default="0") status = models.CharField(max_length=6, choices=STATUS_CHOICES, default="CLOSED") extra = 1 class Meta: unique_together = [("destination", "origin_country")] verbose_name_plural = "Border Statuses" def __str__(self): return ( f"{self.origin_country.origin_country.name} -> {self.destination.name}" f" ({self.status})" ) Other models: # Create your models here. class Country(models.Model): name = models.CharField(max_length=100, unique=True, verbose_name='Country') class Meta: verbose_name_plural = "Countries" def __str__(self): return self.name class OriginCountry(models.Model): origin_country = models.ForeignKey( Country, related_name="origins", on_delete=models.CASCADE ) destinations = models.ManyToManyField( Country, related_name="destinations", through="BorderStatus" ) class Meta: verbose_name_plural = "Origin Countries" def __str__(self): return self.origin_country.name Im trying to send post request based on the origin_country and destination so that I can change status of the given combination: Here is my serializer for the endpoint: class BorderStatusEditorSerializer(serializers.ModelSerializer): """Create serializer for editing single connection based on origin and destination name- to change status""" origin_country = serializers.StringRelatedField(read_only=True) destination = serializers.StringRelatedField(read_only=True) class Meta: model = BorderStatus fields = ('origin_country', 'destination', 'status') And my endpoint: class BorderStatusViewSet(viewsets.ModelViewSet): queryset = BorderStatus.objects.all() serializer_class = BorderStatusEditorSerializer filter_backends = (DjangoFilterBackend,) filter_fields=('origin_country','destination') so when I send request … -
field Error message showing different from intended
Hello im trying to make my form show validation errors but its keeps showing 'this field is required' instead of 'this email has already been registered' etc. any suggestions will help thanks. my form: class NewCustomer(UserCreationForm): class Meta: model = Customer fields = ('Email_Address','Phone_number','first_name','last_name') #tried the cleaned data option below but it didnt work def clean(self): cleaned_data = super().clean() Email_Address = cleaned_data.get("Email_Address") Phone_number = cleaned_data.get("Phone_number") first_name = cleaned_data.get("first_name") last_name = cleaned_data.get("last_name") My views: class SignUpView(CreateView): form_class = NewCustomer success_url = reverse_lazy('store:user_login') template_name = 'store/signup.html' -
I resized the field, but now instead of tag names I see a list with dictionaries
I resized the field, but now instead of tag names I see a list with dictionaries. How i can fix it? formfield_overrides = { TaggableManager: {'widget': AdminTextareaWidget(attrs={'rows': 4, 'cols': 40})}, }