Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to reference self.something as ForeignKey in Django models.py?
I'm working on a Django project that uses models. I want to somehow access the highest bid on that listing at all times (as listing.highest_bid) or some other way if there's a better solution. What I tried in the code snippet below for the highest_bid doesn't seem to work, it gives me an AttributeError (AttributeError: 'str' object has no attribute 'bids'). How can I access a model's own parameter's values and filter them to my liking? class Listing(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="listings") title = models.CharField(max_length=100) description = models.CharField(max_length=1000) starting_bid = models.PositiveIntegerField() picture = models.TextField(max_length=200, default='static/auctions/notfound.png') category = models.ForeignKey(Category, on_delete=models.CASCADE,related_name="listings") is_active = models.BooleanField() highest_bid = models.ForeignKey("self".bids.aggregate(Max('price')).first()) #["price__max"] # highest bid # listing created on xxxx-xx-xx def __str__(self): return f"{self.title}" class Bid(models.Model): listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="bids") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="bids") price = models.PositiveIntegerField() # time TODO def __str__(self) -> str: return f"Bid #{self.id}" -
Accessing S3 img from plain javascript while using django storages
I have a pretty basic issue am unable to solve. I am serving static files from S3 using Django storages. In my template, I setup img source like this: "{% static 'fun_share/img/logo/logo.svg' %}" while having STATIC_URL = "/static/" Django storages handle the actual img src "translation", ie becomes https://my-bucket.amazonaws.com/static/fun_share/img/logo/logo.svg?..... So far so good. Now, I want to change the image src from plain javascript to I different image (logo-2.svg). What is the best way to handle calling the s3 bucket with proper URL (also considering secrets and keys)? I would expect const logo = document.querySelector(".navbar-brand img"); logo.src = "/static/fun_share/img/logo/logo-2.svg"; to work, but that does not seem to be the case, as the js call is made to the server itself, not redirected to the s3 bucket. Any help much appriciated. -
Django i want create a function which can be run from any page from the website and do its process and return on the same page
Django i want create a function which can be run from any page from the website and do its process and return on the same page What i want to is to create a button to add to cart i have writted function but the time come from returning from the function i use redirect to cart page but i want that there are lots of types of product pages and i want they must redirect to the same page from where they come and use the same function to do that any idea @login_required(login_url='login_signup') def add_cart(request,id): prod = Product.objects.get(id = id) try: cart = Cart.objects.get(cart_id = _cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create( cart_id = _cart_id(request) ) cart.save() try: cart_item = CartItem.objects.get(product = prod,cart = cart) cart_item.quantity = cart_item.quantity + 1 cart_item.save() # print("I was tries") customer = request.user cust = Customer.objects.get(user = customer) # print(f"The customer is {cust}") except CartItem.DoesNotExist: customer = request.user cust = Customer.objects.get(user = customer) # print("Cart except is also being hit") cart_item = CartItem.objects.create( product = prod, quantity = 1, cart = cart, user = cust, ) cart_item.save() return redirect('/cart/cart_page') Here is the function i use to add to cart i want it to redirect … -
Get ressource URI for foreign object in django in a serializer?
Supposing we have the following models: class Person(models.Model): name = models.CharField(max_length=10, blank=True, null=True) class Food(models.Model): person = models.ForeignKey(Person, default=None, on_delete=models.CASCADE) name = models.CharField(max_length=10, blank=True, null=True) I have these models in ModelViewSets and registered them as URLs with Django Rest Framework. And they are accessible as ressource URI successfully, but I want to add field for Food that can return the Person ressource URI. I can hardcode it as follows but I need something better: class Food(models.Model): person = models.ForeignKey(Person, default=None, on_delete=models.CASCADE) name = models.CharField(max_length=10, blank=True, null=True) def get_person_uri(self): return f"http://127.0.0.1:8000/persons/{self.person.id}/" Serializer is as follows: class FoodSerializer(serializers.Model): class Meta: model = Food fields = ["person", "name", "get_person_uri"] Where get_person_uri should take me directly to the parent person URI What solutions can you suggest? -
django query nested list in array
I have a jsonfield in my model (callRecord called participants containing the following data: [ { "acsUser":"None", "spoolUser":"None", "phone":"None", "guest":"None", "encrypted":"None", "onPremises":"None", "acsApplicationInstance":"None", "spoolApplicationInstance":"None", "applicationInstance":"None", "application":"None", "device":"None", "user":{ "id":"1", "displayName":"User One", "tenantId":"some tenant" } }, { "acsUser":"None", "spoolUser":"None", "phone":"None", "guest":"None", "encrypted":"None", "onPremises":"None", "acsApplicationInstance":"None", "spoolApplicationInstance":"None", "applicationInstance":"None", "application":"None", "device":"None", "user":{ "id":"2", "displayName":"User Two", "tenantId":"some tenant" } } ] I want to search the entire json to check if it conjtains a displayName of "User Two" I just can't get it to work. What I tried: recent_user_calls = CallRecord.objects.filter(participants__user__contains = {'displayName':'User Two'}) recent_user_calls = CallRecord.objects.filter(participants__contains = {'displayName':'User Two'}) recent_user_calls = CallRecord.objects.filter(participants__user__contains = [{'displayName':'User Two'}]) recent_user_calls = CallRecord.objects.filter(participants__contains = 'User Two') ecent_user_calls = CallRecord.objects.filter(participants__user__contains = 'User Two') and a million other combinations. None of them work. They all return empty results. searching on a key outside of the user list works fine. IS there a way to search the user list contained in each object of the array? -
How to handle cron-tabs for a Docker-based Django app running on a Linux-based Webapp in Azure, scaled over multiple cloud-instances
I have a Docker-based Django application running on a Linux based Webapp in Azure, which can scale from 1-5 instances. I want to run cron-tabs which run management commands inside the Django application, and found the following approaches: I've found this post, suggesting a bash-script to start the cron-tabs. How to run cronjobs on an azure linux hosted webapp? I've also found this example github on how to set-up cron-tabs inside a docker-container: https://github.com/Adiii717/docker-python-cronjob But the problem is that I can't run it inside the Docker environment, as the cron-jobs then will be run multiple times if the Webbapp is scaled over multiple instances in Azure. I neither can use Azure's Webjobs, as it's not yet available for Linux-based Webapps. The only option I see right now is creating a parallell mirrored Webapp that's restricted to only using one instance from Azure, thus not creating the issue with having cronjobs being run multiple times - but this seems sub-optimal as I need to deploy two web-apps every time I make code change, to have both the "original" application as well as the "cronjobs-application" being run on the same updated version of the codebase. How can I implement a better solution … -
Google line chart not printing in Django
I'm doing a project on covid visualization i.e., when a user selects a particular state, date range, and output type corresponding to the input we get output as a graph for which I'm using Google API to display line charts. The problem occurring now is graph is not displayed on the website but data is passing from backend python views to HTML. HTML <div id="chart_div"> <script type="text/javascript"> google.charts.load('current', {packages: ['corechart', 'line']}); google.charts.setOnLoadCallback(drawBasic); function drawBasic() { var data = new google.visualization.DataTable(); data.addColumn('string', 'X'); data.addColumn('number', {{user_required_type_json|safe}}); data.addRows({{chart_list_json|safe}}); var options = { hAxis: { title: 'Dates', textStyle: { color: '#1a237e', fontSize: 14, fontName: 'Calibri', bold: true }, titleTextStyle: { color:'#1a237e', fontSize: 22, fontName: 'Calibri', bold: true, }, }, vAxis: { title: {{user_required_type_json|safe}}, textStyle: { color: '#1a237e', fontName: 'Calibri', fontSize: 18, bold: true }, titleTextStyle: { color: '#1a237e', fontName: 'Calibri', fontSize: 22, bold: true }, }, title: {{user_input_state_json|safe}}+' '+{{user_required_type_json|safe}}+' Data' }; var chart = new google.visualization.LineChart(document.getElementById('chart_div')); chart.draw(data, options); } </script> </div> views.py import json from django.shortcuts import render from django.http import HttpResponse import requests import datetime as dt def indexview(request): url=requests.get('https://data.covid19india.org/v4/min/timeseries.min.json') json_data=url.json() user_input_state='' user_input_date_from='2021-10-01' user_input_date_to='2021-10-10' user_data_type='' user_required_type='' if request.method == 'POST': user_input_state=request.POST.get('state') user_input_date_from=request.POST['date_from'] user_input_date_to=request.POST['date_to'] user_data_type=request.POST.get('data_period') #cumulative or daily user_required_type=request.POST.get('required_type') #confirmed, recovered..... #To store dates … -
Why does Django run all scripts when `makemigrations` is run?
Whenever I run python manage.py makemigrations it seems that Django executes a script within one of my apps that establishes a connection to an external API which takes some time. Why's that & is there any way to avoid this? This slows down development since the script takes 30 seconds or some. -
Files not uploading to the chosen directory after form validation with Dropzone.js and Django
I am trying to implement a drag & drop function for files in my webpage (now limited to images for testing purposes). I am using Django and Dropzone.js I think I implemented everything properly but for some reason, even the form is validated, the content is not uploaded to the desired folder. forms.py from django.forms import ModelForm from crown_agents.models import FileHistory class UploadFileForm(ModelForm): class Meta: model = FileHistory fields = ('file_image',) models.py from django.db import models from django.contrib.auth.models import User class FileHistory(models.Model): file_image = models.ImageField(null=True, blank=True, upload_to="project_files/") user = models.ForeignKey( User, null=True, blank=True, on_delete=models.SET_NULL, ) timestamp = models.DateTimeField( auto_now_add=True) views.py from django.contrib.auth.decorators import login_required from django.conf import settings from django.shortcuts import HttpResponse, render from .forms import UploadFileForm @login_required def project_page(request): context = {} context['nbar'] = projects if request.method == 'POST': print(request.FILES) form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): # file is saved form.save() return render(request, 'project_page.html', context) print (form.errors) else: form = UploadFileForm() context['form'] = form return render(request, 'project_page.html', context) urls.py from django.conf import settings from django.conf.urls.i18n import i18n_patterns from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views from django.utils.translation import gettext_lazy as _ from . import views urlpatterns = [ … -
Working DRF and JWT returns "detail": "No active account found with the given credentials"
I went through StackOverFlow and none of the solutions seem to fix my problem. I created a superuser and only that superuser is able to obtain an access token and refresh token. While newly created users don't seem to be recognized by the system. I use a custom user class. Here you can view the error serializers.py from rest_framework import serializers from .models import CustomUser from django.contrib.auth.hashers import make_password class RegisterUserSerializers(serializers.ModelSerializer): class Meta: model = CustomUser fields = ('email', 'password') extra_kwargs = {"password": {"write_only": True}} def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance def validate_password(self, value: str) -> str: """ Hash value passed by user. :param value: password of a user :return: a hashed version of the password """ return make_password(value) views.py from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.permissions import AllowAny from .serializers import RegisterUserSerializers from rest_framework_simplejwt.tokens import RefreshToken class CustomUserCreate(APIView): permission_classes = [AllowAny] def post(self, request): reg_serial = RegisterUserSerializers(data=request.data) if reg_serial.is_valid(): newUser = reg_serial.save() if newUser: context = { "message": f"User created {newUser}" } return Response(context, status=status.HTTP_201_CREATED) return Response(reg_serial.errors, status=status.HTTP_400_BAD_REQUEST) class BlacklistTokenView(APIView): permission_classes = [AllowAny] def post(self, request): try: refresh_token = … -
Request always returns get Django
I can't post my django form. Request always returns get. Can you help me form, model, view, template aşağıda belirtiğim gibi. Post request is not detected when I fill out and submit the form. It doesn't even enter the is valid part anyway. I made the POST post and wrote the url in the action ="". I tried it as a model form. I checked the divs but no result no matter what I did view.py if request.method =="POST": print('send1') form = ContactForm(request.POST) if form.is_valid(): print('send1.1') print('send1') subject = request.POST['subject'] name = request.POST['name'] company_name = request.POST['company_name'] title = request.Post['title'] email_address = request.POST['email_address'] phone = request.POST['phone'] city_country = request.POST['city_country'] message = request.POST['message'] form.save() value = "İsim ve Soyisim : {0}\nŞirket İsmi : {1}\nÜnvanı ve Departmanı : {2}\n" \ "Mail adresi : {3}\nTelefonu : {4}\nŞehir ve Ülkesi : {5}\nMesajı : {6}\n"\ .format(name,company_name,title,email_address,phone,city_country,message) send_mail(subject, message=value, from_email="utku.mutlu@adatech.com.tr", recipient_list=['utku.mutlu@adatech.com.tr']) print('send2') print(form.data) return redirect('offer-request') else: form = ContactForm() print("send3") print(form.data) context = {'contexts':OfferRequest.objects.first(),'form':form} return render(request, "offer.html", context) template.html {% if form %} <form id="form" class="modular-form modular-form--black" method="POST" action=""> {% csrf_token %} <div class="modular-form__pages "> <div class="modular-form__page modular-form__page--active " data-page-number="1 "> <div class="modular-form__field form-text "> {{form}} </div> </div> <div class="form-footer__action "> </div> </div> </form> {% endif %} -
Render pdf locally
I don't have an access to S3 project bucket and I would like to save html file or pdf(will be better) in my local machine, instead of S3 storage. When I'm generating pdf I'm catching ValidationError I have this function for rendering pdf file, any ideas how I can edit this and save it locally? def _render_pdf(storage, context, language_code, filename, template_path): tmp_html_file = tmp_pdf_file = None try: with tempfile.NamedTemporaryFile( delete=False, suffix='.html' ) as tmp_html_file: with translation.override(language_code): tmp_html_file.write( str( render_to_string( template_path, context ) ).encode('utf-8') ) tmp_pdf_file = tempfile.NamedTemporaryFile( delete=False, suffix='.pdf' ) i = 0 while i < settings.WKHTMLTOPDF_BINARY_RETRIES and os.path.getsize(tmp_pdf_file.name) == 0: i += 1 generate_pdf_file(tmp_html_file.name, tmp_pdf_file.name) if os.path.getsize(tmp_pdf_file.name) == 0: raise ValidationError(u'Pdf file is empty: {}'.format(tmp_pdf_file), u'empty_pdf_file') storage.save(filename, tmp_pdf_file) finally: if tmp_html_file is not None: os.unlink(tmp_html_file.name) if tmp_pdf_file is not None: tmp_pdf_file.close() os.unlink(tmp_pdf_file.name) -
Page not found (404) Using the URLconf defined in shop.urls, Django tried these URL patterns, in this order:
Error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:9000/accounts/profile/ Using the URLconf defined in shop.urls, Django tried these URL patterns, in this order: admin/ products/ The current path, accounts/profile/, didn’t match any of these. shop is my project products is my app... After Login my page redirect to another location... i want another page in (products/templates/index.html) to shown after login.. how i do that products/urls.py from django.contrib.auth import views as auth_views path('login/', auth_views.LoginView.as_view(template_name='login.html'), name='login'), in views.py i have no function called login login.html <h1>login page</h1> <form class="login-form" method="POST"> {% csrf_token %} <div class="row"> <div class="col-lg-12"> <div class="form-group position-relative"> <label>Username <span class="text-danger">*</span></label> {{form.username}} </div> </div> <div class="col-lg-12"> <div class="form-group position-relative"> <label>Password <span class="text-danger">*</span></label> {{form.password}} </div> </div> <div class="col-lg-12 mb-0"> <a href="{% url 'index' %}"><button class="btn btn-primary w-100" type="submit">Login</button></a> </div> <div class="col-12 text-center"> <p class="mb-0 mt-3"><small class="text-dark mr-2">Don't have an account ?</small> <a href="{% url 'register' %}" class="text-dark font-weight-bold">Sign Up</a></p> </div> </div> </form> -
Django: how do you prefetch recursive fields?
class Item(models.Model): # ... required_items = models.ManyToManyField("self", symmetrical=False, blank=True) Since it's a M2M relation, I can't use select_related to optimise my query, so I have to use prefetch_related. But I don't undertstand why I can't chose the depth of recursion, like I would with select_related and the depth parameter. For example, to select 3 levels of recursion, I would expect some syntax like this to work (it doesn't): Item.objects.prefetch_related("required_items", depth=3). But instead, what I'm currently doing and is obviously awful is: Item.objects.prefetch_related("required_items__required_items__required_items") I think I don't get it at some point... -
Signal attached to 3rd party library model not being triggered
I've have got a usecase in which I have a model named "Content" which inherits from a 3rd party library I've installed as a pip package known as "django-mptt" as shown below. content_viewer/models.py class Content(MPTTModel): content_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) content_name = models.CharField(max_length=250) I'm also using redis cache for cacheops and I've added the configurations as follow in my settings.py. dashboard/settings.py CACHEOPS_REDIS = { "host": REDIS_HOST, "port": REDIS_PORT, "db": 1, "socket_timeout": 3, } CACHEOPS = { "content_viewer.*": {"ops": {"fetch", "get"}, "timeout": 60 * 60}, } Note:- content_viewer is the name of the app Requirement: What I want here is a post_save signal on the MPTTModel class which should invalidate/clear the redis cache for the object that has been created/saved I've created a signal in my signals.py file as below. content_viewer/signals.py @receiver(post_save, sender=Content) def clear_redis_cache_for_mptt_instance(sender, instance, **kwargs): invalidate_obj(instance) and I've imported the signals inside the apps.py file as shown below. content_viewer/apps.py class WorkspaceDisplayConfig(AppConfig): name = "content_viewer" def ready(self): import content_viewer.signals But when I run the code in debug mode the signal seems to be never fired whenever I create an instance of the Content object. can anyone tell me what could I be doing wrong here? -
Django - after saving data redirecting to same url and showing json data showing on page django
I am trying to save data but the problem is while saving data it is showing json response which I'm returning from view views.py def Vwallocator_time(request): application_date = FcApplicationParameters.objects.first().todays_date att_data = FcAgentAttendance.objects.filter(user_id__in=User.objects.filter(is_active=1), attendance_status__in=('P', 'H'), attendance_date=application_date) attendance_data = att_data.values_list('user_id', flat=True) role_data = FcUserRoleMst.objects.filter(role_id=6, user_id__in=attendance_data).values_list('user_id', flat=True) profile_data = FcUserProfile.objects.filter(user_id__in=role_data) if request.POST: hours = request.POST.get('hours', 0) user_id = request.POST.get('user_id', None) att_data = FcAgentAttendance.objects.filter(user_id=user_id, attendance_date=application_date) att_data.update(fe_shift_hrs=hours) messages.success(request, "Hours saved Successfully.") return JsonResponse({'data': 'Hours saved Successfully'}) return render(request, 'allocator_agent_time.html', {'profile_data': profile_data, 'att_data': att_data }) allocator_agent_time.html <form action="{% url 'firstcall:allocator_time' %}" method="post"> {% csrf_token %} {% for message in messages %} <span id="msg_element"> <div class="alert alert-{{ message.tags }} alert-dismissible"> {{ message }} </div></span> {% endfor %} <span class="msg"></span> {% if att_data|length == 0 %} <div class="alert alert-warning"> <center> Please fill up the today's attendance muster. </center> </div> {% endif %} <div class="row"> <div class="col-md-12 roleBoxNewD"> <div class="Country-detail detail-style marginTop20"> <div class="box-header with-border p-0 m-0 position-relative"> <div class="row m-0 p-0"> <div class="col-md-7"> <h3 class="box-title position-absolute title_area">Agent Muster FE</h3> </div> <div class="col-md-5 text-right mt-1 mb-1">&nbsp;</div> </div> </div> <div class="output-table pre-allocation-box"> <div class="col-12"> <div id="example1_wrapper" class="dataTables_wrapper dt-bootstrap4 "> <div class="row"> <div class="col-sm-12 table-responsive"> <table id="example1" class="table table-hover table_devider table-striped table-top-design border-right border-left mb-2 dataTable currency-rate-table no-footer" role="grid" aria-describedby="example1_info"> <thead> … -
How to properly unpack a nested dictionary in a django HTML template?
So I was able to figure out how to unpack a dictionary keys and values on to a HTML template, but I am a bit confused as to how to unpack if if a dictionary value is a Querylist. For example I passing in all the timeslots of the given user into the dictonary. How can I unpack the attributes of the TimeSlot Query List for each timeslot such as the start time and end time? This is my HTML Template: <table> {% for key, value in user_info.items %} {% for key2,value2 in value.items %} <tr> <td>{{key2}}</td> <td>{{value2}}<td> </tr> {% endfor %} <br> {% endfor %} </table> My function in views.py def check_food_availibility(request): food = FoodAvail.objects.all() timeslots = TimeSlot.objects.all() users_dict = {} for i in range(len(user_info)): user = { "author": None, "food_available": None, "description": None, "timeslot": None } user["author"] = user_info[i].author.username user["food_available"] = user_info[i].food_available user["description"] = user_info[i].description if TimeSlot.objects.filter(time_slot_owner=user_info[i].author): user["timeslot"] = TimeSlot.objects.filter(time_slot_owner=user_info[i].author) users_dict[user_info[i].author.username] = user return render(request, "food_avail/view_food_avail.html", {"user_info": users_dict}) This is how it shows up currently: -
ctypes.util.find_library() did not manage to locate a library called 'pango-1.0-0' UBUNTU SERVER (EC2)
I am setting up my EC2 instance on AWS with an UBUNTU 18.04 and running into the following error when trying to run this gunicorn command gunicorn --bind 0.0.0.0:8000 zipherJobCards.wsgi:application error: OSError: cannot load library 'pango-1.0-0': pango-1.0-0: cannot open shared object file: No such file or directory. Additionally, ctypes.util.find_library() did not manage to locate a library called 'pango-1.0-0' I ran into this error after installing weasyprint in both my base directory and my web apps directory. Does anyone know the cause of this and also how to fix it? -
Passing Data From View to Model Django
I'm working on how to passing data from View to Model. I want to pass request.user.id from view to model through save method and put it on created_by field. Here is my view.py codes: def dashboardCategoryCreate(request): form = CategoryForm() if request.method == 'POST': form = CategoryForm(request.POST, request.FILES) form.save(request.user.id) # I Wanto To Pass This Value return redirect('dashboard-category') context = {'form': form} return render(request, 'category/category_form.html', context) And I try to catch this data on models.py and modify field created_by with userId value def save(self, userId=None): self.created_by = userId super().save() There is no error but value is not passing. How to do that? Or maybe there is another way to do that? -
Django model order_by based on another model queryset length
I have 2 models: models.py class Post(models.Model): title = models.CharField(max_length=255) desc = models.CharField(max_length=500) content = models.TextField() uploadedBy = models.ForeignKey(User, on_delete=models.CASCADE) LIKE_CATEGORIES = ( ("LIKE", "LIKE"), ("DISLIKE", "DISLIKE") ) class PostLike(models.Model): _type = models.CharField(max_length=200, choices=LIKE_CATEGORIES, blank=True, null=True) content = models.ForeignKey( Post, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) I want to order Post based on number of likes a post has. Number of likes a post has is the count of PostLike objects having _type="LIKE",content=post_object. How can I order Post specifically based on number of likes? -
I want that my answer field must be equal to the (one)options field. i try but it didn't working?
#forms.py from django.forms import ModelForm from .models import Question class QuestionForm(ModelForm): class Meta: model = Question fields = "__all__" def clean_answer(self): answer = self.cleaned_data['answer'] option1 = self.cleaned_data['option1'] option2 = self.cleaned_data['option2'] option3 = self.cleaned_data['option3'] option4 = self.cleaned_data['option4'] # print(answer,option1,option2, option3,option4) # return answer if answer == option1 or answer == option2 or answer == option3 or answer == option4: return answer #views.py class AddQuestion(View): def post(self, request): forms = QuestionForm(request.POST) if forms.is_valid: forms.save() messages.success(request, 'Successfully Added') else: messages.error(request, 'Answer must be equal to the choices') return redirect(reverse('home')) def get(self, request): forms = QuestionForm() context = {'forms': forms} return render(request,'file/addQuestion.html',context) #AddQuestion.html {% extends 'file/base.html' %} {% block title %} AddQuestion {% endblock %} {% block body %} <div class = 'container mt-5 pt-6'> <div class = 'col-md-5 mx-auto'> <h3>Add Question: </h3> <form method="POST" action="" > {% for msg in messages %} {{ msg }} {% endfor %} {% csrf_token %} {{forms.as_p}} <input type = 'submit' value = 'Submit'> </form> </div> </div> {% endblock %} -
how can I convert the normal post method submission from an html from into an ajax call in django without losing the same logic?
How can I convert the normal post method submission from an html from into an ajax call in django without losing the same logic.My django files are given below.I don't want to lose the logic. The logic should be same. views.py @csrf_exempt @require_http_methods(['POST', 'GET']) # only get and post def crawl(request): if request.method == 'POST': url = request.POST.get("id_url",None) print(url) if not url: return JsonResponse({'error': 'Missing args'}) if not is_valid_url(url): return JsonResponse({'error': 'URL is invalid'}) domain = urlparse(url).netloc # parse the url and extract the domain unique_id = str(uuid4()) # create a unique ID. settings = { 'unique_id': unique_id, # unique ID for each record for DB 'url':url, #'USER_AGENT': 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)' } This is my index.html <form method="POST" class="post-form" id='userinfoform' action="{% url 'crawl' %}" onsubmit="return spinner();"> <div class="container " > <br> <div class="form-group"> <label class=" col-form-label"></label> <div class="col-lg"> <h3><strong>Please Fill The Details</strong></h3> </div> </div> <br> <fieldset class="w-100 border border-rounded p-4"><legend class="w-25 text-center">Domain Form</legend> <div class="form-group row"> <label class="col-sm-4 col-form-label"><strong>Enter domain name:</strong></label> <div class="col-sm-8"> <input type="text" name="id_url" id="id_url" required="" value=""> </div> </div> <br> {% if d %} <p style="color: red;">{{d}}</p> {% endif %} </fieldset> <div class="form-group row mt-3"> <label class="col-sm-4 col-form-label"></label> <div class="col-sm-8 text-right"> <button type="submit" class="btn btn-primary w-25" name='submit' … -
How i can make Analytics dhasboard with models data in django without using google Analytics
I am working on my website but I am confused does I make Analytics function with myself or do I use Google Analytics? I don't have experience in both. In the dashboard, I have to show views with graph and retention on-page and other things -
Multiple forms with one single create view in Django
I have 5 forms: MyForm, EducationForm, ExperienceForm, RecommendationForm, OtherDocumentsForm I want to disply them in one form template. I can not do it with CreateView because it only accepts one form class. How can I create single view for multiple forms? class MyForm(forms.ModelForm): class Meta: model = UserForm_uz fields = 'all' class EducationForm(forms.ModelForm): class Meta: model = Education_uz fields = 'all' class ExperienceForm(forms.ModelForm): class Meta: model = Experience_uz fields = 'all' class RecommendationForm(forms.ModelForm): class Meta: model = Recommendation_uz fields = 'all' class OtherDocumentsForm(forms.ModelForm): class Meta: model = OtherDocuments fields = 'all' -
How to connect Google big query between Django project and postgresql database?
I am new to bigquery and Django, I want to optimize the performance for analysis of past data for that I want data to come out from postgresql to bigquery for process and then I want to show it in frontend of Django project. Since analysis of past data effect the performance of transaction workloads in postgresql so bigquery is best technology for that.