Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to stop django-html formatting to one line with tags
When I save my django-html file the following changes occur in auto formatting. {% extends 'base.html' %} {% block content %} {% if dice %} {% for die in dice %} <img src="{{die.image.url}}" alt="{{die.name}}" /> {% endfor %} {% endif %} {% endblock %} I want to have something like the following instead... {% extends 'base.html' %} {% block content %} {% if dice %} {% for die in dice %} <img src="{{die.image.url}}" alt="{{die.name}}" /> {% endfor %} {% endif %} {% endblock %} I have Beautify installed and my settings are as follows... "emmet.includeLanguages": { "javascript": "javascriptreact", "django-html": "html" }, "files.associations": { "**/*.html": "html", "**/templates/*/*.html": "django-html", "**/templates/*": "django-txt", "**/requirements{/**,*}.{txt,in}": "pip-requirements" }, "beautify.language": { "html": ["htm", "html", "django-html"] }, -
Need help in Django templates
So I have a list named counts and it has a method times_used. I cannot use the method on the counts but it can be only used on each item in the list counts. The problem now is I cannot use counts[0].times_used in html template as it shows the error of not parsing. So I have used {% for count in counts %} <td>{{ count.times_used }}</td> {% endfor %} The problem here is all count.times_used is displayed for every item in counts. I want the count to be displayed only once per loop based on loop number (like counts[0],counts[1]....). How can I do this? -
django admin custom middleware password reset confirm issue
Code for Cutom Login Middleware: class LoginCheckMiddleWare(MiddlewareMixin): def process_view(self, request, view_func, view_args, view_kwargs): modulename = view_func.__module__ user = request.user #Check whether the user is logged in or not if user.is_authenticated: if user.role_id == "3": if modulename == "user.adminViews": pass elif modulename == "user.adminViews" or modulename == "django.views.static": pass else: return redirect("home") else: return redirect("login") else: headers = request.META urlCheck = request.path in set({reverse("login"), reverse("doLogin"), reverse("schema"),reverse('password_reset'),reverse('password_reset_confirm',args=(uid64,token)),reverse('password_reset_complete')}) if headers.get('HTTP_TOKEN') or urlCheck or modulename == 'django.views.static': pass else: return redirect("login") Urls i have like : path("password_reset/", adminViews.password_reset_request, name="password_reset"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="registration/password_reset_confirm.html"), name='password_reset_confirm'), path('password_reset/done/', auth_views.PasswordResetCompleteView.as_view(template_name='registration/password_reset_complete.html'), name='password_reset_complete'), After thi i am getting the mail where i am getting the password reset link like : http://127.0.0.1:8000/reset/MQ/advtup-241878a4d46ab73c5d381bf194fea697/ But when i click on this link it returning me the error like NameError at /reset/MQ/advtup-241878a4d46ab73c5d381bf194fea697/ name 'uid64' is not defined when i remove the ,reverse('password_reset_confirm',args=(uid64,token)) from my custom middleware .then it is redirecting me to login page instead of password changes screen can anyone please help me related this ?? i am stuck here . -
Pagination problems with filtering objects in Django
I'm trying to add the pagination functionality on my project that has a plog section. On this project I have different types of page that needs to display some content and to be more efficient I've mad a single model that hold all types of pages. On the page section I want to display just the pages that has the blog_post=True and apply a pagination. I've tried that on my class based view but the paginator is not working. It show me correct number of post per page, is showing the pagination buttons but when I try to acces another page, for example next page it give an error like this, but on the url I know that should display me something like blog/?page=2 but it displays me this "http://localhost:8000/blog/?page=%3Cbound%20method%20Page.next_page_number%20of%20%3CPage%201%20of%202%3E%3E" Class based view class BlogListView(generic.ListView, MultipleObjectMixin): model = Page template_name = 'pages/blog_list.html' paginate_by = 1 def get_queryset(self): return Page.objects.filter(blog_post=True).order_by('-created_dt') Models.py class Page(models.Model): class Meta: ordering = ['slug'] blog_post = models.BooleanField(_("Blog Post"), blank=False, default=False) title = models.CharField(_("Title"), blank=True, max_length=100, unique=True) slug = models.SlugField(_("Slug"), unique=True, max_length=100, blank=True, null=False) breadcrumb_title = models.CharField( _("Breadcrumb Title"), blank=True, max_length=100, null=False, default='') text = MarkdownxField(_("Text"), blank=True, null=False) description = models.TextField( _("Meta Description"), blank=True, null=False, default='') keywords = … -
Run Script inside Migration file - django
I have generated an empty migration file. from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('core', '0049_auto_20201125____'), ] operations = [ ] My goal is to run a script to update the username column of the table User if the username is equal to None. I have to generate a unique username and use it for the update. -
how to map nested json data in react js
how to map one nested json data in react js example i want to display the product images that i recived from api export class Planview extends Component{ constructor() { super(); this.state = { package: [], }; } componentDidMount() { const ProdID = this.props.match.params.ProductID fetch(`http://127.0.0.1:8000/api/plan/${ProdID}/`) .then(response => response.json()) .then(responseData => { this.setState({ package: responseData }); }) .catch(error => { console.log('Error fetching and parsing data', error); }); } render(){ return(<> <div className="container mar" > <h1 className="my-4">{this.state.package.title}</h1> <div className="row"> <div className="col-md-offset-2"> <div className="row" id="gradient"> <div className="col-md-6 img-responsive"> <img className ="img-main img" src={"http://127.0.0.1:8000"+this.state.package.thumbnail} alt="main" fluid ="True"/> </div> <div className="col-md-6" id="overview"> <h4>{this.state.package.code}</h4> <h5><small> {this.state.package.created_at}</small></h5 </div> <div className="row mt-4"> <h3><small></small></h3> <div className="row"> { this.state.package.image.map(function (person, index) { return ( <div className="col" key={index}> <img className={person.image} src="" alt="1"/> </div> )})} </div> </div> </div> <div className="row"> <h3 className="my-4">{this.state.package.description}</h3> </div> </div> </div> </div> </> ); } } export default Planview; and my json is like {id: 1, image: [{image: "/media/plan_images/Home-5-E-plan-1024x684.jpg"},…], title: "sample",…} code: "MAG0001" created_at: "2020-11-23" description: "college book" details: {age: 31, city: "New York", name: "John"} id: 1 image: [{image: "/media/plan_images/Home-5-E-plan-1024x684.jpg"},…] slug: "sample" thumbnail: "/media/plan_images/900-square-feet-home-plan.jpg" title: "sample" from the above json i want to display the image from the field image array it contains multiple images and also … -
Python Django heroku error “! [remote rejected] master -> master (pre-receive hook declined)” [closed]
Please help me....... Whenever I type command: git push heroku master $ git push heroku master Enumerating objects: 10320, done. Counting objects: 100% (10320/10320), done. Delta compression using up to 4 threads Compressing objects: 100% (6444/6444), done. Writing objects: 100% (10320/10320), 15.12 MiB | 4.10 MiB/s, done. Total 10320 (delta 2785), reused 10299 (delta 2778) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! Requested runtime (Python-3.8.2) is not available for this stack (heroku-18). remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: bb01b6d148aaa616f56e755b64cb0b783740d38c remote: ! remote: ! We have detected that you have triggered a build from source code with version bb01b6d148aaa616f56e755b64cb0b783740d38c remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch. remote: ! remote: ! If you are developing on a branch and deploying via git you must run: remote: ! remote: ! git push heroku :main remote: ! remote: ! This article goes into details on the behavior: remote: ! https://devcenter.heroku.com/articles/duplicate-build-version remote: … -
AttributeError at /upload_to_vimeo/ 'TypeError' object has no attribute 'message'
while uploading videos to vimeo it throws this error following are codes views def upload_to_vimeo(request): token = 'xxxxx' if request.method == 'POST': form = VideoUploadForm(request.POST, request.FILES) if form.is_valid(): v = vimeo.VimeoClient( token=token, ) v.upload(request.FILES['video_file']) return HttpResponseRedirect(request.META.get("HTTP_REFERER")) else: form = VideoUploadForm() return render(request, 'forms/video_upload_form.html', {'form': form}) template <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="video_file"> <input type="submit" class="button inline-block bg-theme-1 text-white mt-5" value="Upload"> </form> Traceback: File "/home/biju/Desktop/Dev/multitenant/lib/python3.8/site-packages/vimeo/upload.py" in __perform_tus_upload 143. with io.open(filename, 'rb') as fs: During handling of the above exception (expected str, bytes or os.PathLike object, not TemporaryUploadedFile), another exception occurred: File "/home/biju/Desktop/Dev/multitenant/lib/python3.8/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/biju/Desktop/Dev/multitenant/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/biju/Desktop/Dev/multitenant/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/biju/Documents/mtenant/client_admin/views.py" in upload_to_vimeo 787. v.upload(request.FILES['video_file']) File "/home/biju/Desktop/Dev/multitenant/lib/python3.8/site-packages/vimeo/upload.py" in upload 71. return self.__perform_tus_upload(filename, attempt, chunk_size=chunk_size) File "/home/biju/Desktop/Dev/multitenant/lib/python3.8/site-packages/vimeo/upload.py" in __perform_tus_upload 152. raise exceptions.VideoUploadFailure( File "/home/biju/Desktop/Dev/multitenant/lib/python3.8/site-packages/vimeo/exceptions.py" in init 93. super().init(response, message) File "/home/biju/Desktop/Dev/multitenant/lib/python3.8/site-packages/vimeo/exceptions.py" in init 30. self.message = self.__get_message(response) File "/home/biju/Desktop/Dev/multitenant/lib/python3.8/site-packages/vimeo/exceptions.py" in __get_message 23. message = getattr(response, 'message') Exception Type: AttributeError at /upload_to_vimeo/ Exception Value: 'TypeError' object has no attribute 'message' -
Saving dynamically added text box to database
First here is my view: def price_save(request): remarks = request.POST.get("remarks") current_user = request.user pah = PAH(remarks=remarks, created_by=current_user) pah.save() item1 = request.POST.getlist("item_code[]") item2 = request.POST.getlist("item_description[]") item3 = request.POST.getlist("uom[]") for item in item1: item_price = PAR(transaction_id=pah, item_code=item, item_description=item2, uom=item3) item_price.save() return HttpResponse("Saved!") with this I can save multiple rows with different values on item_code and same transaction id, but I dont know how to add item_description and uom in the for loop. -
How to foreign key to a foreign key
In class Model, brand is foreign key from Brand. In class Car, how do I foreign key the brand in class Brand? class Brand(models.Model): brand = models.CharField(max_length=200) def __str__(self): return self.brand class Color(models.Model): color= models.CharField(max_length=200) def __str__(self): return self.color class Model(models.Model): brand = models.ForeignKey(Brand, null=True, on_delete=models.CASCADE) model = models.CharField(max_length=200) def __str__(self): return self.model class Car(models.Model): brand=models.ForeignKey(Brand,null=True,on_delete=models.CASCADE)#it is wrong here, how do i fix it? model=models.ForeignKey(Model,on_delete=models.CASCADE) plate_number=models.CharField(max_length=200) -
Need help using placeholders for auth_views in django
I created a forgot password functionality using django.contrib.auth.views which is working fine. However the styling does not go with the rest of the site. I want to use only placeholders for the form fields. But since I am using the mentioned view, i don't know how. I want to remove the Email label here and write that as a placeholder This is the general theme of the site: For the login and register pages, I am mentioning the fields separately as shown in the figure: If i try do that for my forgot-password page, I get this result with no visible fields. If I try using form.password1 and form.password2, it doesn't work and I don't get the form fields at all. Here i use only the form option. I want to have the labels as placeholders(no labels). And the other stuff removed. Here are the views used in the urls.py file: Is the view using the second form? Also is there an option for a redirect here so I can just redirect my users to login page instead of a separate page? please help -
how to set djang logger to send email and save in file on AWS lightsail
Based on this SO question, I'm trying to implement error logging for my django project which is deployed on aws lightsail. my settings.py: DEBUG = False ALLOWED_HOSTS = ['XX.XXX.XXX.XXX'] # Email config EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD = 'mypass' EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' ADMINS = ( ('myname', 'my email'), ) MANAGERS = ADMINS LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style': '{', }, 'simple': { 'format': '{levelname} {message}', 'style': '{', }, }, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, }, } I user the logger in one of my apps' views.py as following: import logging def register(request): logger = logging.getLogger(__name__) ... if some_condition: logger.error('Something went wrong!') def mylogin(request): logger = logging.getLogger(__name__) if some_condition: logger.error('Something went wrong!') but I get no email at all. In addition to this, when I set file handler, my site gives internal error and don't come up at all. any idea how to do it? I need error logs to check the source of … -
Django returns only default image URL
I am new to Django and building a simple social media type app for adding and viewing posts. I am using admin side to upload profile images for users and it works well. I am yet to create a frontend to upload profile images. I am using PostgreSQL and I can query to see the correct URLs being saved in the table for profile images. But when I try to fetch these images and render, the default image (set in models.py) always renders. I am able to open the right images from admin side but Django only returns the default image. My frontend has Javascript in which I am using fetch API to get URLs of profile images. It works well except it returns only the default image. Please help me find out where I am going wrong or why only 'defaultpp.jpg' always shows up. I have tried using print statements in models.py and views.py and only see the URL for 'defaultpp.jpg' being returned. models.py def user_directory_path(instance, filename): return f'{instance.profile_user.id}/{filename}' class User(AbstractUser): def __str__(self): return f"User ID: {self.id} Username: {self.username}" class UserProfile(models.Model): profile_user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) profile_picture = models.ImageField(upload_to = user_directory_path, blank=True, null=True, default='defaultpp.jpg') def __str__(self): return f"User: {self.profile_user} … -
Need a documentation for using sslcommerz api in django
Can someone help me out to build a payment gateway in django. I want to use sslcommerz. They dont have any documentation for django.Here is their documentation sslcommerz I badly need this or any documentation which i can follow.Because of some mobile banking i have to use their service. -
Django wagtail login required not working
I'm working on wagtailcms.I just want to display a page only if the user is logged in. I have tried LoginRequiredMixin,@method_decorator(login_required, name='dispatch') but nothing works from django.contrib.auth.decorators import login_required @login_required(login_url='/login/') class LessonListPage(RoutablePageMixin, Page): """ Lists all the lessons on one page """ template = "lesson/lesson_list_page.html" custom_title = models.CharField( max_length=100, blank=False, null=False, help_text='Overwrites the default title', ) content_panels = Page.content_panels + [ FieldPanel("custom_title"), ] def get_context(self, request, *args, **kwargs): """Adding custom stuff to our context""" context = super().get_context(request, *args, **kwargs) context["posts"] = LessonDetailPage.objects.live( ).public().order_by('-first_published_at')[:10] #Change 'public' to adjust which posts are displayed context["postcategories"] = Category.objects.all() return context -
html select tag not working in django template
This question is asked many times, but I think I am having issues with strings in the Django template I have a select tag and I want to select the default option from database <select name="category" class="form-control" required="" id="id_category"> <option value="" >--------</option> {% for cat in all_categories %} <option value="{{cat}}" {% if form.instance.category == cat %} selected {% endif %}> {{cat}}</option> {% endfor %} </select> my {{cat}} variable has value 'Django Book' and {{form.instance.category}} also have same value i.e. 'Django Book'. But it doesn't select the desired option however, I am using similar logic in another part <select class="form-control" id="client" required name="client"> <option value=" ">-----</option> {% for customer in all_customers %} <option value="{{customer.pk}}" {% if form.instance.client_id.pk == customer.pk %}selected{% endif %}>{{customer}}</option> {% endfor %} </select> but this time I am comparing ids to select the default option and it works. what is the issue in the above code?? is this issue with strings?? and how can I overcome this. Also, I would like to set strings in the value attribute in the first code example. Thanks for any help. -
How do I proceed after authenticating the user through python social auth?
Hello so I'm very new to Django and I have successfully authenticated a user through twitter using python-social-auth. However, now I need to make a call to Twitters API and I am very lost in how I should retrieve and process the necessary data after authentication such as the user_id and access token in order to be able to do that. Thank you. -
Django ValueError: Field 'id' expected a number but got 'S'
Below is my models that are used in view where errors occur and error occurs in StockQuantity model particularly, when i try to filter or use get to retreive query it says expected number but got 'stringvalue' models.py # StockQuantity class StockQuantity(models.Model): item = models.ForeignKey('Item', on_delete=models.CASCADE, null=True) color = models.ForeignKey( 'ItemColor', on_delete=models.CASCADE) cloth_size = models.ForeignKey( 'ClothSize', on_delete=models.CASCADE, blank=True, null=True) footwear_size = models.ForeignKey( 'FootwearSize', on_delete=models.CASCADE, blank=True, null=True) stock_quantity = models.IntegerField(null=True, default=10) #OrderItem class OrderItem(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) footwear_size = models.CharField(max_length=50, null=True) cloth_size = models.CharField(max_length=50, null=True) color = models.CharField(max_length=50, null=True) ordered = models.BooleanField(default=False) #Order class Order(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ref_code = models.CharField(max_length=20, blank=True, null=True) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) shipping_address = models.ForeignKey( 'Address', related_name='shipping_address', on_delete=models.SET_NULL, blank=True, null=True) billing_address = models.ForeignKey( 'Address', related_name='billing_address', on_delete=models.SET_NULL, blank=True, null=True) payment = models.ForeignKey( 'Payment', on_delete=models.SET_NULL, blank=True, null=True) coupon = models.ForeignKey( 'Coupon', on_delete=models.SET_NULL, blank=True, null=True) being_delivered = models.BooleanField(default=False) received = models.BooleanField(default=False) requested_refund = models.BooleanField(default=False) refund_status = models.BooleanField(default=False) #Payment class Payment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, blank=True, null=True) paypal_transaction_id = models.CharField(max_length=50) amount = models.FloatField() timestamp = models.DateTimeField(default=timezone.now) Below is my views.py and specifically the view where the error is thrown, I have … -
app.js:6 Uncaught TypeError: Cannot read property 'addEventListener' of null
Here is my app.js const navBtn = document.getElementById("nav-btn"); const navbar = document.getElementById("navbar"); const navClose = document.getElementById("nav-close"); navBtn.addEventListener("click", () => { navbar.classList.add("showNav"); }); navClose.addEventListener("click", () => { navbar.classList.remove("showNav"); }); I have placed the script tag at the end of the body tag in my html. I am using django as my backend and the javascript files have been loaded properly as I am not getting a 404 error. Need some help to resolve the issue -
I want to show customers phone_number and coin in home page
I am trying to fetch customers phone_number & Coin from the DB to my home page But I am stuck here and got really confused about this topic.I tried request.session.customer but it only shows the customers ID. Here is my Customer Models: class Customer(models.Model): phone_number = models.CharField(max_length=100, default=1) email = models.EmailField( default=1) password = models.CharField(max_length=100) coin = models.FloatField(null=True, blank=True) Here is views.py class Index(View): def get(self, request): cart = request.session.get('cart') if not cart: request.session['cart'] = {} #products = None products = Product.get_all_products() cats = Category.get_categories() brands = Brand.get_brands() sliders = Slider.objects.all() offers = Offer.objects.all() # balance = Customer.objects.get(user=request.user) # balance = get_object_or_404(Customer, coin = request.coin) categoryID = request.GET.get('category') brandID = request.GET.get('brand') if categoryID: # products = Product.get_products_by_category(categoryID) products = products.filter(category__id = categoryID) # else: # products = Product.get_all_products() if brandID: # proucts = Product.get_brands_by_products(brandID) products = products.filter(brand__id = brandID) # else: # products = Product.get_all_products() args = { 'products':products, 'cats': cats, 'brands': brands, 'sliders':sliders, 'offers':offers, # 'balance':balance } return render(request, 'Home/index.html', args) I commented somelines to show only coin in homepage but its not showing :( -
Django, Permissions other than'view' do not work
First of all, I can't speak English well. test1 account permissions.py from rest_framework import permissions import copy class ViewPermissions(permissions.DjangoObjectPermissions): def __init__(self): self.perms_map = copy.deepcopy(self.perms_map) self.perms_map['GET'] = ['%(app_label)s.view_%(model_name)s'] class AddPermissions(permissions.DjangoObjectPermissions): def __init__(self): self.perms_map = copy.deepcopy(self.perms_map) self.perms_map['POST'] = ['%(app_label)s.add_%(model_name)s'] class UpdatePermissions(permissions.DjangoObjectPermissions): def __init__(self): self.perms_map = copy.deepcopy(self.perms_map) self.perms_map['PATCH'] = ['%(app_label)s.change_%(model_name)s'] view.py from rest_framework import viewsets, permissions, generics from .serializers import PlayerListSerializer from .models import PlayerList from .permission import ViewPermissions, AddPermissions, UpdatePermissions class ListPlayer(generics.ListCreateAPIView): permission_classes = [ViewPermissions, ] queryset = PlayerList.objects.all().filter(del_yn='no').order_by('-key') serializer_class = PlayerListSerializer class AddListPlayer(generics.ListCreateAPIView): permission_classes = [AddPermissions, ] queryset = PlayerList.objects.all().filter(del_yn='no').order_by('-key') serializer_class = PlayerListSerializer class DetailPlayer(generics.RetrieveUpdateDestroyAPIView): permission_classes = [UpdatePermissions, ] queryset = PlayerList.objects.all() serializer_class = PlayerListSerializer Through a simple test I confirmed that I can't see the list without 'view' permission. But for the rest of the permissions I get a '401 (Unauthorized)' error and it doesn't work. I have clearly given the authority right. Can you please let me know where the hell is the problem? Thanks in advance to those who answer. No answer was posted, so I ask again. -
Reverse for 'update_order' with arguments '('',)' not found. 1 pattern(s) tried: ['update_order/(?P<pk>[^/]+)/$']
I am currently using django 3.1.3 on Windows 10. I was following Dennis Ivy's tutorials for creating a django app, and I reached part 11: Inline Formsets. I am 100% sure I have everything Dennis has but for some reason I am getting the error I mentioned in the title. It was able to access the dashboard once, when I went to update orders it crashed, and after that I was never even able to access dashboard (http://127.0.0.1:8000/dashboard/) again! Here are my files: views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.forms import inlineformset_factory from .models import Customer, Address, Credit_Card, Order, Grocery_Store, Product, Supplier, Warehouse, Staff_Member, Price from .forms import OrderForm #Create your views here. def index(request): return render(request, 'index.html', {}) def dashboard(request): orders = Order.objects.all() customers = Customer.objects.all() total_customers = customers.count() total_orders = orders.count() delivered = orders.filter(status='Delivered').count() pending = orders.filter(status='Pending').count() context = {'orders':orders, 'customers':customers,'total_orders':total_orders,'delivered':delivered,'pending':pending } return render(request, 'dashboard.html', context) def customer(request, pk_test): customer = Customer.objects.get(Customer_ID=pk_test) orders = customer.order_set.all() order_count = orders.count() context = {'customer':customer, 'orders':orders, 'order_count':order_count} return render(request, 'customer.html', context) def products(request): products = Product.objects.all() return render(request, 'products.html', {'products':products}) def createOrder(request, pk): OrderFormSet = inlineformset_factory(Customer, Order, fields=('Product_Name', 'status'), extra=10 ) customer = Customer.objects.get(Customer_ID=pk) formset = OrderFormSet(queryset=Order.objects.none(),instance=customer) … -
The view register.views.ActivateAccountView didn't return an HttpResponse object. It returned None instead
Request Method: GET Request URL: http://localhost:8000/activate/MTA/adw60x-512068e272684badad26f51a29e1412f/ Django Version: 3.1.3 Exception Type: ValueError Exception Value: The view register.views.ActivateAccountView didn't return an HttpResponse object. It returned None instead. Exception Location: E:\python\soalnesia\venv\lib\site-packages\django\core\handlers\base.py, line 307, in check_response Python Executable: E:\python\soalnesia\venv\Scripts\python.exe Python Version: 3.9.0 Python Path: ['E:\python\soalnesia\soalnesia', 'C:\Users\uec\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\uec\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\uec\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\uec\AppData\Local\Programs\Python\Python39', 'E:\python\soalnesia\venv', 'E:\python\soalnesia\venv\lib\site-packages'] Server time: Wed, 25 Nov 2020 04:46:31 +0000 class ActivateAccountView(View): def get(self,request,uidb64,token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.Objects.get(pk=uid) except Exception as identifier: user=None if user is not None and generate_token.check_token(user,token): user.is_active=True user.save() messages.success(request, 'ACCOUNT IS ACTIVATE') return redirect('login') else: return render(request,'auth/activate_failed.html', status=401) path('activate///',views.ActivateAccountView.as_view(), name='activate'), Hi, {{user.username}} Please click this link below to verify your account http://{{domain}}{% url 'activate' uidb64=uid token=token %} -
update the choice list of django model using django Admin panel
my model is currently as follows : class Food(model.Model): CUISINE_CHOICES = ( ('1', 'Chinese'), ('2', 'French'), ('3', 'Italian'), ('4', 'Indian'), ('5', 'Japanese'), ('6', 'Moroccan'), ('7', 'Spanish'), ('8', 'Thai'), ) Cuisine = models.CharField(max_length = 20,choices = CUISINE_CHOICES,default = '1') Dish = models.CharField(max_length=200, blank=True) Is there a way by which I can update the CUISINE_CHOICES list in future from the admin panel. Say I need to add Arabian as the 9th cuisine. I know that manually updating the cuisine_choices list will resolve it, I want to know if i can do the same from Admin Panel. If yes, How ? I've searched for similar questions/ solutions but could not find one that matches my requirement. TIA. -
Inlineformset_factory saving parent without child and not displaying validation errors if child is none
I am having 2 issues, one if you submit and click back and then submit again it duplicates the instance in the database - in this case Household. In addition it is saving the parent 'Household' without the child 'Applicants' despite me setting min_num=1 can someone point me in the right direction to resolve this issue. Many thanks in advance class Application(models.Model): name = models.CharField(max_length=100, blank=True, null=True) application_no = models.CharField(max_length=100, unique=True, default=create_application_no) created_date = models.DateTimeField(auto_now_add=True) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) class HouseHold(models.Model): name = models.CharField(max_length=100) application = models.ForeignKey(Application, on_delete=models.CASCADE) no_of_dependents = models.PositiveIntegerField(default=0) class Applicant(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) household = models.ForeignKey("HouseHold", on_delete=models.CASCADE) forms.py class ApplicationForm(ModelForm): class Meta: model = Application fields = ( "name", ) class ApplicantForm(ModelForm): class Meta: model = Applicant fields = [ "household", "first_name", "last_name" ] class HouseHoldForm(ModelForm): class Meta: model = HouseHold fields = [ 'name', 'application', 'no_of_dependents' ] def __init__(self, application_id=None, *args, **kwargs): super(HouseHoldForm, self).__init__(*args, **kwargs) self.fields['name'].label = 'House Hold Name' if application_id: self.fields['application'].initial = application_id self.fields['application'].widget = HiddenInput() ApplicantFormset = inlineformset_factory( HouseHold, Applicant, fields=('household', 'first_name', 'last_name'), can_delete=False, extra=1, validate_min=True, min_num=1) views.py class HouseHoldCreateView(LoginRequiredMixin, generic.CreateView): model = models.HouseHold template_name = "households/household_create.html" form_class = HouseHoldForm def get_parent_model(self): application = self.kwargs.get('application_pk') return application def …