Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problems on through model with Django Rest Framework
This happens when I list to Recipe objects. Trying to do as here, I get no errors, but the response I'm getting is as the following: # response of Recipe.objects.all() [ { "user": 1, "name": "sandwich", "ingredients": [ {}, {} ], "created": "2021-01-11T00:47:04.932071-03:00", "modified": "2021-01-11T00:47:04.932167-03:00" } ] When the models are: class Recipe(models.Model): user = models.ForeignKey('users.User', on_delete=models.CASCADE, null=False) name = models.CharField(blank=False, max_length=50) ingredients = models.ManyToManyField('recipes.Ingredient', through='recipes.IngredientComposition') # some other fields... class Ingredient(BaseModel): name = models.CharField(blank=False, max_length=25, unique=True error_messages={'unique': 'Ingredient already exists'}) class IngredientComposition(models.Model): ingredient = models.ForeignKey('Ingredient', on_delete=models.CASCADE, null=False) recipe = models.ForeignKey('recipes.Recipe', on_delete=models.CASCADE, null=False) quantity = models.DecimalField(max_digits=21, decimal_places=3, null=False, default=1) And their serializers: class RecipeSerializer(serializers.ModelSerializer): ingredients = IngredientCompositionSerializer(read_only=True, many=True) class Meta: model = Recipe fields = ['user', 'name', 'ingredients', 'created', 'modified'] class IngredientSerializer(serializers.ModelSerializer): class Meta: model = Ingredient fields = ['name', 'created', 'modified'] class IngredientCompositionSerializer(serializers.HyperlinkedModelSerializer): name = serializers.ReadOnlyField(source='ingredient.name') class Meta: model = IngredientComposition fields = ['name', 'quantity'] The expected response is: [ { "user": 1, "name": "sandwich", "ingredients": [ {"name": "bread", "quantity", 2.0}, {"name": "cheese", "quantity", 3.0} ], "created": "2021-01-11T00:47:04.932071-03:00", "modified": "2021-01-11T00:47:04.932167-03:00" } ] What am I missing? -
how to handle authentication error in angular based on data returned from django rest-framework
a login may result in authentication failed by Django due to 'Invalid credentials', 'Account disabled' , 'Email is not verified' , the code looks as below if not user: raise AuthenticationFailed('Invalid credentials, try again') if not user.is_active: raise AuthenticationFailed('Account disabled, contact admin') if not user.is_verified: raise AuthenticationFailed('Email is not verified') I am getting three different responses in three different conditions but 401 status code in all three cases. my login request sends from angular as follow, if (this.loginForm.dirty && this.loginForm.valid) { this.httpService.doLogin(this.loginForm.value).subscribe(data=>{ console.log() if(data['email'] && data['tokens']){ //codes gets executed if everything goes well and authenticate well. ... ... }else{ console.log('data load fail', data) } },error=>{ //line 1 this.toastr.error('Invalid Credentials or email not verified', 'Login Error',); }) }else{ this.toastr.warning('Info!', 'Invalid data provided.'); } } the problem is in all three above authentication fail, my codes come to line 1, and I am not able to toast the failing reason properly although I get the response but HTTP 401 takes me to line 1. I want to toast according to the response so that the user understand what is the issue, ex: if the email is not verified I must toast email not verified if account disabled I must toast account disabled … -
TodayArchiveview is not detected in urls.py(Django)
I created several date-based views in Django, and while views for year and month function as expected, the view to display today is not detected. For instance, if I try to get http://127.0.0.1:8000/blog/archive/2021/jan or http://127.0.0.1:8000/blog/archive/2021/jan/07/ the views will be displayed, http://127.0.0.1:8000/blog/archive/today/ will fail. I understand that the problem must be with urls.py configuration, but I just cannot find it in documentation. urls.py from django.urls import path, re_path from blog import views app_name = 'blog' urlpatterns = [ # Example: /blog/ path('', views.PostListView.as_view(), name='index'), # Example: /blog/post/ (same as /blog/) path('post/', views.PostListView.as_view(), name='post_list'), # Example: /blog/post/django-example/ re_path(r'^post/(?P<slug>[-\w]+)/$', views.PostDetailView.as_view(), name='post_detail'), # Example: /blog/archive/ path('archive/', views.PostArchiveView.as_view(), name='post_archive'), # Example: /blog/archive/2019/ path('archive/<int:year>/', views.PostYearArchiveView.as_view(), name='post_year_archive'), # Example: /blog/archive/2019/nov/ path('archive/<int:year>/<str:month>/', views.PostMonthArchiveView.as_view(month_format = '%b'), name='post_month_archive'), # Example: /blog/archive/2019/nov/10/ path('archive/<int:year>/<str:month>/<int:day>/', views.PostDayArchiveView.as_view(), name='post_day_archive'), # Example: /blog/archive/today/ path('archive/today/', views.PostTodayArchiveView.as_view(), name='post_today_archive'), ] views.py from django.shortcuts import render # Create your views here. from django.views.generic import ListView, DetailView, ArchiveIndexView, YearArchiveView, MonthArchiveView, \ DayArchiveView, TodayArchiveView from blog.models import Post class PostListView(ListView): model = Post template_name = 'blog/post_all.html' context_object_name = 'posts' paginate_by = 2 class PostDetailView(DetailView): model = Post class PostArchiveView(ArchiveIndexView): model = Post date_field = 'modify_dt' class PostYearArchiveView(YearArchiveView): model = Post date_field = 'modify_dt' make_object_list = True class PostMonthArchiveView(MonthArchiveView): model = Post date_field … -
Django blog comments
I can't get to add the new comment in the list of existing commetns on a post. Here's the model: class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') body = models.TextField() commented_by = models.ForeignKey(User, on_delete=models.CASCADE) commented_on = models.DateTimeField(auto_now_add=True) def __str__(self): return f'Commented by {self.commented_by} on {self.post}.' Here's the view: def post_detail(request, id): post = Post.objects.get(id=id) comments = post.comments.all().order_by('-commented_on') total_comments = post.comments.all().count() form = CommentForm() if request.method == 'POST': form = CommentForm(request.POST, instance=post) if form.is_valid(): instance = form.save(commit=False) instance.post = post instance.save() context = { 'post' : post, 'comments' : comments, 'form' : form, 'total_comments' : total_comments, } return render(request, 'blog/detail.html', context) -
Django Error NoReverseMatch at /new_bid/1 Reverse for 'addwatchlist' with arguments '('',)' not found
I am somewhat new to Django. I'm encountering an error that I find very odd. The site allows a user to place a bid (enter a number amount) on an item, similar to ebay. When I enter the number, I get the error "NoReverseMatch at /new_bid/1 Reverse for 'addwatchlist' with arguments '('',)' not found. 1 pattern(s) tried: ['addwatchlist/(?P[0-9]+)$'] This is odd because that area of the code (new_bid in views.py) has nothing to do with the addwatchlist. The addwatchlist in views.py adds this particular item to a list, for that user. It's just so a user can keep track of any items on the site they want to watch. The watchlist function works completely - I can add an item to my watchlist and it's fine. I don't know why this function is interacting with my other function, new_bid, which adds a bid for the item. I know this error usually is related to the url or the way the html template calls the url but I really don't know why they two are interacting. Is it because they both use "id": listingid ? Any help is appreciated! urls.py for relevant urls: urlpatterns = [ path("addwatchlist/<int:listingid>", views.addwatchlist, name="addwatchlist"), path("new_bid/<int:listingid>", views.new_bid, … -
Autumate bigo live apk from windows
In the clip below there is a software on the left giving command to Bigo live apk I want to know what should I learn in order to be able to make similar software as the clip the software has two features login to Bigo live with multi accounts and the accounts can auto chat. https://www.youtube.com/watch?v=7wqGxlZWKqQ -
Suddenly getting Validation Error when trying to perform db migration in Django
For weeks I have had no issues making db migrations, and running models. I added a few fields and then I got Validation Error so I removed the fields, but the error remains. I am not sure what the issue is or how to fix it. I've looked into the db entries and there are no NA entries. I removed from the current field any default="NA" but I continue to get the error. What is the source of the error? How can I fix it? Operations to perform: Apply all migrations: admin, animals, auth, contenttypes, sessions Running migrations: Applying animals.0025_auto_20210111_0214...Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/usr/Desktop/animalDirectoryTemplate/.venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/usr/Desktop/animalDirectoryTemplate/.venv/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/usr/Desktop/animalDirectoryTemplate/.venv/lib/python3.7/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/Users/usr/Desktop/animalDirectoryTemplate/.venv/lib/python3.7/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/Users/usr/Desktop/animalDirectoryTemplate/.venv/lib/python3.7/site-packages/django/core/management/base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "/Users/usr/Desktop/animalDirectoryTemplate/.venv/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 245, in handle fake_initial=fake_initial, File "/Users/usr/Desktop/animalDirectoryTemplate/.venv/lib/python3.7/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Users/usr/Desktop/animalDirectoryTemplate/.venv/lib/python3.7/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/Users/usr/Desktop/animalDirectoryTemplate/.venv/lib/python3.7/site-packages/django/db/migrations/executor.py", line 227, in apply_migration state = … -
django dumpdata command throws doesnot exist error
I am trying to add some default/fixed values to postgres database and came across fixtures. My model is like this app/models.py class Category(models.Model): category = models.CharField(max_length=255) def __str__(self): return self.category app/fixtures/category.json [ { "model": "core.category", "pk": 1, "fields": { "category": "foo" } ] However, I am getting the following error when I run manage.py dumpdata [CommandError: Unable to serialize database: cursor "_django_curs_139823939079496_sync_1" does not exist -
Data accessing by double reverse filter with multiple interdependent model
I am working with some models in Django. my models.py: class Industry(models.Model): user = models.OneToOneField(myCustomeUser, null=True, blank=True, on_delete=models.CASCADE, related_name='industry_releted_user') name = models.CharField(max_length=200, blank=True) gmail = models.EmailField(null=True, blank=False, unique=True) owner = models.CharField(max_length=200, blank=True) license = models.IntegerField(null=True, unique=True) industry_extrafield = models.TextField(blank=True) def __str__(self): return self.name class Industry_Report(models.Model): industry = models.ForeignKey(Industry, null=True, blank=True, on_delete=models.CASCADE) extra1 = models.CharField(max_length=200, blank=True, null=True) extra2 = models.CharField(max_length=200, blank=True, null=True) extra3 = models.CharField(max_length=200, blank=True, null=True) extra4 = models.CharField(max_length=200, blank=True, null=True) def __str__(self): return self.industry.name class report_tableA(models.Model): industry_report = models.ForeignKey(Industry_Report, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, blank=False, null=True) father_name = models.CharField(max_length=200, blank=False, null=True) mother_name = models.CharField(max_length=200, blank=False, null=True) rank = models.CharField(max_length=20, blank=False, null=True) nid = models.IntegerField(blank=False, unique=True) phone_number = models.IntegerField(blank=False, null=True) gmail = models.EmailField(null=True, blank=True, unique=True) Now I am trying to access all those data of report_tableA which are interrelated to Industry's object from the Industry model's DetailView. my views.py: class industryDetails(DetailView): model = Industry template_name = 'app/industryDetails.html' def get_queryset(self): return Industry.objects.filter(user=self.request.user) def get_object(self): return get_object_or_404(Industry, user=self.request.user) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) Industry_Report_obj = self.object.industry_report_set.all() context['Industry_Report'] = Industry_Report_obj report_tableA_obj = self.object.industry_report_set.report_tablea_set.all() context['report_tableA'] = report_tableA_obj return context Actually, I try to implement a kind of double reverse approach doc for relationship field. But it won't work and say Queryset not … -
Error code when trying to create new django project
I am trying to create a new django app. After creating an initial "mysite" project, I tried to create an application labeled "polls" from my windows command line. However, when I put in py manage.py startapp polls, I get this error message: C:\Users\22may> py manage.py startapp polls C:\Users\22may\AppData\Local\Programs\Python\Python39\python.exe: can't open file 'C:\Users\22may\manage.py': [Errno 2] No such file or directory From my understanding, I need to reestablish the project's address. How would I go about this? The current address is: C:\Users\22may\mysite\manage.py Thanks! -
Is it secure to create API in django without rest framework
I've created an app in my django project which works same like API. But for post requests, logins I'm doing something like this. request "GET"(url: example.com/api/get) this returns a csrftoken which is then used by my applications as cookie. request "POST"(url: example.com/api/login), Here frontend application logs in the user. The csrftoken from example.com/api/get is used in cookies and same is used as csrfmiddlewaretoken in post data. My question here is, it is secure to create API like this and use instead of Django RestFramework. Any suggestion will be appreciated.THANK YOU -
How to store information from javascript into a Django model?
I currently have an app which uses HTML/CSS/JQuery. As of right now all my data is saved in Jquery (and therefore not saved between sessions), but I am learning Django and want to learn how I would save that JQuery data into Django models. So how do javascript and django communicate in order to save information from one to the other? -
Django admin search_fields for ForeignKey CustomUser
I am using this model class Project(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(CustomUser, on_delete=models.PROTECT, editable=False) name = models.CharField(max_length=20, editable=False) total = models.DecimalField(max_digits=7, decimal_places=2, default=0) created = models.DateTimeField(auto_now_add=True, editable=False, null=False, blank=False) # new fields comission_owed = models.DecimalField(max_digits=7, editable=False, decimal_places=2, default=0) comission_paid = models.DecimalField(max_digits=7, editable=False, decimal_places=2, default=0) def __str__(self): return self.name Which has CustomUser as a Foreign Key for user from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): pass I am trying to do a search on name and user (Which is a foreign key) using this admin config from django.contrib import admin from .models import Project class ProjectAdmin(admin.ModelAdmin): readonly_fields = ('id','user','name','created','comission_owed','comission_paid') # new list_display = ('user', 'name','comission_owed','comission_paid') search_fields = ( 'name','user') ordering = ('user',) admin.site.register(Project, ProjectAdmin) However I am getting this error: Exception Type: FieldError Exception Value: Related Field got invalid lookup: icontains I tried varius things such as Users__username in my search field or CustomUser__user to no avail, how could I have my user field as a searchable field? Thanks -
how to i reset password if user forget his password, checking a valid user id and mobile number
I want to first ask user to enter his user id and mobile number, if it is correct then render a new form to capture new password and update the password in DB views.py file def forgot_password(request): if request.method=="POST": data=request.POST user_name=data['user_id'] mobile_number=data['mobile_number'] print('user name is: ',user_name) print('mobile number is: ',mobile_number) queryset = MyAccount.objects.filter(username=user_name,mobile_number=mobile_number).values('email', 'mobile_number','username') if not queryset.exists(): messages.warning(request, 'Please enter valid email id and mobile number') fm=ForgotPassword() form={'form':fm} return render(request,'account/forgot_uid_pass.html',form) else: #render new form to enter password by user and change/update password in DB #queryset.set_password('Comedy@124') #queryset.save() else: print('need to generate password change form') fm=ForgotPassword() form={'form':fm} return render(request,'account/forgot_uid_pass.html',form) forms.py file class Register(UserCreationForm): class Meta: model=MyAccount fields=['email','username','mobile_number'] class ForgotPassword(forms.Form): #this will used to provide the user id and mobile number, if they are user_id = forms.CharField(max_length = 200) #valid the will render form to provide new password mobile_number = forms.IntegerField(help_text = "Enter 6 digit mobile number") class CapturePasswordForm(forms.Form): #this form will be used for capture new password by user new_password=forms.CharField(min_length=8) confirm_password=forms.CharField(min_length=8) -
How to specify the type of http request in django
I am writting a view named index. I want to specify that it can handle not only get requests but also post. In flask it was done by decorator, how to achieve it using django? I use Django 1.9.5 -
How to get a non-pk value to be the value by which a post request is made in django rest framework
As the question states, I'd like to be able to instead of having to pass a PK inside my JSON file in the post request I could pass a different value, like a username "bob" instead of 1. here are my relevant models: class UserModel(models.Model): MEMBERSHIP_TYPE = [ ('NM', 'NORMAL'), ('PT', 'PLATA'), ('OR', 'ORO'), ('PL', 'PLATINO'), ] id = models.AutoField(primary_key=True) username = models.CharField(max_length=100, unique=True) photo = models.ImageField(upload_to='images/', blank=True) address = models.TextField() client_type = models.CharField(max_length=2, choices=MEMBERSHIP_TYPE, default= 'NM') def __unicode__(self): return self.name class ArticleModel(models.Model): id = models.AutoField(primary_key=True) code = models.IntegerField(unique=True) description = models.TextField() def __str__(self): return str(self.code) class SupplierModel(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) address = models.TextField() articles = models.ManyToManyField(ArticleModel) def __str__(self): return self.name class OrderModel(models.Model): id = models.AutoField(primary_key=True) client = models.ForeignKey('UserModel', on_delete=models.CASCADE) gen_time = models.DateTimeField(auto_now_add=True) gen_supplied = models.DateTimeField(null=True, blank=True) urgent = models.BooleanField() order_to = models.ForeignKey('OrderToModel', on_delete=models.CASCADE) article = models.ForeignKey('ArticleModel', on_delete=models.CASCADE) quantity= models.IntegerField() and Serializer: class OrderCreateSerializer(serializers.ModelSerializer): # order_to = OrderToPolymorphicSerializer() class Meta: model = OrderModel fields = ('client', 'urgent', 'article', 'quantity', 'order_to') Help is much appreciated. Thank you in advance. -
How to create nexting columns with bootstrap grid
I'm trying to create nexted columns with bootstrap grid, but the result I'm getting isn't nexted {% for home in home %} <div class="container"> <div class="row"> <div class="col-sm-6 col-md-3 med_trend bg-light shadow m-4 rounded"> <h3 class="text-center text-info">{{ home.title }}</h3> <li><i class="fas fa-check text-info mr-2"></i>{{ home.first_point }}</li> <li><i class="fas fa-check text-info mr-2"></i>{{ home.second_point }}</li> <li><i class="fas fa-check text-info mr-2"></i>{{ home.third_point }}</li> <li><i class="fas fa-check text-info mr-2"></i>{{ home.fourth_point }}</li> </div> </div> </div> {% endfor %} -
Change a view varible file with the html file
Im making an online store and I add to it the Stripe Checkout for payments, everything works correct, the problem is that the view fuction only manage one price, it looks like this def charge(request): # new if request.method == 'POST': charge = stripe.Charge.create( amount=179900, currency='mxn', description='Bota Caballero', source=request.POST['stripeToken'] ) return render(request, 'charge.html') the amount says the price, In my html homepage i have a select tag, it define the cost of the product <select id="modelo" onchange="modelo()" class="select__option" required> <option>Selecciona Modelo...</option> <option>$1799</option> <option>$1299</option> <option>$1199</option> </select> i would like to change the amount variable of the view file depending on what is selected in the select tag. Any idea? -
Superuser doesn't work after unapplying migrations in Django
I was having some trouble (errors) with old migrations in my auction site project, so I decide to run python manape.py migrate auctions zero to unapply all the migrations and apply new ones, and it worked. However, after I did it I couldn't use my superuser account to manipulate the models in the admin/ url anymore. In fact, I couldn't use any other account -- this website I'm working on allows the creation of profiles by the user, and before I unapply all the migrations it worked perfectly. But now, if I try to log in with an existing account created for testing purposes, I receive this error message (that I wrote): But I was expecting that to happen, since I (if I understood well) cleared the user database when I unapplied the migrations. But when I try to create a new user, no matter the username or password, I get this error (that I also wrote): How can the username be already taken if it is completely new? These errors appears no matter what I do, even when I try to login with the superuser. When I try to create a new superuser I also have problems, like this … -
Could someone please provide a link to a Django + Javascript basic project?
Could someone please provide a link to a sample Django project that I can download and build off. To be specific, I am going to create a website used for a business application on a mobile device. The web page will have a login. When logged in, the user will be presented with a few menu options. The user can click between the menus without the page reloading. All will be done with Ajax. The user will enter data, scan/search and submit forms. The submitted data will be sent to an external application (ERP system). I have created several projects in the past, but they become difficult to scale and manage. In my previous apps, I used Flask and had everything in a single html file including the javascript. It works, but it isn't great. I'm trying to take things to the next level. I have spent a bunch of time researching google but find several different directions to take. I learn best, by having a basic example and then reverse engineering how it works. -
How to read shapefile in Django view helper function?
As part of my view logic I need to check if Latitude and Longitude points are withing city boundaries. To do that, I am using city shapefiles with geopandas. It all works ok locally in plain python code. However, when I run the following code in Django: LA_geo_df = gpd.read_file('./City_Boundaries/City_Boundaries.shp') I get the error: DriverError at / ./City_Boundaries/City_Boundaries.shp: No such file or directory What is the proper Django way of loading such files? -
How do I display videos in template from inline formset?
I have a form that includes an inline formset and I am having trouble displaying the videos in the template that were uploaded from the form. What would I add to the html line in the template as the source so that the video uploads are displayed? Thanks. models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=100, blank=True) last_name = models.CharField(max_length=100, blank=True) bio = models.TextField(max_length=150, null=True) phone_number = models.CharField(max_length=50, null=True, blank=True) def __str__(self): return self.user.username class MultipleFileUpload(models.Model): file_uploads = models.ForeignKey(Profile, on_delete=models.CASCADE) video = models.FileField(null=True, blank=True, upload_to='videos') def __str__(self): return self.user.username @receiver(post_save, sender=User) def update_profile_signal(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() forms.py: class EditProfile(forms.ModelForm): class Meta: model = Profile fields = ['bio', 'phone_number'] class ProfileUpdateFormset(forms.ModelForm): class Meta: model = MultipleFileUpload fields = ['video'] views.py: def edit(request, id): all_objects = get_object_or_404(Profile, id=id) ProfileFormset = inlineformset_factory(Profile, MultipleFileUpload, fields=('video',), can_order=False, can_delete=True, extra=1) if request.method == 'POST': form1 = EditProfile(request.POST or None, instance=all_objects) formset = ProfileFormset(request.POST, request.FILES, instance=all_objects) if form1.is_valid() and formset.is_valid(): form1.save() formset.save() return HttpResponseRedirect(".") form1 = EditProfile(instance=all_objects) formset = ProfileFormset(instance=all_objects) context = { 'form1': form1, 'formset': formset, } return render(request, 'accounts/edit.html', context) html: <video width="350" height="200" source src="{{ user.profile.file_uploads.video.url }}" controls></video></p> -
Updating two models with a foreign key at the same time
Below are my codes and I get the error ValueError at /inventory/stock/1/edit Cannot assign "'1'": "Stock.category" must be a "Category" instance. in model.py class Category(models.Model): name = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return self.name class Stock(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE,blank=True) item_name = models.CharField(max_length=100, blank=True, null=True) quantity = models.IntegerField(default='0',blank=True, null=True) class StockHistory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE,blank=True) item_name = models.CharField(max_length=100, blank=True, null=True) quantity = models.IntegerField(default='0',blank=True, null=True) in view.py def UpdateStock(request, pk): stock = Stock.objects.get(id=pk) stock_form = StockForm(instance = stock) history_form = StockHistoryForm(instance = stock) if request.method == 'POST': stock_form = StockForm(request.POST, instance = stock) history_form = StockHistoryForm(request.POST, instance = stock) if stock_form.is_valid() and history_form.is_valid(): stock = stock_form.save() history = history_form.save() return redirect('inventory') context = { 'stock_form': stock_form, 'history_form': history_form } return render(request, 'inventory/edit.html', context) -
AttributeError: 'CharField' object has no attribute 'stream_block'
I'm really new to Python3, Django & Wagtail and am trying to create an ArticlePage Model with a StreamField block used in it, and have run into problems and am getting an error: AttributeError: 'CharField' object has no attribute 'stream_block' error. I have no idea what I'm doing wrong? I'm obviously doing something wrong but have no idea what? Here's the model.py code: articles/models.py: from modelcluster.fields import ParentalKey from wagtail.core import blocks from wagtail.core.models import Page, Orderable from wagtail.admin.edit_handlers import FieldPanel, StreamFieldPanel, MultiFieldPanel, InlinePanel from wagtail.core.fields import StreamField from streams import blocks from wagtail.core.fields import RichTextField from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.search import index ### Flexible Page # Create your models here. class ArticlePage(Page): subtitle = models.CharField() body = RichTextField() date = models.DateField("Article date") team_member = models.CharField() feed_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) search_fields = Page.search_fields + [ index.SearchField('body'), index.FilterField('date'), index.FilterField('subtitle'), ] template = "articles/article_page.html" #ToDo: add StreamFields content = StreamField( [ ("team_member", blocks.TeamMembersBlock()) ], null=True, blank=True, ) subtitle = models.CharField() content_panels = Page.content_panels + [ FieldPanel("subtitle"), FieldPanel('date'), FieldPanel('body', classname="full"), InlinePanel('related_links', label="Related links"), StreamFieldPanel("team_member"), ] promote_panels = [ MultiFieldPanel(Page.promote_panels, "Common page configuration"), ImageChooserPanel('feed_image'), ] # Parent page / subpage type rules parent_page_types = ['articles.ArticleIndex'] subpage_types = [] … -
How can i Fix this problem in Python Django?
enter image description hereClass 'User' has no 'objects' memberpylint(no-member) i don't understand