Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django technology implementation of line breaks by number of posts
My problem I am making a shopping mall using Django, Bootstrap I want to implement technology line break when the post becomes 4 I thought if I used col-3 and {$ for %} {% endfor %} it would be divided into four and line breaks. but not working How can i fix it? MY models from django.db import models class Cloth(models.Model): title = models.CharField(max_length=30) explain = models.CharField(max_length=30) price = models.IntegerField(blank=True) def __str__(self): return self.title My views from django.shortcuts import render from .models import Cloth def index(request): post = Cloth.objects.all() return render(request, 'Blog/index.html', {'post':post}) My urls from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] My index.html <div class="container py-3"> <h2 align="center"> Top </h2> </div> <div class="container py-2 px-1"> <div class="row"> {% for p in post %} <div class="card col-3" style="width: 16rem;"> <img src="http://placeimg.com/600/600/any" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title"> {{ p.title }}</h5> <p class="card-text"> {{ p.explain }}</p> <p> {{ p.price }}</p> </div> </div> {% endfor %} </div> -
How to discover the reason for a N+1 query in DRF serializer
I have a Django REST Framework -based project where one of the endpoints is super slow. Turns out it's a N+1 queries problem, where each of the returned row, of hundreds of rows, causes an additional query. The endpoint is not supposed to do any joins or additional queries, just return the contents of a single table, filtered a bit. The model for that table contains a few foreign keys, but none of the referents are supposed to be accessed, only the ID's are supposed to be rendered as JSON and sent to the client. A bit of trial and error reveals that it's DRF's Serializer that causes the additional queries: class FooSerializer(serializers.ModelSerializer): class Meta: model = Foo fields = ["data_field_a", "data_field_b", "bar_id", "qux_id"] When I comment bar_id out in the serializer, the query becomes as fast as expected. What's surprising is thatqux_id, even though the field is basically identical to bar_id, doesn't cause such a slowdown. I read https://www.django-rest-framework.org/api-guide/relations/ and among other stuff, tried setting depth = 0 in the Meta class. Also, I understand that using select_related or prefetch_related whould essentially serve as a quick fix for the problem, but strictly saying, those shouldn't be needed for this … -
dj-stripe (django) - How to distinguish between free trial vs. paying user?
How do you distinguish between a user who is on free trial vs. someone who is actually paying? Say it's a 30 day trial.. but someone decides to upgrade on day 10... so you can't go by date. -
Django choice field is not returning data through API endpoints
I have a custom User model and Profile model. In the Profile model I have 4 attributes: owner - OnetoOne relation with CustomUser gender - IntegerField with choices tuple. ie: (1, 'Male'), default=1 city - CharField country - CharField The serializer is defined with '__all__' fields. But the API endpoint is returning: { "id": 5, "city": null, "country": null } What I'm expecting from the API to return is all the fields defined in Profile Model. like this: { "id": 5, //Here I'm expecting the owners(CustomUser) Fields under user key "gender": 1, "city": null, "country": null } for better understanding please take a look at the code. My Custom User model: class CustomUser(AbstractBaseUser, PermissionsMixin): avatar = models.ImageField(upload_to="avatars/", null=True, blank=True) email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = CustomBaseUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] def get_full_name(self): return self.name def __str__(self): return self.email Profile Model: GENDERS = ( (1, 'Male'), (2, 'Female'), (3, 'Other'), ) class Profile(models.Model): """Model for users profile""" owner = models.OneToOneField( CustomUser, on_delete=models.CASCADE, related_name='profile' ) gender = models.IntegerField(_('Gender'), default=1, choices=GENDERS) city = models.CharField(_('City'), max_length=255, null=True, blank=True) country = models.CharField(_('Country'), max_length=255, null=True, blank=True) def __str__(self): return f'profile-{self.id}-{self.owner.get_full_name()}' Profile Serializer: class ProfileSerializer(serializers.ModelSerializer): """Serializer … -
Permission denied from pre-commit, unable to access local python build
I am trying to commit some recent work and have been unable to get my precommit to work. I have changed permissions for this file, restarted the terminal, etc. Essentially the precommit script refuses to run. Any insight into this? Here is the error message I have been getting. $ git commit -m "test commit" .git/hooks/pre-commit: line 14: C:\Users\Josiah\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\python.exe: Permission denied .git/hooks/pre-commit: line 14: C:\Users\Josiah\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\python.exe: Permission denied also here is my current pre-commit file #!/usr/bin/env bash # File generated by pre-commit: https://pre-commit.com # start templated INSTALL_PYTHON='C:\Users\Josiah\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\python.exe' ARGS=(hook-impl --config=.pre-commit-config.yaml --hook-type=pre-commit) # end templated HERE="$(cd "$(dirname "$0")" && pwd)" ARGS+=(--hook-dir "$HERE" -- "$@") if [ -x "$INSTALL_PYTHON" ]; then exec "$INSTALL_PYTHON" -mpre_commit "${ARGS[@]}" elif command -v pre-commit > /dev/null; then exec pre-commit "${ARGS[@]}" else echo '`pre-commit` not found. Did you forget to activate your virtualenv?' 1>&2 exit 1 fi -
Django Filter name is not defined
I'm trying to filter my Todos by the test_id pulled from the URL. It pulls the id from the URL but it cant seem to filter with todo__test. I have also tried "test", "Todo.test.test_id", "Todo.test". I guess I'm confused about what variable I need to filter and the Django restframework documentation doesn't explicitly show what variable to use. Their example uses "purchaser__username" which I don't understand where it comes from. https://www.django-rest-framework.org/api-guide/filtering/ class TodoList(generics.ListAPIView): queryset = Todo.objects.all() serializer_class = TodoSerializer def get_queryset(self): test_id = self.kwargs['test_id'] return Todo.objects.filter(todo__test == test_id) class Todo(models.Model): test = models.ForeignKey(Test, on_delete=models.CASCADE) content = models.TextField(blank=True) order = models.IntegerField() def __str__(self): return self.content + ' - ' + self.test.test_name class Meta: ordering = ['test_id'] -
Cant upload multilple images using django admin
I have two models: one is the post model that can have multiple linked images. The image model has a foreign key to the post. That is, the images have a foreign key for a single post. When adding a new post I want to upload multiple images at the same time. Here is the code: model.py class Post(models.Model): title = models.CharField(max_length=255) thumbnail = models.ImageField(upload_to='thumbnails') summary = RichTextField() body = RichTextUploadingField() created_at = models.DateField(auto_now_add=True) class Meta: ordering = ['-created_at',] def __str__(self): return self.title class Imagens(models.Model): img = models.ImageField( upload_to = "media/", ) post = models.ForeignKey( "Post", on_delete=models.CASCADE, default=1) admin.py class ImageAdminForm(forms.ModelForm): class Meta: model = Imagens fields = ['img',] def __init__(self, *args, **kwargs): super(ImageAdminForm, self).__init__(*args, **kwargs) self.fields['img'] = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class ImageInline(admin.TabularInline): model = Imagens extra = 1 form = ImageAdminForm class PostAdmin(admin.ModelAdmin): search_fields = ['title'] inlines = [ImageInline,] def save_model(self, request, obj, form, change): obj.save() files = request.FILES.getlist('img') #he gets nothing print(files) for f in files: x = Imagens.objects.create(post=obj,img=f) x.save() admin.site.register(Post, PostAdmin) The problem is that if I save the post object it saves only one image and if I try to get the list of images it gives an empty list. Sorry I'm new to Django and even … -
Checkbox and function in Django
I welcome everyone who answers and helps if possible and thank you all in advance! There is a Django web application that downloads videos from YouTube using the python library. It will convert the video to audio and make a transcript of the text into a file. The question is that there is a variable in the language function that will change the language of text extraction. You need to change the value that corresponds to the video every time. How to make a language selection in a template that supports google web speech. I can't implement this idea, any help is welcome! Links to files at the bottom https://github.com/Erekeakz/Youtube-to-text.git -
Django; How can I display the questions foreign key for a responses table and then saving the responses using Django forms?
Hey I'm working on a survey app that has 7 questions and accepts a 1-3 integer answer for all of them except the last question which is free response. My models.py looks like this: class Question(models.Model): question = models.CharField(max_length=255) class Response(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="response") response = models.IntegerField(validators=[MinValueValidator(0),MaxValueValidator(3)]) respondantEmail = models.EmailField(unique=True) I was planning on storing the 7 questions in the questions table and then have the survey's response split into 7 rows per user submission. I don't know if there's a better approach to this so feel free to direct me towards another way of storing the responses. This works well in my admin view but I can't get it to display properly in the front-end. What I currently have is: Forms.py class ResponseForm(ModelForm): class Meta: model = Response fields = { "response","respondantEmail"} widgets = {"response": forms.TextInput(attrs={'type':"range", 'min':'1','max': '3'})} index.html <form action="{% url 'AssessmentForm:submit' %}" method="post"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Submit"> </form> Now this obviously only displays a single range input field and an email input field but I'd like it to display a range field and an email field for every question there is stored in my Questions table, alongside the question itself. How do … -
How to return variables and store them from ready() method in Django?
I want to initialize a class ONCE when the app starts and store the return variable from the ready() method in apps.py. But I don't see how to return the variables. I searched google and everyone is pointing to apps.py is the preferred location to write these kinds of "Run Only Once" functions. This is my code- class MainPageConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'main_page' def ready(self) -> None: print("Hello ready") load_dotenv(".env") logging.set_verbosity_error() x, y = ModelProcessorCaller()() return x, y How to use this x and y later? What is the better alternative? And also why is the load_dotenv not working in the ready() method even though there is a .env file? The main idea is that I want to run this ModelProcessorCaller only once and store it for future use. -
How can i have same html for multiple categories or pages and then add specific or different data from database to them in django restframework?
In this program i have these two functions in my views.py: def home(request): p=product.objects.all() return render(request,'home.html',{'p':p}) def foods(request): p=product.objects.all() return render(request,'foods.html',{'p':p}) They both have access to the same data from database i mean if i want to post some json with django restframework then foods and home will have the same data because they have the same html: <div class="grid"> {% for i in p%} <div class='card'> <img src="{{i.image}}"></img> <p id="id">{{i.description}}</p> <a href="{{i.buy}}" target='_blank' rel='noopener noreferrer'> <button><span class="price"> ${{i.price}}</span> buy</button> </a> </div> {%endfor%} </div> it is good for me to have just one html for multiple pages and then access to different data from database but if i add some json both of them will contain the same data(for some reason data of foods is empty but it will generate the same number of products based on json like home) I want to know how can you have same html for multiple categories or pages and then add specific or different data from database to them? More details: models.py: from django.db import models # Create your models here. class product(models.Model): image=models.CharField(max_length=500) description=models.CharField(max_length=500) price=models.CharField(max_length=50) buy=models.CharField(max_length=100) serializers.py: from rest_framework import serializers from .models import product class productSerializer(serializers.ModelSerializer): class Meta: model= product fields="__all__" … -
Do I need a User Class in my models? Or is there an easy fix to the foreign key?
Made some modification to my code (there is was some mistake) which created a new problem. Pulling the following error message: "insert or update on table "main_productreview" violates foreign key constraint "main_productreview_user_id_bdd4771a_fk_main_user_id" DETAIL: Key (user_id)=(3) is not present in table "main_user"." (I used to have a User class in my models.py which I have removed as registered Users where not moved to Main. Removing the class sorted the problem, but created this one) What I am trying to do: when a user is logged in, the user can leave a review against a specific product. Any idea? Models.py from django.db import models from django.contrib.auth.models import User from decimal import Decimal import locale import logging class Product(models.Model): name = models.CharField('Product Name', max_length=120, null=True) description = models.TextField(blank=True, null=True) price = models.DecimalField(null=True, max_digits=6, decimal_places=3) #venue = models.ForeignKey(Venue, blank=True, related_name="venue", on_delete=models.CASCADE) tasters = models.ManyToManyField(User, blank=True) image_url= models.URLField('Image Web Address', blank=True) product_url = models.URLField('Product Web Address', blank=True) class Meta: db_table='Product' def __str__(self): return str(self.name) RATING=( (1,'1'), (2,'2'), (3,'3'), (4,'4'), (5,'5'), ) class ProductReview(models.Model): user=models.ForeignKey(User, on_delete=models.CASCADE) product=models.ForeignKey(Product,related_name="comments", on_delete=models.CASCADE) review_text=models.TextField(max_length=250) review_rating=models.IntegerField(choices=RATING,max_length=150, default=0) date_added = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s - %s'%(self.user, self.product, self.date_added) Views.py from django.shortcuts import render, redirect from django.http import … -
Django Form/Models: Adding Row Data To Existing Model Instance Via Form
Description of Database Hello so my problem is that I have a Database with three models: Beacon: Which collects data about hosts that ping back data to it. Command_Node: Which collects commands to be executed by the host in question via a form submitted by the website user. Executed_Commands: Which will collect any Commands contained within a Command_Node when they are collected through a query by a connecting machine via a function to be implemented, it will also delete the Commands in a Command_Node as they are now previous commands. (To be implemented) Problem I want to add multiple commands to a single instance of a Command_Node. Via a form, which allows me to select which host I want to give commands to, and which allows me to select which commands to issue to which host. It should then adds those commands into the current_commands column of that Command_Node as a new row, in the selected Command_Node instance. However I don't know how to do this. I don't need to edit existing commands, I don't need to create a new Command_Node instance as the present code does. I just need to add more rows to existing instances. Any ideas on … -
django.core.exceptions.ImproperlyConfigured: Set the DB_NAME environment variable
I have some troubles. I'm running Django on Ubuntu 20.04. Everytime that I try to set environment variable instead of a string i get an error, when I use python3 manage.py runserver I am getting django.core.exceptions.ImproperlyConfigured: Set the DB_NAME environment variable and I am using docker , docker-compose . my config/settingsfile: env = environ.Env( DEBUG=(bool, False), ) DEBUG = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': env('DB_NAME'), 'USER': env('DB_USER'), 'PASSWORD': env('DB_PASSWORD'), 'HOST': env('DB_HOST'), 'PORT': 5432, } } EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = env('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD') SERVER_EMAIL = EMAIL_HOST_USER DEFAULT_FROM_EMAIL = EMAIL_HOST_USER BACKEND_DOMAIN = '' my .env file: DB_NAME=my_db_name DB_USER=postgres DB_PASSWORD=my_password EMAIL_HOST_USER=my_email_address EMAIL_HOST_PASSWORD=my_password OPENROUTE_API_KEY= MY FILES: enter image description here -
How can i get parameter from a url with django
i have this in the url: localhost/apli/orden/devices/Instalacion%20LB%20+%20BA/ so i need to get the parameter Instalacion%20LB%20+%20BA in a view, how can i do it? this is the url path: path('orden/devices/<str:tipoOrden>/', asignDevicesView.as_view(), name='devices_ot') I clarify that I do not use models where this info is saved, the info comes from a variable from js that I rescue from an object of a web service -
Add the result of a queryset to another queryset
I have 2 models : class ModelA(models.Model): some_fields = .... class ModelB(models.Model): model_a = models.ForeignKey(Model_A) How can I in my viewset of ModelA return a response which will include all ModelB who have model_a as FK ? Can I do it in the get_queryset function ? -
Architecture clarification for Warehouse Django application
everyone, I've started implementing my next project under the Warehouse title :) And actually, I am stuck, again. I guess I've made things too complicated and I don't know how to get out of it. So basic assumptions of Warehouse application: We have a few products You take the goods to the warehouse - the order consists of multiple products. You must know the purchase price and qty for each of them. Some model which will store information about current stock status. I guess it will be Singleton? You sell products from Warehouse - order consists of products sell price, product qty Ok, It seems to me all the above are basic assumptions, below is what I wrote to reach my target but I am pretty sure it doesn't work as is intended. I will be very grateful for any tips and tricks and clarification on architecture. class OrderIn(models.Model): # Standard fields last_updated = models.DateTimeField(auto_now=True, editable=False) ordered = models.DateField(auto_now_add=True, editable=True) received = models.DateField(auto_now_add=True, editable=True) class OrderOut(models.Model): # completed = models.BooleanField(default=False) # Standard fields last_updated = models.DateTimeField(auto_now=True, editable=False) ordered = models.DateTimeField(auto_now_add=True, editable=True) class MiddleOrder(models.Model): order_in = models.ForeignKey(OrderIn, on_delete=models.CASCADE, blank=True, null=True) order_out = models.ForeignKey(OrderOut, on_delete=models.CASCADE, blank=True, null=True) def save(self, *args, **kwargs): super(MiddleOrder, … -
NameError name 'F' is not defined
when i tried this code to add 10 point to user after he fill out one survey it show this error However, I am running into a problem. I get the error: models.py", line 22, in give_coins user.coins = F('coins') + count NameError: name 'F' is not defined models.py class User(AbstractUser): user_pic = models.ImageField(upload_to='img/',default="",null=True, blank=True) coins = models.IntegerField(default=10) def get_image(self): if self.user_pic and hasattr(self.user_pic, 'url'): return self.user_pic.url else: return '/path/to/default/image' def give_coins(user, count): user.coins = F('coins') + count user.save(update_fields=('coins',)) user.refresh_from_db(fields=('coins',)) views.py : @require_http_methods(["POST"]) def submit_survey(request): request.user.give_coins(count=10) form_data = request.POST.copy() form_items = list(form_data.items()) print("form_items", form_items) form_items.pop(0) # the first element is the csrf token. Therefore omit it. survey = None for item in form_items: # Here in 'choice/3', '3' is '<choice_id>'. choice_str, choice_id = item choice_id = int(choice_id.split('/')[1]) choice = Choice.objects.get(id=choice_id) if survey is None: survey = choice.question.survey choice.votes = choice.votes + 1 choice.save() if survey is not None: participant = Participant(survey=survey, participation_datetime=timezone.now()) participant.save() return redirect('/submit_success/') so .. where is the error here -
Problem with Cors and fetching information in react
I have a problem with CORS and fetch with REACT.JS. That's my code: let componentMounted = true; useEffect(() => { const getCars = async () => { const response = await fetch('http://127.0.0.1:8000/dealership/cars/?format=json', {mode: 'no-cors'}); if(componentMounted){ setData(await response.clone().json()); setFilter(await response.json()); } return () => { componentMounted = false; } } getCars(); }, []); In the Chrome console i have this error: Uncaught (in promise) SyntaxError: Unexpected end of input (at Cars.js:17:1) at getCars (Cars.js:17:1) And this: Cross-Origin Read Blocking (CORB) blocked cross-origin response http://127.0.0.1:8000/dealership/cars/?format=json with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details. In the backend i have Django and I have import Cors-headers like this: CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', ] -
Django & POSTMARK API Templates
I'm trying to send a receipt template using POSTMARK API from my Django application but I'm struggling with retrieving multiple items under receipt details. I'm converting my query of items within an order to a list, then from the list, we are serializing it to JSON. Here is the output I get with the JSON with products when I run print: [{'product__name': 'Pokemon 25th Anniversary', 'quanity': 1, 'product__point_price': 100.0}] The serialization all looks correct however if you have multiple items, this becomes an issue. If you look down at my code under receipt details you will see I had to specify [0] before specifying the key name. How do I do this without specifying [0] so I can get all items? Here is my code : VIEW @login_required def checkoutcomplete(request): customer = request.user order = Order.objects.get(customer= customer , complete = False, ) favorites = Favorite.objects.filter(customer = customer.id) today_date = datetime.datetime.today() today_date_strf = datetime.datetime.strftime(today_date,"%m/%d/%Y" ) items = order.orderitem_set.all() data = list(items.values("product__name","quanity","product__point_price")) save_json = json.dumps(data, indent = 2) my_cart_json = json.loads(save_json) #POST MARK API url = "https://api.postmarkapp.com/email/withTemplate" payload = json.dumps({ "From": "", "To": "", "TemplateId": 28132290, "TemplateModel": { "counselor_name": "Fellow Counselor", "student_name": student.student_name, "receipt_id": str(order.transaction_id), "date": today_date_strf, "points": order.get_cart_total, "receipt_details": [ { … -
I am trying pass the obj2 to the frontend but it is not working passing it show the previous values not the updated values in django
when I am trying to pass the context in the post method it works and displays the content in the front-end but when I am trying to pass the context in the get method it is not working. I am trying to change the view based on the filer. if(request.POST): # it is form print("%%%%%%%%%%%%%% post ") chapter_tag = request.POST.get('chap_tag') chapter_name = request.POST.get('chap_name') pub_id_chap = pub_id[0][0] data = { 'chapter_tag': chapter_tag, 'publication_id': pub_id_chap, 'std': int(clas), 'chapter_name': chapter_name } form = chapter_details_master_form(data) if form.is_valid(): form.save() print("*********** ___________") pub_id, summa_list = chapter_list(pub, sub, clas) content = { 'pubk_list': mylist, 'obj': summa_list } redirect(reverse('publication_chapter_list')) return render(request, "publication_chapter_list.html", content) else: print(form.errors.as_data()) #print('$$$$$$$$$$$$',pub,sub,clas) pub_id, summa_list = chapter_list(pub, sub, clas) content = { 'pubk_list': mylist, 'obj': summa_list } print('----------------------------') return render(request, "publication_chapter_list.html", content) if request.method == 'GET': print("%%%%%%%%%%%%%% get ") pub = request.GET.get('publication') clas = request.GET.get('class_value') sub = request.GET.get('subject_id') flag = request.GET.get('flag') request.session['clas'] = clas request.session['sub'] = sub request.session['pub'] = pub pub_id = 0 if flag: pub_id, summa_list = chapter_list(pub, sub, clas) request.session['pub_id'] = pub_id #print('%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%% ',summa_list) chapter_tag_list = summa_list request.session['list_chap'] = summa_list content = { 'pubk_list': mylist, } content['obj'] = chapter_tag_list print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ', content) return render(request, "publication_chapter_list.html", content) -
Django User Model (Employee and Customer)
I am currently working on a mobile app delivery system which involves two types of users: "Employee" and "Customer". Each type of user would have different views and permissions within the app. In addition, each type of user would their own "profile", if you will. The employee's profile purpose is mostly just to designate company roles. The customer's profile is mostly used to save an address for delivery. I am trying to get some opinions on what the best practice to achieve something like this would be. I can't decide if its better to use AbstractBaseUser or AbstractUser. Below is a visual of the models I am wanting to create along with their relationship: Below is the the user/models.py file that I mocked up: class UserTypes(models.Model): type = models.CharField(max_length=100) def __str__(self): return self.type class User(AbstractBaseUser): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField() phone_number = models.CharField(max_length=20) is_employee = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) def __str__(self): return f'{self.first_name} {self.last_name}' # if user.is_employee == True class EmployeeProfile(models.Model): EMPLOYEE_ROLES = ( ('Driver', 'driver'), ('Production', 'production'), ('Manager', 'manager') ) user = models.OneToOneField(User, on_delete=models.CASCADE) role = models.CharField(max_length=12, choices=EMPLOYEE_ROLES) def __str__(self): return self.user # if user.is_customer == True class CustomerProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company = … -
Django, more type of user - I need advice
I need advice. I want make 3 types of user: member (only nickname/password/email) company (nickname/password/email/company/regon + permision for edit model) admin My question is aobut how make model for this users: make big model for member and company together but field which are only for comapny make empty for member. Next to by admin panel i can make group and add "comapny" ppl make 2 type of user (here i will need advice like what i should use on it) and seperate website register for member and company and login should be the same form Thank you for answer -
How can I show posts on page using django TemplateView class?
I used a ready-made template for the blog project. When the button is clicked on the template in home page, a modal opens and login registration processes are performed from here. On the home page, both view and login and register functions should work at the same time. I did login and registration with template view, but this time my posts disappeared. no error on the page or terminal.Anybody can help me to do this! Thanks all! views.py class HomeView(TemplateView): # model = Post template_name = 'blog/index.html' # ordering = ['-last_updated'] def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) context['posts'] = Post.objects.all() print(context['posts']) return context def get(self, request, *args, **kwargs): return self.render_to_response({'loginform': AuthenticationForm(prefix='loginform_pre'), 'registerform': UserCreationForm(prefix='registerform_pre')}) def post(self, request, *args, **kwargs): # self.object_list = self.get_queryset() loginform = _get_form(request, AuthenticationForm, 'loginform_pre') registerform = _get_form(request, UserCreationForm, 'registerform_pre') if loginform.is_bound and loginform.is_valid(): # Process loginform and render response user = loginform.get_user() login(request, user) return redirect('index') elif registerform.is_bound and registerform.is_valid(): user = registerform.save() login(request, user) return redirect('index') return self.render_to_response({'loginform': loginform, 'registerform': registerform}) html template <div class="row"> {% for post in posts %} <div class="col-lg-4 col-md-6 col-12 mb-4"> <div class="blog-item"> <div class="image-blog"> <img src='{{ post.image.url }}' alt="blogImage" class="img-fluid" style="height: 162px;overflow: hidden;"> </div> ... -
intcomma after widthratio in Django templates
I want to do "intcoma" after "widthratio" in the Django template. I thought about it as below, but it doesn't work. {{ {% widthratio p.price 2 1 %}|intcomma }}