Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create object within nested serializer on API create call
I have an API with nested serializers where I overwrote the create method. My nested serializer has Foreign Keys to another model. Now I want to create objects of this other model in the same API call. This is where I am stuck. My data looks like so: [ { "project": "project1", "name": "Graph1", "description": "testdescription", "nodes": [ { "id": 16, "name": "target1", "graph": 49 }, { "id": 15, "name": "Node1", "graph": 49 } ], "edges": [ { "id": 14, "name": "Edge1", "graph": 49, "source": 15, "target": 16 } ] } ] The fields source and target are Foreign Keys to the model Node. Now, I can send this data without a problem when the fields source and target are already existent in the database. But what I want is, that I send the data and I create a new Node object (source) and a new Node object (target) in the same call. So far I overwrote the create method to enable nested serialization like so: class GraphSerializer(serializers.ModelSerializer): nodes = NodeSerializer(many=True) edges = EdgeSerializer(many=True) class Meta: model = Graph fields = ('project', 'name', 'description', 'nodes', 'edges', ) def create(self, validated_data): nodes_data = validated_data.pop('nodes') edges_data = validated_data.pop('edges') graph = Graph.objects.create(**validated_data) for … -
django-intl-tel-input returns 404 error in the terminal?
I'm using Django-intl-tel-input to make a widget in the user sign up page to choose the phone number format/country but the widget doesn't appear in the page and the terminal gives the following error : Not Found: /accounts/signup/”https: //code.jquery.com/ui/1.12.1/jquery-ui.js” Not Found: /accounts/signup/”https://code.jquery.com/jquery-1.12.4.js” Not Found: /accounts/signup/<link href= [29/Jul/2019 14:10:52] "GET /accounts/signup/%E2%80%9Dhttps://code.jquery.com/jquery-1.12.4.js%E2%80%9D HTTP/1.1" 404 5475 Not Found: /accounts/signup/<script type= [29/Jul/2019 14:10:52] "GET /accounts/signup/%E2%80%9Dhttps://code.jquery.com/ui/1.12.1/jquery-ui.js%E2%80%9D HTTP/1.1" 404 5493 [29/Jul/2019 14:10:52] "GET /accounts/signup/%3Clink%20href= HTTP/1.1" 404 5370 [29/Jul/2019 14:10:52] "GET /accounts/signup/%3Cscript%20type= HTTP/1.1" 404 5376 Not Found: /accounts/signup/”https://code.jquery.com/jquery-1.12.4.js” [29/Jul/2019 14:10:53] "GET /accounts/signup/%E2%80%9Dhttps://code.jquery.com/jquery-1.12.4.js%E2%80%9D HTTP/1.1" 404 5475 Not Found: /accounts/signup/”https://code.jquery.com/ui/1.12.1/jquery-ui.js” [29/Jul/2019 14:10:53] "GET /accounts/signup/%E2%80%9Dhttps://code.jquery.com/ui/1.12.1/jquery -ui.js%E2%80%9D HTTP/1.1" 404 5493 I didn't load/call any CSS or js files in this template {%load staticfiles %} {% block content %} <head>> <link href="{{ form.media.css }}" rel="stylesheet"> </head> <style> #content{ margin-top : 4%; margin-left : 18%; margin-right : 2%; margin-bottom : 6%; } </style> <div id="content"> <h2>Sign up</h2> <form method="POST" action="{% url 'accounts:signup' %}"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary">Sign up</button> <p></p> </form> </div> <script src="{{ form.media.js }}"></script> <script> jQuery(document).ready( {{ form.media.js }} ); </script> {% endblock %} and my form : class SignupForm(UserCreationForm): Telephone_num = forms.CharField(label='Phone Number', widget= IntlTelInputWidget()) class Meta(UserCreationForm.Meta): model = MyUser fields = ('first_name', 'last_name', 'email', … -
Validation error on empty forms using CreateView and modelformset
I use forms and want to avoid filling out all forms on the page, but my code only works if all forms are filled in. If I send some forms empty, I get an error The view base.views.SkillTestCreateView didn't return an HttpResponse object. It returned None instead. views.py class SkillTestCreateView(AuthorizedMixin, CreateView): model = Skill form_class = SkillCreateForm template_name = 'skill_create.html' def get_context_data(self, **kwargs): context = super(SkillTestCreateView, self).get_context_data(**kwargs) context['formset_framework'] = SkillFrameworkFormSet() context['formset_planguage'] = SkillPLanguageFormSet() return context def post(self, request, *args, **kwargs): if 'framework' in request.POST: form = SkillFrameworkFormSet(self.request.POST) if form.is_valid(): return self.form_valid(form) elif 'language' in request.POST: form = SkillPLanguageFormSet(self.request.POST) if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(self.form) def form_valid(self, form): """If the form is valid, redirect to the supplied URL.""" print('valod') for form in form: self.object = form.save(commit=False) self.object.employee =Employee.objects.get(pk=self.kwargs['pk']) self.object.save() return redirect("profile", pk=self.kwargs['pk']) def form_invalid(self, form): print('Invalid') return self.render_to_response(self.get_context_data(formset_framework=self.form, formset_planguage=self.form)) How do I allow acceptance of empty forms? -
Django - How To Use Form In Footer
Previously, I had my 'subscribe to newsletter' form on the home page (index.html). However, I moved it to the footer.html in order for it to be shown on every page. The issue is that since the logic to deal with the form is only in the home view, submitting to the form only works on the home page. Here is some code to help you understand: This is in footer.html which is included in base.html which is extended by all other htmls <form class="nwsltr-primary-1" action="." method="POST"> <!-- . means current URL we are on --> {% csrf_token %} <input type="email" name="email" id="email" placeholder="Your email"/> <button type="submit"><i class="ion-ios-paperplane"></i></button> </form> This is what I think needs to change. This is the view for the home page and the only place the logic for the form is being seen: def index(request): # featured and object_list get all Posts with featured bool true. order_by=latest first. :6=first 6 featured = Post.objects.filter(featured=True).order_by('-share_count')[:6] latest = Post.objects.order_by('-timestamp')[:5] popular = Post.objects.order_by("-share_count")[:4] # Basic but does not do any verification if request.method == "POST": email = request.POST["email"] new_signup = Signup() new_signup.email = email new_signup.save() context = { 'object_list': featured, 'latest': latest, 'popular': popular } return render(request, 'index.html', context) # html … -
Circular dependency created by serializer
When importing a serializer into my model the model cannot be imported anymore so I suspect there is a circular dependency. When not importing the serializer everything goes smoothly but when importing it everything breaks. This works from shift.models import Shift class ShiftChangeRequest(models.Model): shift = models.ForeignKey(Shift, on_delete=models.CASCADE, null=True) And this does not: from shift.models import Shift from shift.serializers.base import BaseSerializer class ShiftChangeRequest(models.Model): shift = models.ForeignKey(Shift, on_delete=models.CASCADE, null=True) As you can see the ShiftChangeRequest does have a connection with shift but in the BaseSerializer ShiftChangeRequest is not even mentioned: from rest_framework import serializers from shift import models class BaseSerializer(serializers.ModelSerializer): class Meta: model = models.Shift fields = [ "id", "title", "start", "end", "amount_of_minutes", "amount_of_employees", "client", "skills", "users", "repeat_at", ] I expected that everything worked as before the import but I get the error ImportError: cannot import name 'ShiftChangeRequest' -
How to exclude the field which it is the foreign key to the parent model
How can I exclude the credit field from CreditInlineAdmin. In this case I get error: : (admin.E201) Cannot exclude the field 'credit', because it is the foreign key to the parent model 'credits.Credit'. models.py class AbstractBaseAction(models.Model): name = models.CharField(_('name'), max_length=255) short_description = models.CharField(_('short description'), max_length=255) full_description = models.TextField(_('full description'), blank=True, null=True) class Meta: abstract = True class CreditAction(AbstractBaseAction): credit = models.ForeignKey(Credit, verbose_name=_('credit')) admin.py class BaseActionInlineAdmin(admin.StackedInline): model = AbstractBaseAction extra = 0 max_num = 2 class CreditActionInlineAdmin(BaseActionInlineAdmin): exclude = ('credit',) model = CreditAction class CreditAdmin(BaseCreditAdmin): inlines = [CreditActionInlineAdmin] -
Django 2 Saving models.FileField manualy in forms.py
My code is: Models.py class Claimmessage(models.Model): text = models.TextField(_('Сообщение'),) class Claimfile(models.Model): claimmessage = models.ForeignKey(Claimmessage, on_delete=models.CASCADE, verbose_name=_('Сообщение рекламации'), ) attachment = models.FileField(upload_to='claims/%Y/%m/%d/', blank=True, null=True,) forms.py class ClaimCreateForm( forms.Form ): message = forms.CharField(widget=forms.Textarea,) attachments = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) def save(self, commit=False): message = self.cleaned_data.get("message") attachments = self.cleaned_data.get("attachments") mess = Claimmessage() mess.text = message mess.save() for f in attachments: Claimfile. objects.create(claimmessage=message, attachment=f) views.py if request.method == 'POST': form = ClaimCreateForm(request.POST, request.FILES,) if form.is_valid(): obj = form.save() return redirect('claim_details', claim_id=obj.pk) else: form = ClaimCreateForm() And I ve got AttributeError at /ru/claims/400002013/create/ 'bytes' object has no attribute '_committed' How can I save file object in form.save() method? -
Use autocomplete_fields with Proxy model
I want to implement autocomplete_fields feature but it doesn't work. I assume it happens because of Proxy model. So I have Customer Proxy model and PromoCode model. PromoCode has FK to Customer model. And I need to have search field for customers in PromoCode change form. Here are models and admin classes: class User(AbstractUser): # bunch of fields class Customer(User): class Meta: proxy = True class CustomerAdmin(admin.ModelAdmin): search_fields = ['email',] admin.site.register(Customer, CustomerAdmin) class PromoCode(TimeStampedModel): customer = models.ForeignKey(User, on_delete=PROTECT, null=True, blank=True) class PromoCodeAdmin(admin.ModelAdmin): autocomplete_fields = ('customer',) admin.site.register(PromoCode, PromoCodeAdmin) This code gives error: : (admin.E039) An admin for model "User" has to be registered to be referenced by PromoCodeAdmin.autocomplete_fields. But I can't change model in customer field to Customer, becase when I run migration it breaks with following error: ValueError: The field coupons.PromoCode.customer was declared with a lazy reference to 'users.customer', but app 'users' doesn't provide model 'customer' Also I can't register User as admin class, because I don't need it to be registered. I register Customer model. What can I do to solve such case? -
Django : null value in column "id" violates not-null constraint(Issue is at admin)
On addidng the data from admin panel in django , on adding the records , the postgresql is throwing the error as primary key is getting the null value.As it must be auto incremented. Please let me know how to fix this issue and why it may be persisting . As previously , this issue got fixed automatically. -
Getting Bad request 400 when testing API create method
I am trying to test an API with pytest. I am getting a bad request 400 where I'd expect a status code 201. There must be some error in how I set up the test data but I can't figure out where. this is the data I am trying to send graph_data = { "project": "project1", "name": "Graph1", "nodes": [ { "name": "Node1 of Graph 1", "graph": 1 } ], "edges": [ { "name": "EdgeForGraph1", "graph": 1, "source": 1, "target": 1 } ] } And here my test: @pytest.mark.django_db class TestCreate: def setup(self): """Setup for tests to create user, graph, project and node """ password = 'mypassword' username = 'testuser' project = Project.objects.create(project_name='project1') graph = Graph.objects.create(project=project, name='Graph1') node = Node.objects.create(graph=graph, name='node of Graph') source = Node.objects.create(graph=graph) target = Node.objects.create(graph=graph) user = User.objects.create_superuser(username=username, email='test@test.com', password=password) edge = Edge.objects.create(graph=graph, source=source, target=target) def test_aut_user_can_create_graph(self, client): headers = get_token(client) print(headers) create_data = graph_data print(create_data) url = api_reverse('create-graph') response = client.post(url, create_data, headers=headers) assert response.status_code == 201 the get_token method returns a token that I use to authenticate. Here are my models: class Graph(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) name = models.CharField(max_length=120, blank=True) description = models.CharField(max_length=400, blank=True) def __str__(self): return self.name @property def nodes(self): return self.node_set.all() … -
multilingual site: how create clean relationship between "static" texts (coded into templates) and database?
On a multilingual (manually translated) website appropriate translations of products or newspaper-articles are pulled out according to user (or user-selected) language. But what about all those annoying "static" texts that ordinarily get coded directly into a template? Perhaps "opening hours" or "contact us"? Obviously these need to exist in various translations (and therefore in the database), my question is how to develop clearly the relationship between database entry and code? So far was thinking of the following: MODELS Language name Article article_title article_slug Translation article =models.ForeignKey(Article) language =models.ForeignKey(Language) title_text article_text VIEWS def page12view(request) article = article.objects.get(slug=friendly-name-of-article) query = Translation.objects.filter(article=article).filter(language=request.user.language) if not query.first(): #if translation not available in user’s language default to ENGLISH (pk=1) query = Translation.objects.filter(article=article).filter(language=1) context = { ‘friendly-name-of-article’: query.first()} return render (request,’page12.html', context) TEMPLATE {{friendly-name-of-article.title_text}} {{friendly-name-of-article.article_text}} The idea revolves around giving each article a slug (referred to in above example as "friendly-name-of-article"). Thus "about-us", "opening-hours"etc.. That string would be copy-pasted in the view and template as suggested in the code. The idea is that it would at least bring some clarity as to what is going on. But is it a good idea? Have my doubts... Any good practices to share? -
nginx upstream prematurely closed connection on Django on the server
I have a Django 2.x application and separated API and admin urls using Django_hosts plugin. I have the following nginx configuration to serve the two URLs upstream app_server { server localhost:8000; } server { listen 80; server_name api.staging.example.io admin.staging.example.io; access_log /etc/nginx/log/local-wc.access.log; error_log /etc/nginx/log/local-wc.error.log; location / { proxy_http_version 1.1; proxy_pass http://app_server/; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Protocol $scheme; proxy_temp_file_write_size 64k; proxy_connect_timeout 10080s; proxy_send_timeout 10080; proxy_read_timeout 10080; proxy_buffer_size 64k; proxy_buffers 16 32k; proxy_busy_buffers_size 64k; proxy_request_buffering off; proxy_buffering off; } listen 443 ssl; # managed by Certbot ssl_certificate ... } I have configured boto3 to upload files to S3 using django-storages plugin. When I visit htts://admin.staging.example.com and create a model record and uploads the file, the file is being saved to S3 bucket but within a few seconds the gives 502 page. The nginx error log have [error] 9566#9566: *1 upstream prematurely closed connection while reading response header from upstream, client: 13.233.000.90, server: api.staging.example.io, request: "POST /myapp/view/add/ HTTP/1.1", upstream: "http://127.0.0.1:8000/myapp/view/add/", host: "admin.staging.example.io", referrer: "https://admin.staging.example.io/myapp/view/add/" I tried configurations from the other answers with a similar title but none of them is working. Creating an object without uploading file is working fine. -
Display Algolia Results with Jinja / Django
I have got Algolia all set up with Django and the results are displaying. However, when I move on to formatting them there is a clash with the Jinja templating engine. Essentially Algolia uses the double parentheses like Jinja {{ value }} In the script below the {{ highlightResult.name }} cause a error How do I render the results of the search without using the double parentheses? Thanks! <script> const searchClient = algoliasearch('xxx', 'xxx'); const search = instantsearch({ indexName: 'Item', searchClient, }); console.log(search) search.addWidget( instantsearch.widgets.searchBox({ container: '#searchbox', }) ); search.addWidget( instantsearch.widgets.hits({ container: '#hits', templates: { item: ` <div> {{ highlightResult.name }} </div> `, }, }) ); search.start(); </script> -
how to send data from the view to the template
how to send data from django views into the template in order to display the data stored in database. i have a function that insert data into a model and what i need is to retrieve the inserted data and display in template until now i tried this code but it did not display anything. Note i am sure that is correct but i do not know why its not displayed. views.py dbFolder = Folder.objects.create(folder_num = FolderNum, title = FolderTitle,date_on_folder = DateInFolder, folder_type = Type, content_folder = Content) dbFolder.save() print("dbfolder = ", dbFolder.id) print("title====", dbFolder.title) update2.html <h1>{{dbfolder.title}}</h1> Note its printed the values in the cmd. -
Django ValueError - not enough values to unpack (expected 2, got 1) list of tuples error
This is what is causing the error, I know that much: forms.py file: class CustomSignupForm(UserCreationForm): ENGLISH_INTEREST = EnglishInterest.get_english_interest_data() english_interest = forms.MultipleChoiceField(choices=ENGLISH_INTEREST, widget=forms.CheckboxSelectMultiple()) models.py file: class EnglishInterest(models.Model): english_interest = models.CharField(max_length=255) def get_english_interest_data(): return EnglishInterest.objects.values_list('english_interest') I know there must be some simple solution to get this multiple choice field to work. It does work if I were to use instead: ENGLISH_INTEREST= [ ('general speaking', 'General Speaking'), ('work opportunities', 'Work Opportunities'), ('travel', 'Travel'), ('study abroad', 'Study Abroad'), ] -
DRF Token Authentication: { "detail": "Authentication credentials were not provided." }
I am working on a Django e-commerce project. I tried to implement a token authentication system. I added rest_framework.authtokento INSTALLED_APPS and REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } to settings file. Here's my urls.py path('admin/', admin.site.urls), path('login_signup/',include('login_signup.urls')), path('profile',include('profile_info.urls')), path('',include('category.urls')), path('cart',include('cart.urls')), path('api_token_auth',views.obtain_auth_token,name='auth-token'), ] I am able to obtain tokens by providing username and password at api_token_auth end point. Now, I should be able to access any API provided I add Authorization HTTP header in this format. Authorization:Token "xyz" But I keep getting {"detail":"Authentication credentials were not provided"} Here is the view I am trying to access. class SubcategoryView(APIView): def get(self,request): serializer=SubcategorySerializer(Subcategory.objects.all(),many=True) return JsonResponse({"subcategories":serializer.data}) Why do I keep getting this error? What am I doing wrong? -
Accesing django jinja authenticated user in angularjs
I would like to access authenticated user in angularjs. How can I do that ? Also I can access jinja user in my index.html but when I try to access user in angularjs state templateUrl's html file, it does not work.? Thanks for any help. -
How querry a class with custom __init__
I save my model's class into database and now trying to querry it by using default manager's method .objects.all(). And got an error: __init__() takes 2 positional arguments but 3 were given Here is my model: class BaseCrudEntity(models.Model): pass class Meta: abstract = True class BaseListViewPreset(BaseCrudEntity): RelativeClass = models.CharField(max_length = 255, null = True) def __init__(self, context): BaseCrudEntity.__init__(self) self.model = context self.columns = [] #self.setColumns(self.model) self.RelativeClass = ".".join([context.__module__, context.__name__]) def addColumn(self, prop): _column = Column(system_name = prop.name, Preset = self) self.columns.append(_column) def setColumns(self, context): _props = context._meta.get_fields() for prop in _props: self.addColumn(prop) class Column(models.Model): system_name = models.CharField(max_length = 255) lookup_name = models.CharField(max_length = 255) Preset = models.ForeignKey(BaseListViewPreset, on_delete = models.CASCADE) I have a record in database for Preset and several records for its columns. The error i receive when calling BaseListViewPreset.objects.all() I try to comment the init inside preset class and it helps me to querry it. But I need init for initializing. So how can I solve this problem? The traceback is here: http://dpaste.com/15449TR Thanks for any help -
How to pass custom data to a django template?
I like to pass some custom data to a template in django admin. How do I access myData in the sample below? class MyAdmin(admin.ModelAdmin): def get_object(self, request, object_id, form_field=None): obj = super().get_object(request, object_id, form_field) self.myData = MyModel.objects.filer(id=obj.myData_ID) return obj In the template: {% for p in myData %} <p>{{p}}</p> {% endfor %} -
How to Read the Barcode in image using Python 3.6 without using Zbar
I am New to Barcode Reader i found some Tutorial about Zbar and which seems to not support in ZBAR. I like to raed the Barcode in a Image and extract the Data in it. This is What is Actually Tried. def detect_barcode(request): try: import pyqrcode import zbarlight qr = pyqrcode.create("HORN O.K. PLEASE.") qr.png("download.png", scale=6) import qrtools from qrtools.qrtools import QR from qrtools.qrtools import Image,BOM_UTF8 qr = qrtools.QR() qr.decode("download.png") True print(qr.data); qr.data except Exception as e: test = str(e) def detect_barcode(request): try: import pyqrcode import zbarlight qr = pyqrcode.create("HORN O.K. PLEASE.") qr.png("download.png", scale=6) import qrtools from qrtools.qrtools import QR from qrtools.qrtools import Image,BOM_UTF8 qr = qrtools.QR() qr.decode("download.png") True print(qr.data); qr.data except Exception as e: test = str(e) I Need to Decode the Barcode and extract the Data. I don't like to use Zbar. -
How to add user in admin page after downgrading the django version to 2.1.3?
I have a problem in making new user in admin page in django but whenever I add user in admin page in django version 2.2.3, it gives me NotImplementedError but when I downgraded it to 2.1.3, it gave me another error in command prompt. Now the browser page is not loading anything. I also equaled uses_savepoints = True which is by default False NotImplementedError at /admin/auth/user/add/ UNKNOWN command not implemented for SQL SAVEPOINT "s6856_x1" C:\Users\Bilal\Envs\trial\lib\site-packages\djongo\sql2mongo\query.py in parse handler = self.FUNC_MAP[sm_type] Error after downgrading to 2.1.3 django version File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run self.check_migrations() File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\core\management\base.py", line 442, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__ self.build_graph() File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\db\migrations\loader.py", line 273, in build_graph raise exc File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\db\migrations\loader.py", line 247, in build_graph self.graph.validate_consistency() File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\db\migrations\graph.py", line 243, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\db\migrations\graph.py", line 243, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "C:\Users\Bilal\Envs\trial\lib\site-packages\django\db\migrations\graph.py", line 96, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration auth.0012_auto_20190724_1222 dependencies reference nonexistent parent node ('auth', '0011_update_proxy_permissions') -
How to implement autocomplete_fields with Proxy model?
I want to implement autocomplete_fields feature but it doesn't work. I assume it happens because of Proxy model. So I have Customer Proxy model and PromoCode model. PromoCode has FK to Customer model. And I need to have search field for customers in PromoCode change form. Here are models and admin classes: class Customer(User): # User is a class based on django.contrib.auth.models.AbstractUser class class Meta: proxy = True class CustomerAdmin(admin.ModelAdmin): search_fields = ['email',] admin.site.register(Customer, CustomerAdmin) class PromoCode(TimeStampedModel): customer = models.ForeignKey(Customer, on_delete=PROTECT, null=True, blank=True) class PromoCodeAdmin(admin.ModelAdmin): autocomplete_fields = ('customer',) admin.site.register(PromoCode, PromoCodeAdmin) There are no errors but Customer field is still default Select input without desired filter. What I am doing wrong and how to properly implement autocomplete_fields here? p.s. python_version = "3.6" Django = "==2.2.3" -
Django Inlineformsets - Custom validation with django-extra-views
So I have a question about the form_valid for django-extra-views. I used the CreateWithInlinesView method to create a form with multiple inline formsets. The base form called "Order" contains two different formsets, "Booking" and "Payment". An Order always has to include a minimum of one Booking but does not necessarily need to have a Payment when the Order is created. The form for the Payment will be generated nonetheless. I would like to validate the Payment form on a "payment_amount" > 0. If no payment is made at the moment the order is created, no PaymentInline should be saved. views.py class BookingInline(InlineFormSetFactory): model = Booking form_class = BookingForm prefix = 'booking_formset' factory_kwargs = { 'extra': 0, 'min_num': 1, 'validate_min': True, 'can_delete': True } class PaymentInline(InlineFormSetFactory): model = Payment form_class = PaymentForm prefix = 'payment_formset' factory_kwargs = { 'extra': 1, 'min_num': 0, 'validate_min': False, 'can_delete': True } class OrderCreateView(NamedFormsetsMixin, CreateWithInlinesView): model = Order inlines = [BookingInline, PaymentInline] inlines_names = ['booking_formset', 'payment_formset'] form_class = OrderForm template_name = 'orders/order_form.html' def get_success_url(self): return reverse_lazy('order_detail', kwargs={'pk': self.object.pk}) def forms_valid(self, form, inlines): """ If the form and formsets are valid, save the associated models. """ self.object = form.save(commit=False) self.object.created_by = self.request.user form.save(commit=True) for formset in inlines: … -
u"Key 'bank' not found in 'CreditForm'"
I'm trying to expand the base model, but I get the following error. u"Key 'bank' not found in 'CreditForm'" models.py class Credit(AbstractBaseProduct): bank = models.ForeignKey('banks.Bank', verbose_name=_('bank')) class Meta: verbose_name = _('credit') verbose_name_plural = _('Credits') admin.py class BaseCreditAdmin(admin.ModelAdmin): list_display = ['id', 'name', 'slug', 'created_at', 'updated_at'] list_display_links = ['slug',] fieldsets = [ (None, {'fields': [('best', 'hot'), 'name', 'slug']}), ('SEO', {'fields': [('breadcrumbs',), ('meta_title',), ('meta_keywords',), ('meta_description',),('short_description',)]}) ] model = AbstractBaseProduct class CreditAdmin(BaseCreditAdmin): model = Credit def get_list_display(self, requset): self.list_display.insert(2, 'bank') return self.list_display def get_fieldsets(self, request, obj=None): fieldsets = copy.deepcopy(super(CreditAdmin, self).get_fieldsets(request, obj)) self.fieldsets[0][1]['fields'].insert(1, 'bank') return fieldsets -
how o fix this error i am doing crud operation there is no error but in vies file
Class 'Employee' has no 'objects' memberpylint(no-member) See every employee has a red line and that red line is saying what see in the picture enter image description here