Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to convert a range of dates to fill in for a drop down list in django
Trade(models.Model): user_id = models.CharField(max_length=5, null=True, blank=True) nse_index = models.ForeignKey('NseIndex', on_delete=models.CASCADE) trade_expiry = models.DateField(default=THURSDAYS[0], choices=THURSDAYS) trade_type = models.CharField(max_length=25, choices=TRADE_TYPE, default="paper") id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) I need to display the trade_expiry(all thursdays in a year) as a tuple to be displayed as a dropdown list on a form using django pls help -
How can I get return value from A class to class B in python?
class InputForm(forms.Form):ㅤ attachment = forms.FileField() class View1(FormView): template_name = 'main.html' form_class = InputForm def post(self, request) : I_want_this_file = request.FILES.get('attachment') return I_want_this_file class View2: blar blar ..... When there's this structure, Is there any way to get the value of I_want_this_file from a class called View2? I understand that I have to hand over the parameters to get the return value. But I couldn't bring it because of the "request". When a user uploads a file from a template called main.html, I want to take the file itself, put it in the return value I_want_this_file, and bring the file itself to View2. I have to bring that, but it's not my personal project, so there's no other way to add a file field than this. I'd appreciate it if you could help me. -
missing "Meta.model" attribute i can't find the solution
i'am statring create my rest Api with django restapi but my problem is when i create my meta class he show me this error i don't know why Class SoundSerializer missing "Meta.model" attribute and this is my code ` from rest_framework import serializers from sounds.models import Sound class SoundSerializer(serializers.ModelSerializer): class Meta: Model = Sound fields = '__all__'` from django.urls import path from sounds.api.views import SoundList urlpatterns = [ path('list/',SoundList.as_view() , name ='list'), #path('<int:pk>',sounds_names, name='name1'), ] from rest_framework.response import Response from sounds.api.serializers import SoundSerializer from sounds.models import Sound from rest_framework.views import APIView from rest_framework.decorators import api_view # Create your views here. class SoundList(APIView): def get(self,request): sounds =Sound.objects.all() serializer= SoundSerializer(sounds,many=True) return Response(serializer.data) def post(self, request): serializer=SoundSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors) please help me i don't know the problem where is it -
How to detect the Android foldable/flip phone in Djagno
My project displays templates separately from PC/tablet and mobile. views.py ... from django_user_agents.utils import get_user_agent ... class indexView(View): def get(self, request, *args, **kwargs): ... user = get_user_agent(request) if user.is_pc or user.is_tablet: template_name = 'web/index.html' # for PC and Tablet else : template_name = 'mobile/index.html' # for Mobile ... However, Galaxy z fold 4 is recognized as tablet when folded and opened in the Chrome browser. In Samsung's basic browser, when folded, it is displayed as a mobile template. When I checked the userAgent, it included "Safari" instead of "Mobile Safari" in the Chrome browser. Mozilla/5.0 (Linux; Android 13; SM-F936N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36 When the foldable phone is folded, I want to display it as a mobile template on the cover screen in the Chrome browser. Is there a way to detect a foldable phone in Django? Or if you have another good idea, please recommend it :) -
useing logging.getLogger(__name__) in django where can i define logger path
I'm using logger = logging.getLogger(name) where can I define logger path in django. logger.warning("Batch files not found.") logger.error('error1') I want to know the log file path and how will create that path? -
expected str, bytes or os.PathLike object, not BoundField in instaapi
I was trying to post a picture in instagram, I have picture url, caption, instagram username and password in 3 different model, I'm sending primary key of the models in response. class InstagramPost(APIView): @staticmethod def post(request, user_id, pk, attachment_id, *args, **kwargs): user_name = get_user_name(user_id) caption = get_post(pk) url = get_attachment(attachment_id) bot = Bot() bot.login(username=user_name['name'], password=user_name['password'], is_threaded=True) print(user_name['name']) print(user_name['password']) bot.upload_photo(url[r'url'], caption=caption['caption']) print(url['url']) print(caption['caption']) return HttpResponse("posted") -
ReactJs Url is changing on its own on api call
I am hitting an api using my ReactJs application. My code is as follows export const getCustomers = (filters) => { return createAction({ type: GET__CUSTOMERS, action: async () => await axios.get(`${BASE_URL}/customers${filters}`, { data: {}, headers: HEADERS.AUTHENTIC(), }), }); }; In the above code, we can see that in the url -> '${BASE_URL}/customers$' , 'customers' is hard coded, but whenever I am running it actually, it hits the as 'Customers'. The case of c changes on its own. It is nowhere in my application. The same problem is with other routes as well. What can be the possible issue and solutions? I hard coded the api to find the issue but it persists. -
How to access request object of django in react?
I have multiple apps in my Django project but for One app I would like to use react, so I have create two apps one for apis and other for frontend. I used webpack to merge django and react. Now I want to access request.user and user.is_authenticated in my components. How can I access those without calling apis as I am not using token-based authentication so I can not call APIs. views.py def index(request): return render(request,'index.html') urls.py urlpatterns = [ re_path(r'^(?:.*)/?$',index), ] I would like to use is_authenticated in my sidebar everywhere. -
DRF, get foreignkey objects using option
i'm trying to make backend using DRF, and i just faced a problem This is models class SchoolYear(models.Model): title = models.CharField(max_length=255, unique=True) class Student(models.Model): name = models.CharField(max_length=10) school_year = models.ForeignKey( "students.SchoolYear", related_name="school_year", on_delete=models.CASCADE, ) class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = '__all__' Result from POSTMAN when using the option. { "name": "Student Signup", "description": "", "renders": [ "application/json", "text/html" ], "parses": [ "application/json", "application/x-www-form-urlencoded", "multipart/form-data" ], "actions": { "POST": { "name": { "type": "string", "required": true, "read_only": false, }, "school_year": { "type": "field", "required": true, "read_only": false, } } } } But I want to get a result like this. Because I have to deliver this to the front-end developer to make select form I'd like to use this method, so I'd appreciate it if you could let me know if there's any other good method. Thanks. { "name": "Student Signup", "description": "", "renders": [ "application/json", "text/html" ], "parses": [ "application/json", "application/x-www-form-urlencoded", "multipart/form-data" ], "actions": { "POST": { "name": { "type": "string", "required": true, "read_only": false, }, "school_year": [ { "id" : 1, "title": "title1", }, { "id" : 2, "title": "title2", }, { "id" : 3, "title": "title3", }, { "id" : 4, "title": "title4", } ] … -
change color of button after click
I have a question with four answers and I want the button to flash green when the correct answer is selected and red when the wrong answer is selected. How can I do that? i want to solve this problem with django and not with javascript. html {% for q in questions %} {% if q.kategorie == category and q.flaag == True %} {% if questions.has_next %} <br/> <div class="flex-container"> <div class="container1"> <div class="position_startButton"><button type="submit" name="next" value="{{q.question}}" class="nächstefrage_btn">Nächste Frage!</button></div> <div class="game_options_top"> <div class="option"> <p><button class="option_btn" name="next" value="{{erste_frage}}" formaction="{% url 'quiz' %}?page={{ questions.next_page_number }} " type="submit">A: <span id="option_span">{{erste_frage}}</span></button></p> </div> <div class="option"> <p><button class="option_btn" name="next" [ngClass] = value="{{zweite_frage}}" formaction="{% url 'quiz' %}?page={{ questions.next_page_number }} " type="submit">B: <span id="option_span">{{zweite_frage}}</span></button></p> </div> </div> <div class="game_question"> <h1 class="display_question">{{q.question}}</h1> </div> <div class="game_options_bottom"> <div class="option"> <p><button class="option_btn" name="next" value="{{dritte_frage}}" formaction="{% url 'quiz' %}?page={{ questions.next_page_number }} " type="submit">C: <span id="option_span">{{dritte_frage}}</span></button></p> </div> <div class="option"> <p><button class="option_btn" name="next" value="{{vierte_frage}}" formaction="{% url 'quiz' %}?page={{ questions.next_page_number }} " type="submit">D: <span id="option_span">{{vierte_frage}}</span></button></p> </div> </div> </div> <div class="menü"> <button class="menü_button" formaction="{% url 'Example_dashboard' %}" ><i class="fa fa-bars" aria-hidden="true"></i><b> Menü</b></button> <div class="items"> <a href="{% url 'Example_dashboard' %}"> <i class="fa-solid fa-house"></i> Startseite </a> <a href="{% url 'Example_fragenkatalog' %}"> <i class="fa-solid fa-pen"></i> Fragenkatalog </a> <a href="{% url 'statistics' … -
Django cannot display a PDF inline on a web page using <embed> or <object> or <iframe> tags
I am trying to embed a PDF into a web page in Django. This is the message I see in the console: Refused to display 'http://127.0.0.1:8000/' in a frame because it set 'X-Frame-Options' to 'deny'. Here is the function definition in my python file: from django.http import HttpResponse from django.views.decorators.clickjacking import xframe_options_exempt from django.template.loader import render_to_string ... @login_required @xframe_options_exempt def resource_entity_screen(request,pk): ... rendered = render_to_string('classroom/resourcecenter/resource_entity_display.html', \ {'src' : url_src, \ 'embed_pdf' : embed_pdf, \ 'embed_video' : embed_video, \ 'embed_audio' : embed_audio, \ 'embed_image' : embed_image, \ 'obj_type' : obj_type, \ 'image_info' : image_info}) return HttpResponse(rendered) I ncluded this code instead of a straight render because I read in another post that the decorator only works with HttpResponse. However even with this code I am still getting the message shown above (in the console). I did clear my cache and do a reload, and also tried Ctrl-Shift R as well. No change. Can anyone tell me what I am missing? Is there something additional needed in settings.py? I have not tried deploying this to a testing server on the web to see if it just my local testing environment. -
Django media image not showing up in template but can acces it via .../media/thumbnail/image.png
Altough context does render in html, i can use other variables but cant accsess the image. My code is: html: {% for a in Manga %} <div class="manga_container"> <div class="manga_image"> <p>{{a.manga_image}}</p> <img src="{{ x.manga_image.url }}" alt=""> </div> </div> {%endfor%} model: class Manga(models.Model): manga_name = models.CharField(max_length= 255, default="null") manga_image = models.ImageField(upload_to="thumbnail", default="thumbnail/noimage.png") def __str__(self): return f"{self.id}, {self.manga_name}" and lastly view: def Index(request): manga = Manga.objects.all().values() chapter = Chapter.objects.all().values() fansub = Fansub.objects.all().values() context= { "Manga": manga, "Chapter": chapter, "Fansub": fansub, } template = loader.get_template("Index.html") return HttpResponse(template.render(context, request)) ı have used function based views since ı have to deal with multiple models at once. my media and url is as following: import os MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urlpatterns = [ ... ... ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I have put that p tag for me to see its url and as you can see it was in the right place, when i go to 127.0.0.1:8000/media/thumbnail/noimage.png i can see it and it does come up to my screen. i have tried most of the ways i could have think of. I want to see the image on my html and i didnt touch anything so it is basicly default image as i have … -
Image not getting uploaded in Django
I tried to save a record using two different methods but both are not working. Django Form Models (create method) 1 I have created a ModelForm class ProductForm(ModelForm): class Meta: model= ProductDetails fields= ("name","category","subcategory","price","mrp","product_details","main_img","img1","img2","img3") labels={ "name":"Product Name", "product_details":"Description", "category":"Category", "subcategory":"Sub-Category", "price":"Price", "mrp":"MRP", "main_img":"Main Image", "img1":"Image 1", "img2":"Image 2", "img3":"Image 3", } widgets = { 'name':forms.TextInput(attrs={'class':'form-control validate',}), 'product_details':forms.TextInput(attrs={'class':'form-control validate',}), 'category':forms.TextInput(attrs={'class':'custom-select tm-select-accounts',}), 'subcategory':forms.TextInput(attrs={'class':'custom-select tm-select-accounts',}), 'price':forms.TextInput(attrs={'class':'form-control validate',}), 'mrp':forms.TextInput(attrs={'class':'form-control validate',}), 'main_img':forms.FileInput(attrs={'class':'btn btn-primary btn-block mx-auto',}), 'img1':forms.FileInput(attrs={'class':'btn btn-primary btn-block mx-auto',}), 'img2':forms.FileInput(attrs={'class':'btn btn-primary btn-block mx-auto',}), 'img3':forms.FileInput(attrs={'class':'btn btn-primary btn-block mx-auto',}), } Models File # For Product details class ProductDetails(models.Model): name= models.CharField(max_length=100) price= models.FloatField() mrp= models.FloatField() main_img = models.ImageField(upload_to='product_img') img1 = models.ImageField(upload_to='product_img') img2 = models.ImageField(upload_to='product_img') img3 = models.ImageField(upload_to='product_img') category = models.ForeignKey(Category, related_name='produits', on_delete=models.CASCADE) subcategory = models.ForeignKey(SubCategory, related_name='produits', on_delete=models.CASCADE) product_details = RichTextField(blank=True, null=True) trending = models.BooleanField(default=False) def __str__(self): return self.name Method 1 Save record using form.save() getting Form validation error I have tried by removing main_img,img1,img2,img3 from all place (Forms.py, template, views,py). Then there is not validation error and record is getting saved successfully. The validation error is just because of some issue with the image uploading print(form.errors)= <ul class="errorlist"><li>main_img<ul class="errorlist"><li>This field is required.</li></ul></li><li>img1<ul class="errorlist"><li>This field is required.</li></ul></li><li>img2<ul class="errorlist"><li>This field is required.</li></ul></li><li>img3<ul class="errorlist"><li>This field is required.</li></ul></li></ul> def add_product(request): if request.method … -
Django context pass only None value
I have a view where I want to pass a variable to my template, however the value is always passed as None, as shown in numerals 1 , 2 and 3. What am I doing wrong please your help, I know it's a newbie question, actually I'm very newbie. views.py def create_address(request, dni): person = None addresses = None if request.method == 'POST': form = CreateAddressForm(request.POST) if form.is_valid(): try: person = Persona.objects.get(numero_documento=dni) addresses = Direccion.objects.filter(numero_documento=dni) print(f'Persona: {person}') # (1) print person ID. f = form.save(commit=False) f.numero_documento = person f.save() messages.success(request, 'Dirección registrada con éxito.' ) if 'save' in request.POST: return HttpResponseRedirect(reverse('persons:list')) if 'add_data' in request.POST: return HttpResponseRedirect(reverse('persons:create_address', kwargs={'dni': dni})) except Persona.DoesNotExist: person = None messages.error( request, 'El número de DNI no existe en la base de datos.' ) except Direccion.DoesNotExist: addresses = None messages.error( request, 'No se ha registrado ninguna dirección.' ) else: person = None messages.error( request, 'No se pudo registrar la dirección.' ) else: form = CreateAddressForm() template = 'persons/addresses/create_address.html' context = { 'pre_title': 'Direcciones domiciliarias', 'person': person, # (2) The value of "person" is "None". 'form': form, 'addresses': addresses, } return render(request, template, context) template.html (3) Value of "person" is "None". <div class="tab-pane active show" id="tabs-address-data"> Number … -
DRF Response VS Django - JSONResponse
from rest_framework.response import Response from django.http import JsonResponse What is the difference between these two? how can I decide which one should I use? -
How to get IP address of all devices connected on WLAN
Am working on a Django website. Basically, I want to block and IP once it perform an operation, when that Particular IP comes to perform that same operation then the system will not allow it. Now my problem is if a set of devices are connected on the same network and an operation is performed on the site, another person on that same network cannot perform that operation again because the IP has already been used, so how do I get all IP address connected through WLAN. This the code am using import ipaddress import socket import re def is_valid_ip(ip_address): """ Check Validity of an IP address """ try: ip = ipaddress.ip_address(u'' + ip_address) return True except ValueError as e: return False def is_local_ip(ip_address): """ Check if IP is local """ try: ip = ipaddress.ip_address(u'' + ip_address) return ip.is_loopback except ValueError as e: return None def get_ip_address_from_request(request): """ Makes the best attempt to get the client's real IP or return the loopback """ PRIVATE_IPS_PREFIX = ('10.', '172.', '192.', '127.') ip_address = '' x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR', '') if x_forwarded_for and ',' not in x_forwarded_for: if not x_forwarded_for.startswith(PRIVATE_IPS_PREFIX) and is_valid_ip(x_forwarded_for): ip_address = x_forwarded_for.strip() else: ips = [ip.strip() for ip in x_forwarded_for.split(',')] for … -
Python weasyprint unable to find 'gobject-2.0-0' library
While following the installation process for Saleor headless e-commerce, the Python Weasyprint package fails to load the gobject-2.0.0 dependency which I have already installed on my machine using Macport. Below is the source code showing where the error is emitting from after starting the Django server. The file holds utility functions for generating invoices for the plugin file. utils.py import os import re from datetime import datetime from decimal import Decimal import pytz from django.conf import settings from django.template.loader import get_template from prices import Money from weasyprint import HTML # <----------- This what is emitting the error because the # package can't find the needed dependency. from ...giftcard import GiftCardEvents from ...giftcard.models import GiftCardEvent from ...invoice.models import Invoice MAX_PRODUCTS_WITH_TABLE = 3 MAX_PRODUCTS_WITHOUT_TABLE = 4 MAX_PRODUCTS_PER_PAGE = 13 def make_full_invoice_number(number=None, month=None, year=None): now = datetime.now() current_month = int(now.strftime("%m")) current_year = int(now.strftime("%Y")) month_and_year = now.strftime("%m/%Y") if month == current_month and year == current_year: new_number = (number or 0) + 1 return f"{new_number}/{month_and_year}" return f"1/{month_and_year}" def parse_invoice_dates(number: str): match = re.match(r"^(\d+)\/(\d+)\/(\d+)", number) if not match: raise ValueError("Unrecognized invoice number format") return int(match.group(1)), int(match.group(2)), int(match.group(3)) def generate_invoice_number(): last_invoice = Invoice.objects.filter(number__isnull=False).last() if not last_invoice or not last_invoice.number: return make_full_invoice_number() try: number, month, year = parse_invoice_dates(last_invoice.number) … -
I get a form object when I need want to get a form:
Views.py: from django.shortcuts import render, redirect from .forms import UserRegisterForm, UserPostForm from django.contrib.auth.models import User def register(request): if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): form.save() return redirect('home') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form':form}) def profile(request, username): post_form = UserPostForm() context = { 'username': username, 'post_form': post_form, } return render(request, 'users/profile.html', context) urls.py: from django.contrib import admin from django.urls import path, include from users import views as user_views urlpatterns = [ path("admin/", admin.site.urls), path("", include("photoblog.urls")), path("register/", user_views.register, name="register"), path("profile/<str:username>", user_views.profile, name="profile") profile.html: {% extends 'photoblog/base.html' %} {% load crispy_forms_tags %} {% block content %} <h1>Welcome to the {{ username }} profile page</h1> <form method="POST"> {{post_form}} </form> {% endblock %} forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from photoblog.models import Post class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class UserPostForm(): class Meta: model = Post fields = ['title', 'author', 'content', 'date_posted'] Whenever I load up the page, I get an <users.forms.UserPostForm object at 0x7ff183aea670> when I want the actual form to show up on the page. How do I get that to work? I tried uploading UserPostForm() as a variable in the view … -
(Django CBV) Need object be attached to a user with CBV
I implemented this functionality with using FBV, but when I'm trying to use CBV, Objects were created with empty user field. views.py class BlockCreate(CreateView): model = TrainingBlock template_name = 'training_room/create_block.html' form_class = BlockForm success_url = reverse_lazy('gym') def set_user(self, form): form.instance.user = self.request.user return super(BlockCreate, self).set_user(form) models.py class TrainingBlock(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=30) duration = models.IntegerField(default=10) if_ended = models.BooleanField(default=False) def __str__(self): return self.name forms.py class BlockForm(forms.ModelForm): class Meta: model = TrainingBlock fields = '__all__' exclude = ['user'] -
django sql .raw filtering on a string not working
I am trying to filter on a foreign key but getting an error. Current code is: Views.py def kingmailboxcodesshow(request): lname = "King" lockbox_list = MailBoxCodes.objects.raw('SELECT * FROM mailboxcodes WHERE Address_id__contains %s',[lname]) return render(request,"users/mailboxcodesshow.html",{'MailBoxCodes':lockbox_list}) receiving this error: django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''King'' at line 1") I am still really new to django and python, looking at the error I am thinking i need a few less ' around the King, but I am not sure how to make that happen. I have a bunch of addresses in the Address_id and I just want to retrieve all the address with the work King in their street address. I would greatly appreciate any and all assistance. Thank you in advance. -
ImportError: cannot import name 'Random' from 'django.db.models.functions'
Well, I am trying to run my django project in new environment, I installed all of my requirements although every package is installed but it is still giving me below mentioned error. I am not sure but I am guessing it is due to version conflict of some modules. Can anyone help me out? Thanks in Advance :) I looked for existing solutions or someone who faced similar situation but no success. -
drf-yasg doesn't include the "api/" portion of the urls
I'm using drf-yasg to generate a Swagger schema, but it removes the "api/" portion of the url. schema_view = get_schema_view( openapi.Info( title="My API", default_version='v1', description="...", terms_of_service="https://www.google.com/policies/terms/", contact=openapi.Contact(email="hello@mycompany.com"), license=openapi.License(name="BSD License"), ), public=True, permission_classes=[permissions.AllowAny], ) router = routers.DefaultRouter() router.register(r'spaces', SpacesViewSet, basename='spaces') urlpatterns = [ url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'), path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), url(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), path('api/', include(router.urls)), path('api/search-options', SearchPlacesOptionsView.as_view()), ] result on /swagger As you can see for the routes from the drf router, it doesn't include the /api portion of the url. However for the regular api/search-options endpoint it removes the /api portion as well, so I don't think it has something to do with the router. -
Creating a form for each comment jquey and djang
I want for my website in the comments section, when the user clicks on the answer, an input form will be added to the bottom of the same comment, and if there is another form for other comments, they will be hidden. this is my code html and django: <li class="comment" style="margin-right: 100px;"> <div class="comment-body"> <div class="single-comment"> <div class="comment-img" style="margin-left: 50px;"> {% bs_icon 'person' size='65' %} </div> <div class="comment-inner"> <h6 class="commenter"> <a class="hover-flip-item-wrapper" href="#"> <span class="hover-flip-item"> <span data-text="{{ reply.user_name }}">{{ comment.user_name }}</span> </span> </a> </h6> <div class="comment-meta"> <div class="time-spent">آبان 23, 1401 در 12:23 بعد از ظهر</div> <div class="reply-edit"> <div class="reply"> <a class="comment-reply-link hover-flip-item-wrapper" href=""> <span class="hover-flip-item"> <span data-text="Reply" id="reply-comment">پاسخ</span> </span> </a> </div> </div> </div> <div class="comment-text"> <p>{{ comment.text_comment}}</p> </div> </div> </div> </div> <div class="comment-respond reply-form" id="{{ comment.id }}" style="margin-right: 100px;display:none;" > <h4 class="title">پاسخ شما</h4> <form action="#"> <p class="comment-notes"><span id="email-notes">آدرس ایمیل شما منتشر نخواهد شد.</span></p> <div class="row"> <div class="col-12"> <div class="form-group"> <label>پاسخ شما</label> <textarea name="message" placeholder="بنویسید ..."></textarea> </div> </div> <div class="col-lg-6 col-md-6 col-12"> <div class="form-group"> <label>نام <span>*</span></label> <input id="name" type="text"> </div> </div> <div class="col-lg-6 col-md-6 col-12"> <div class="form-group"> <label>ایمیل <span>*</span> </label> <input id="email" type="email"> </div> </div> <div class="col-lg-12"> <div class="form-submit"> <button name="submit" type="submit" id="submit" href="#" class="axil-btn btn-bg-primary w-auto">ارسال پاسخ</button> </div> </div> … -
Web Scraping refreshing in Django Project
I have to create a project with the framework django, and I have to introduce a system of web scraping with bs4. I did it, but I can’t refresh the data. I scrap the data with bs4, requests and time, them display them into my html page. But when I print the data with 3 secondes refreshing with module time, the data are refreshing. But when I display the data into my html page, they don’t actualised them. I would like to be able to scrap and display data from other website into my django app. -
Django multiple table query - convert MySQL to Django (Python) query
I need to figure out how to translate MySQL query into Django (Python) language. Any help? Basically I need to get the total from each table plus the remain total after spend. class Trip(models.Model): name = models.CharField('Name', max_length=254) class Account(models.Model): name = models.CharField('Name', max_length=254) class Wallet(models.Model): trip = models.ForeignKey(Trip, default=1, on_delete=models.SET_DEFAULT) incoming_date = models.DateField(verbose_name='Incoming Date') total = models.DecimalField(('Total'), max_digits=32, decimal_places=2, blank=True, null=True) account = models.ForeignKey(Account, default=1, on_delete=models.SET_DEFAULT) class Expense(models.Model): trip = models.ForeignKey(Trip, default=1, on_delete=models.SET_DEFAULT) outcome_date = models.DateField(verbose_name='Outcome Date') total = models.DecimalField(('Total'), max_digits=32, decimal_places=2, blank=True, null=True) account = models.ForeignKey(Account, default=1, on_delete=models.SET_DEFAULT) SELECT *, (wallet_total - expense_total) AS remain_total FROM ( SELECT account.name, SUM(wallet.total) AS wallet_total FROM account INNER JOIN wallet ON wallet.account_id = account.id WHERE wallet.trip_id=4 GROUP BY account.name ) AS wallet, ( SELECT account.name, SUM(expense.total) AS expense_total FROM account INNER JOIN expense ON expense.account_id = account.id WHERE expense.trip_id=4 GROUP BY account.name ) AS expense;