Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Query on User related Object in Django
In my Application I am trying to query a field which in depth requires a reverse lookup. Let me explain by Models Models.py class User(AbstractUser): is_employee = models.BooleanField(default=False) is_client = models.BooleanField(default=False) class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) client_name = models.CharField(max_length=500, default=0) class MaterialRequest(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) flows = models.ManyToManyField(MaterialRequestFlow) is_allocated = models.BooleanField(default=False) class Allotment(models.Model): transaction_no = models.IntegerField(default=0) dispatch_date = models.DateTimeField(default=datetime.now) send_from_warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE) sales_order = models.ForeignKey(MaterialRequest, on_delete=models.CASCADE) Now I want to query Allotment which are created by a particular Client. In the frontend I have a dropdown of Clients which sends the id of the Client Here's my function for this: Views.py class AllotmentReport(APIView): permission_classes = (permissions.IsAuthenticated,) def get(self, request, *args, **kwargs): cname = self.kwargs['cname'] if self.kwargs['cname']: items = Allotment.objects.filter(sales_order__owner??? = cname).order_by('-id') #Need Help Here else: items = Allotment.objects.all().order_by('-id') serializer = AReportSerializer(items, many=True) return Response(serializer.data, status=status.HTTP_201_CREATED) Also I'd like to know If there is a better alternative to do that -
How can I sort a list of models considering one element of a many-to-many relation?
We're building an API using Django Rest Framework where I have the following schema: class Main(models.Model): name = models.CharField(default=None, max_length=200, blank=True, null=True) # [...] class Attribute(models.Model): main = models.ForeignKey('Main', on_delete=models.CASCADE, related_name='attrs') code = models.CharField(max_length=50, null=True) value = models.CharField(max_length=50, null=True) I want to build a queryset (paginated) for a list of Main objects and I would like to sort them using the "value" of certain Attribute "code". For example, if we suppose three attributes are: "age" (8-18), "grade" ("A", "B", "C", etc.), "stars" (0-5) and Main were "students" I would like to be able to build a queryset for the list of students ordered by "age" and "grade" values. I've tried something like: queryset = Main.objects.filter(id__in=ids).filter(attrs__code='age').order_by(attrs_value) Extra: Woud I be able to reach a multiple attr order? -
How to filter certain fields in Django Rest Framework
I have two models, one is Product and second is paymentInvoice that are connected by a foreign key. I want to get all the invoice details where the product field has the qty_amount='20L'. Product Model class Product(models.Model): Qty_Choices = ( ('250ml', '250ml'), ('500ml', '500ml'), ('1L', '1L'), ('5L', '5L'), ('20L', '20L') ) slug = models.CharField(max_length=200, unique=True) name = models.CharField(max_length=200) available = models.BooleanField(default=True) description = models.TextField(blank=True) image = models.ImageField(default='default_product.jpg', upload_to='product_photos') category = models.CharField(max_length=200) qty_amount = models.CharField( max_length=20, choices=Qty_Choices, default='250ml') price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.name paymentInvoice Model class paymentInvoice(models.Model): class paymentStatus(models.TextChoices): PENDING = 'Pending' PAID = 'Paid' DELIVERED = 'Delivered' class paymentMode(models.TextChoices): MPESA = 'Mpesa' BANK = 'Bank' CHEQUE = 'Cheque' CASH = 'Cash' shipping_address_owner = models.ForeignKey( ShippingAddress, on_delete=models.CASCADE, related_name="customer_invoice") product = models.ManyToManyField( Product, related_name='product_invoice') mode = models.CharField(max_length=20, choices=paymentMode.choices, default=paymentMode.MPESA) date = models.DateField(default=datetime.now) invoice_id = models.CharField(max_length=50, unique=True) quantity = models.PositiveSmallIntegerField() status = models.CharField( max_length=20, choices=paymentStatus.choices, default=paymentStatus.PENDING) total_payment = models.DecimalField(max_digits=20, decimal_places=2) def __str__(self): return self.shipping_address_owner.customer.name My views.py file for my invoice is displayed below. class paymentInvoiceListCreateView(ListCreateAPIView): """ ListCreateAPIView executes both 'GET' and 'POST' requests. i.e listing a queryset or creating a model instance. """ serializer_class = paymentInvoiceSerializer queryset = paymentInvoice.objects.order_by( '-date').filter(product.qty_amount="20L") The filter method i used above does not work. Kindly … -
Django Channel - Redis integration error : aioredis.errors.ReplyError: ERR unknown command 'EVAL'
I am new to Django channels and following the tutorial ( https://channels.readthedocs.io/en/latest/tutorial/part_2.html) As Redis does not support Windows 7 I downloaded Redis version 2.4 from (https://github.com/dmajkic/redis/downloads) When I try to access the Redis from Django shell I got error as mentioned in the subject. $ python3 manage.py shell >>> import channels.layers >>> channel_layer = channels.layers.get_channel_layer() >>> from asgiref.sync import async_to_sync >>> async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'}) >>> async_to_sync(channel_layer.receive)('test_channel') # ERROR OCCURED AFTER THIS STEP As you can see below, the Redis folder , it start dev server at port 6379. -
Field 'id' expected a number but got '_delacruzjuan'
I am trying to put a decimal field form in my accounts.html but whenever I visit the page I created, I always get this traceback error Here is my code in my views.py class UserAccountsView(UpdateView): """ Shows user total income and withdraw money. """ model = User fields = ['money_withdraw'] # Keep listing whatever fields template_name = 'users/accounts.html' def form_valid(self, form): """ Checks valid form and add/save many to many tags field in user object. """ user = form.save(commit=False) user.save() form.save_m2m() return redirect('users:user_account', self.object.username) def get_success_url(self): """ Prepares success url for successful form submission. """ return reverse('users:user_account', kwargs={'username': self.object.username}) Here is the portion of my accounts.html containing the money_withdraw I am trying to put. <form method="post" novalidate enctype="multipart/form-data"> {% csrf_token %} <div class="container"> <div class="form-row"> <div class="form-group col-md-12 mb-0"> {{ form.money_withdraw | as_crispy_field}} </div> </div> <br> <div class="col text-center"> <button type="submit" style="color:#FFFFFF; background-color:#213b52; border: 3pt lightgrey" class="btn btn-success">Request Money</button> </div> </form> I already tried putting the money_withdraw to other .html and it is working fine. I even tried putting it on admin.py and I can access and edit it on the admin page. -
Reducing queries on serialization with SerializerMethodField
I currently have a serializer which uses two SerializerMethodField that access the same nested object, resulting in two db calls: # models.py class Onboarding(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) is_retailer_created = models.BooleanField(default=False) is_complete = models.BooleanField(default=False) # views.py class StateView(RetrieveAPIView): serializer_class = serializers.UserSerialiser def get_object(self): return self.request.user # serializers.py class UserSerialiser(serializers.ModelSerializer): is_onboarded = serializers.SerializerMethodField() is_loyalty_onboarded = serializers.SerializerMethodField() class Meta: model = models.User fields = ('is_onboarded', 'is_loyalty_onboarded') def get_is_onboarded(self, obj): onboarding = obj.onboarding_set.first() if onboarding: return onboarding.is_retailer_created return False def get_is_loyalty_onboarded(self, obj): onboarding = obj.onboarding_set.first() if onboarding: return onboarding.is_complete return False I'd like to roll this into one call if possible. Normally it would be possible to just use prefetch_related, but since the get_object is returning the specific user (and not a queryset) I don't think that solution works here. Is there a way to prefetch the Onboarding model with the user? Or failing that have a single call to Onboarding instead of two? -
Creating a website like Amazon where user can create an account for selling their products with Django
I am basically working on creating a website like Amazon where user can create an account for selling their products with Django, how do I achieve that, should I create a Django group name shopkeepers, kindly please tell me what is the best way to do that -
Django Pagination not working as expected
I am new to Django, and trying to paginate a dictionary objects,However I am unable to so and not getting what's wrong with my code. Above I have posted my View along with template code. class Search(ListView): paginate_by = 5 def get(self, request): if 'search' in request.GET: search = request.GET['search'] url = 'https://api.stackexchange.com/2.2/search/advanced?&site=stackoverflow' params = dict(item.split("=") for item in search.split(",")) req = PreparedRequest() req.prepare_url(url, params) stackoverflow_url = req.url response = requests.get(stackoverflow_url) data = response.json() #Data will be like this # data={{'tag':'python','question':'some question'},{'tag':'java','question':'some question'}} # n here is 2 paginator = Paginator(list(data), 5) page_number = request.GET.get('search') page_obj = paginator.get_page(page_number) return render(request, 'stackoverflow.html', { 'data': data, 'page_obj': page_obj }) Above is my template {%if data %} <div class="container"> <div class="row"> <!-- Blog Entries Column --> <div class="col-md-8 mt-3 left"> {% for key,value in data.items %} <div class="card mb-4"> <div class="card-body"> <h2 class="card-title">{{ value.title }}</h2> <p class="card-text text-muted h6">{{ value.creation_date }} </p> <p class="card-text text-muted h6"> Asked By</p> <a href="{{value.owner_link}}">{{value.display_name }} </a> <p class="card-text"></p> <a href="{{value.link}}" class="btn btn-primary">Read More &rarr;</a> </div> </div> {% endfor %} </div> </div> </div> <div class="pagination"> <span class="page-links"> {% if value.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ page_obj.previous_page_number }}">previous</a> {% endif %} <span class="page-current"> Page {{ page_obj.number }} of … -
why my file input multiply and send the same image twice?
so i have this ajax script to shown the image that the admin send to client but i have problem is that everytime the admin upload new image the script keep doubleing and send image twice for example if the admin upload first image it shown one image and the admin add a new image <-- and here the problem start it double the image that being upload (now it sending the same image twice and so on) how can i fix this? i don't know if my backend is the problem or my ajax script, here is my code and thank you. my ajax script $("#btn-file-input").on("click",function(){ $("#file-input").trigger("click"); $('#file-input').change(function () { var value = $(this).val(); var form = new FormData(); var dat = $('#file-input').prop('files')[0]; console.log(dat) form.append("image-user",dat); form.append("id_user",id_user); for(var q of form.entries()){ console.log(q[0]+ ', ' + q[1]); } $.ajax({ processData: false, contentType: false, async: false, cache: false, type: "POST", url: "updateimage", data: form, success: function(result) { var result_json = JSON.parse(result) console.log(result_json) } }); }); }); my backend @csrf_exempt def admin_send_image(request): data_ajax_r = request.FILES.get('image-user') id_user = request.POST.get('id_user') user = UserMessage.objects.get(line_id=id_user) admin_now = Account.objects.get(id=request.user.id) file_storage = FileSystemStorage() file_storage.save(data_ajax_r.name,data_ajax_r) url_object = file_storage.url(data_ajax_r.name) url_to_line ='https://c93c90ff8ee8.ap.ngrok.io'+url_object line_bot_api.push_message(user.line_id,[ImageSendMessage(url_to_line,url_to_line)]) ctx = {"admin_name":admin_now.username,"file_name":url_object,"admin_image":"/media/"+str(admin_now.gambar)} return HttpResponse(json.dumps(ctx)) here is screen shot … -
django check if a field has changed
This is my update function, where I can update my order details. In this form, I have three fields dispenser, cargo box, and packs. Every time I change other fields and update the form. The values in those three fields get subtracted again. I want to make sure only if I make changes to those three fields then it should be subtracted. def update_order(request, pk): order = Order.objects.filter(id=pk).first() form = OrderForm(request.POST or None, user=request.user,instance=order) if request.method == 'POST': if form.is_valid(): packs = form.cleaned_data.get('packs') dispenser = form.cleaned_data.get('dispenser') cargo_box = form.cleaned_data.get('cargo_box') Material.objects.filter(material_name='Packs').update(quantity=F('quantity')-packs) Material.objects.filter(material_name='Dispenser').update(quantity=F('quantity')-dispenser) Material.objects.filter(material_name='Cargo Box').update(quantity=F('quantity')-cargo_box) order = form.save(commit=False) order.updated_by = request.user order.date_updated = timezone.now() if order.scheduled_date is not None and order.status == 'In Progress': order.status = 'Scheduled' order.save() form.save() return redirect('/orderlist/') context = {'form':form} t_form = render_to_string('update_form.html', context, request=request, ) return JsonResponse({'t_form': t_form}) -
How to fetch data from an api in React Native from Django rest framework using axios
This is the context Provider That has my state that is fetched from the rest framework api. import axios from 'axios'; export const PostContext = createContext(); const PostContextProvider = (props) => { const [ posts, setPosts ] = useState([]); useEffect(() => { axios.get('http://127.0.0.1:8000/api/products/') .then(res => { setPosts(res.data) }) .catch(err => { console.log(err); }) }, []); return( <PostContext.Provider value={{ posts }}> {props.children} </PostContext.Provider> ) } export default PostContextProvider** When I try to console log it I get an this error in my emulator console.log Unrecognized event: {"type":"client_log","level":"log","data":["[]"]} Array [] When I check my browser, I got this error. DevTools failed to load SourceMap: Could not load content for http://127.0.0.1:8000/static/rest_framework/css/bootstrap.min.css.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE I tried to configure my backend using cors headers and the code looks like this INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'django_filters', # 'rest_framework_filters', 'shop.apps.ShopConfig', 'cart.apps.CartConfig', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True # CORS_ORIGIN_WHITELIST = ( # 'http://localhost:19002/' # ) -
Issue with Pipfile.Lock while installing pillow with pipenv
Trying to use pillow for images in Django.Using Pipenv to generate the virtual environment.Pillow is getting installed but Pipfile is not able to lock properly.Below is the Pipfile. name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] [packages] django = "==3.0.1" psycopg2-binary = "==2.8.4" django-crispy-forms = "==1.8.1" django-allauth = "==0.41.0" [requires] python_version = "3.7" -
Django - Updated data is not saving to db
I want to change Branch field of Blank model in a given range. For example, changing Blank model's Branch field with numbers from 1 to 3. Here are my codes: views.py: @login_required(login_url='sign-in') def blanks(request): if request.method == 'POST' and 'create-blank' in request.POST: form = CreateBlankForm(request.POST) if form.is_valid(): form.save() # here happens updating process elif request.method == 'POST' and 'share-blank' in request.POST: form = CreateBlankForm(request.POST) if form.is_valid(): form.update() else: form = CreateBlankForm() blank_list = Blank.objects.all().order_by('-created') context = { 'form': form, } return render(request, 'blank.html', context) forms.py: class CreateBlankForm(ModelForm): def save(self, commit=False): blank = super(CreateBlankForm, self).save(commit=False) number_of_objects = range(blank.number_from, blank.number_to+1) for i in number_of_objects: Blank.objects.create( blank_series = blank.blank_series, blank_number = i, branch=blank.branch, number_from = blank.number_from, number_to = blank.number_to ) def update(self, commit=False): shared_blank = super(CreateBlankForm, self).update(commit=False) number_of_objects = range(shared_blank.number_from, shared_blank.number_to+1) for i in number_of_objects: Blank.objects.update( branch=shared_blank.branch ) models.py: class Blank(models.Model): blank_series = models.CharField(_('Blankın seriyası'), max_length=3) blank_number = models.IntegerField(_('Blankın nömrəsi'), blank=True, null=True) branch = models.ForeignKey(Branch, on_delete=models.CASCADE, blank=True, null=True) number_from = models.IntegerField() number_to = models.IntegerField() def __str__(self): return self.blank_series -
how to split screen into two halves of 20/80 or 30/70 in HTML?
I have the following structure in HTML: <div class="row"> <div class="col"> <div class="leftside"> ...leftside content here... </div> </div> <div class="col> <div class="rightside> ...rightside content here... </div> </div> </div> However, this results into my page being split into 2 halves. I would like to have my leftside be 30% of the page, and the rightside 70%. How can I do this easily? I'm working in the Django with Bootstrap. -
How to Install mysqlclient for Django in windows 10?
i am new in Django.i want to use Mysql database for my project.i am installing mysqlclient for that, but its showing below error. i am using --pip install mysql-python command for installing mysqlclient Collecting mysql-python Using cached MySQL-python-1.2.5.zip (108 kB) Using legacy setup.py install for mysql-python, since package 'wheel' is not installed. Installing collected packages: mysql-python Running setup.py install for mysql-python ... error ERROR: Command errored out with exit status 1: command: 'f:\xampp\htdocs\django\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\DELL\AppData\Local\Temp\pip-install-ti26jpbi\mysql-python\setup.py'"'"'; file='"'"'C:\Users\DELL\AppData\Local\Temp\pip-install-ti26jpbi\mysql-python\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record 'C:\Users\DELL\AppData\Local\Temp\pip-record-h90u4076\install-record.txt' --single-version-externally-managed --compile --install-headers 'f:\xampp\htdocs\django\include\site\python3.8\mysql-python' cwd: C:\Users\DELL\AppData\Local\Temp\pip-install-ti26jpbi\mysql-python Complete output (24 lines): running install running build running build_py creating build creating build\lib.win32-3.8 copying mysql_exceptions.py -> build\lib.win32-3.8 creating build\lib.win32-3.8\MySQLdb copying MySQLdb_init.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.8\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.8\MySQLdb creating build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants_init_.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\REFRESH.py -> build\lib.win32-3.8\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.8\MySQLdb\constants running build_ext building '_mysql' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/ ---------------------------------------- ERROR: Command errored out with exit status … -
How to setup menu data in Context_processor in Django?
I have category and subcategory store in my database, and subcategory is related to category, I have multiple pages on my website, but I am able to display category in the menu on some pages, but I want to display on all pages, so I found the solution using context_processor, but I am unable to render HTML file there, it only takes data in the dictionary file, please check my code and let me know where I am mistaking. here is my models.py file... class Category(models.Model): cat_name=models.CharField(max_length=225) cat_slug=models.SlugField(max_length=225, unique=True) def __str__(self): return self.cat_name class SubCategory(models.Model): subcat_name=models.CharField(max_length=225) subcat_slug=models.SlugField(max_length=225, unique=True) category = models.ForeignKey('Category', related_name='subcategoryies', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.subcat_name here is my context_processor.py file... from django.shortcuts import render from dashboard.models import Category, SubCategory def context_categories(request, cat_slug): category = Category.objects.all().order_by('-created_at') return render(request, "base.html", {'category':category}) included this file in settings.py file under TEMPLATES section 'mainpage.context_processors.context_categories', here is my base.html file... {% for cat in category %} <li> <a href="javascript:void()">{{cat.cat_name}}</a> <ul> {% for subcat in cat.subcategoryies.all %} <li><a href="/subcategory/{{subcat.subcat_slug}}">{{subcat.subcat_name}}</a></li> {% endfor %} </ul> </li> {% endfor %} -
Issue in accessing child model objects from parent model in Django
I am creating a blogging website. I want to display all the articles posted by any particular writer/user. I have created the 'Post' model as the child of the 'Writer' model. I wanna display all the articles of the user in his profile. But I can't access the Post('s title) from the parent class, i.e., Writer class. (I searched a few answers from the internet. Didn't help.) I am getting the error: 'Writer' object has no attribute 'post_set' models.py: class Writer(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) email = models.EmailField(unique=True) profile_pic = models.ImageField(default='profile.png', upload_to = 'Bloggers') def __str__(self): return self.user.username class Post(models.Model): title = models.CharField(max_length=25) cover = models.ImageField(upload_to='Blog Image') content = models.TextField() post_writer = models.ForeignKey(Writer,null=True, related_name="tags", related_query_name="tag", on_delete=models.CASCADE) def __str__(self): return self.title views.py: def profile(request, pk): writer = Writer.objects.get(id=pk) print(writer.post_set.all()) Error received: 'Writer' object has no attribute 'post_set' -
How can I deal with 'str' object has no attribute '_meta' error on my django project
I have django project that have a form to upload data which save at my database. But there are some problems which I cannot deal with. I try to find documentations to deal with problem, but I can't find which can help me. views.py from django.shortcuts import render,redirect from django.contrib.auth.models import User,auth from exam.functions.functions import handle_uploaded_file from django.http import HttpResponse from exam.forms import Examinationform from exam.models import Examination import json # Create your views here. def upload1(request): if request.method == 'POST': main=[] exam = Examinationform(request.POST, request.FILES) if exam.is_valid(): for _file in request.FILES.getlist('fileexam'): _file = request.FILES['fileexam'] #devide list of files. filename = _file.name main.append("filename") handle_uploaded_file(_file) Examination.namefileexam = json.dumps(main) Examination.category = request.POST.get('category') try: Examination.notation = request.POST.get('notation') except AttributeError: Examination.notation = '' try: Examination.name = request.POST.get('name') except AttributeError: Examination.name = '' Examination.save('self') exam = Examinationform() main.clear() return HttpResponse("File uploaded successfuly") else: exam = Examinationform() return render(request,'uploadfileexam1.html',{'form':exam}) Models.py from django.db import models from django import forms class Examination(models.Model): namefileexam = models.TextField(null=True) notation = models.CharField(max_length=78, blank=True, null=True) category = models.CharField(max_length=25) name = models.CharField(max_length=25, blank=True, null=True)` enter code here forms.py from django import forms from exam.models import Examination BOSS_CHOICES=( ('sheets', 'sheets'), ('contestexams', 'contestexams'), ('schoolexams', 'schoolexams'), ('others', 'others'), ) class Examinationform(forms.Form): fileexam = forms.FileField(label = 'เลือกไฟล์', required … -
How to use VSCODE Live Server with templated html?
I'm a web developer who primarily uses Django and is used to using templatized code with Jinja and what not. The Live Server vscode extension is SUPER valuable, but seems to not be able to work with ANY Templating from what I've researched (actually, I couldn't even find another question, but I'm sure it's out there.) I want to use Live Server without having to copy and paste the stuff in the head tag, or the same navbar / footer over and over and over again. Do I have to choose between having templated HTML and using Live Server? If not, how can I do this with Live Server? For example: base.html <!-- DOCTYPE html --> <html> <head> </head> <body> <main> <!-- Where I want the other page's code to be --> </main> </body> </html> Then with my other html pages, I want to not link the other pages: other_page.html <!-- Between the main tag in the other page --> <div>Added code but on a different page</div> <!-- End of the code --> I'm more than open to using some front-end framework like view or react if this will work with liveserver. Thanks in advance! :) -
How can I use concatenation within a request.POST.get() function? (django/python)
I was trying to iterate request.POST.get() to get some inputs from my view's corresponding html file using concatenation. However, no matter whether the input is filled, it always says that the input returns the fallback. (As in the default response that the programmer gives.) Does anyone know how to solve this? I'm trying to make it so it adds each choice to the set of choices for each question. create.html {% block title %}Create a Poll{% endblock title %} {% block header %}Create:{% endblock header %} {% load custom_tags %} {% block content %} {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'polls:create' %}" method="post"> {% csrf_token %} {% for field in questionfields %} {% if field == 'question_text' %} <label for="{{ field }}">{{ field|capfirst|replace }}:</label> <input type="text" name="{{ field }}" id="{{ field }}"> <br> {% endif %} {% endfor %} <br> {% for choice in choicenumber|rangeof %} <br> <label for="choice{{ forloop.counter }}">Choice {{ forloop.counter }}</label> <input type="text" name="choice{{ forloop.counter }}" id="choice{{ forloop.counter }}"> <br> {% endfor %} <br> <br> <input type="submit" value="Create" name="submit"> </form> {% endblock content %} views.py def create(request): choicenumber = 3 context = { 'questionfields': Question.__dict__, 'choicenumber': choicenumber, } submitbutton = request.POST.get('submit', False) … -
Get authentication type from request in a view of Django
In my project, I use 2 authentication backends: LDAPBackend and ModelBackend(Django's default). User can log in by using LDAP account or Django's account. How can I get authentication type from request in a view? Settings.py: AUTHENTICATION_BACKENDS = [ 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ] Views.py: def my_function(request): #I want to get authentication type here return render(request, "index.html") -
Azure search - Create Index - JSON decode error
I'm using the django framework. I'm trying to create an index in the Azure portal using the REST api tutorial they have provided. I'm getting the following error when I send my post request. JSONDecodeError at /createIndex This is my method. @csrf_exempt def createIndex(request): endpoint = 'https://service.search.windows.net/' api_version = '2020-06-30' url = endpoint + "indexes" + api_version index_schema = { "name": "hotels-quickstar11t", "fields": [ {"name": "HotelId", "type": "Edm.String", "key": "true", "filterable": "true"}, {"name": "HotelName", "type": "Edm.String", "searchable": "true", "filterable": "false", "sortable": "true", "facetable": "false"}, {"name": "Description", "type": "Edm.String", "searchable": "true", "filterable": "false", "sortable": "false", "facetable": "false", "analyzer": "en.lucene"}, {"name": "Description_fr", "type": "Edm.String", "searchable": "true", "filterable": "false", "sortable": "false", "facetable": "false", "analyzer": "fr.lucene"}, {"name": "Category", "type": "Edm.String", "searchable": "true", "filterable": "true", "sortable": "true", "facetable": "true"}, {"name": "Tags", "type": "Collection(Edm.String)", "searchable": "true", "filterable": "true", "sortable": "false", "facetable": "true"}, {"name": "ParkingIncluded", "type": "Edm.Boolean", "filterable": "true", "sortable": "true", "facetable": "true"}, {"name": "LastRenovationDate", "type": "Edm.DateTimeOffset", "filterable": "true", "sortable": "true", "facetable": "true"}, {"name": "Rating", "type": "Edm.Double", "filterable": "true", "sortable": "true", "facetable": "true"}, {"name": "Address", "type": "Edm.ComplexType", "fields": [ {"name": "StreetAddress", "type": "Edm.String", "filterable": "false", "sortable": "false", "facetable": "false", "searchable": "true"}, {"name": "City", "type": "Edm.String", "searchable": "true", "filterable": "true", "sortable": "true", "facetable": "true"}, {"name": "StateProvince", "type": "Edm.String", … -
join 2 tables with ForeignKey in django
i have an image table which is made of all of my images and i have a product table i want to use more than one image in my product table how is this possible ? i dont want to write ForeignKey in image table because i want to use my images somewhere else models.py from django.db import models class Image (models.Model): path = models.CharField(max_length=200) class Product (models.Model): name = models.CharField(max_length=100) price = models.FloatField(default=0) description = models.TextField(max_length=10000) image = models.ForeignKey(Image,on_delete=models.DO_NOTHING) -
django-user-accounts signup doesn't work propely
I've started new project with django-user-accounts. This is my html form for sign up: <form class="" action="{% url 'account_signup' %}" method="post"> {% csrf_token %} <div class="form-group"> <input class="form-control" type="text" id="loginInput" name="username " value="" placeholder="Имя пользователя"> </div> <div class="form-group"> <input class="form-control" type="email" id="emailInput" name="email" value="" placeholder="Адрес эл. почты"> <small id="emailHelp" class="form-text text-muted">Мы не распростаняем ваши личные данные третьим лицам.</small> </div> <div class="form-group"> <input class="form-control" type="password" id="pwdInput" name="password" value="" placeholder="Пароль"> </div> <div class="form-group"> <input class="form-control" type="password" id="pwdRepeatInput" name="password_confirm" value="" placeholder="Повторите пароль"> </div> <input type="hidden" name="next" value="{{ redirect_field_value }}" /> <div class="reg__btn"> <button type="submit" class="btn btn-block btn-outline-warning">Регистрация</button> </div> </form> and this is my urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('account/overview', include("account_extend.urls")), path('account/', include("account.urls")), path('', get_index) ] When i go to /account/signup/ i get my html template with form. After that i fill the inputs of it and hit submit button, but nothing happens. I only get my page reloaded, without user creation. At the same time, /account/login/ and /account/logout/ pages work properly. What i'm doing wrong? -
how to calculate between to different models field without having connection
hi i need to calculate between to different models field without having any connection imagine i have two models (tables) i want to get profit and income in a storage , Model1 for selling purpose and the other for costs of the company , i need to know profit and incomes , field_1 all selling prices and field_2 all costs of the company class Model1(models.Model): field_1 = models.IntegerField() class Model2(models.Model): field_2 = models.IntegerField() can i calculate something like this model1__field1 - model2__field2 ? i much appreciate your helps