Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
automatic and unwanted default behavior in checkout
hello I hope you can help me currently I still have the default behavior which is activated while I would like the visitor to choose an address or create one so I always have the first address that the customer has create and not choose as you can see the default behavior is id = 1 the problem is that in practice whatever the choice I always have id = 1 def orders(request): order=Order.objects.all try: the_id=request.session['cart_id'] cart=Cart.objects.get(id=the_id) except: the_id=None return HttpResponseRedirect(reverse("carts:cart")) try: new_order=Order.objects.get(cart=cart) except: new_order=None return HttpResponseRedirect(reverse("carts:cart")) final_amount=0 shipping_a=request.POST.get("shipping_ad", 1) building_a=request.POST.get("building_ad", 1) if new_order is not None: new_order.sub_total=cart.total try: shop=new_order.shipping_ad=UserAddress.objects.get(id=shipping_a) except: shop=new_order.shipping_ad=None try: build=new_order.building_ad=UserAddress.objects.get(id=building_a) except: build=new_order.building_ad=None new_order.address=build.address new_order.address2=build.address2 new_order.city=build.city new_order.state=build.state new_order.country=build.country new_order.zipcode=build.zipcode new_order.phone=build.phone new_order.status="Finished" new_order.save() final_amount=new_order.get_final_amount if new_order.status=="Finished": new_order.save() del request.session['cart_id'] del request.session['items_total'] context={'order':order} template="orders/user.html" return render(request,template,context) @login_required def checkout(request): try: the_id=request.session['cart_id'] cart=Cart.objects.get(id=the_id) except: the_id=None return HttpResponseRedirect(reverse("carts:cart")) try: new_order=Order.objects.get(cart=cart) except Order.DoesNotExist: new_order=Order(cart=cart) new_order.cart=cart new_order.user=request.user new_order.order_id=id_generator() new_order.save() except: new_order=None return HttpResponseRedirect(reverse("carts:cart")) final_amount=0 if new_order is not None: new_order.sub_total=cart.total new_order.save() final_amount=new_order.get_final_amount try: address_added=request.GET.get("address_added") except: address_added=None if address_added is None: address_form=UserAdressForm() else: address_form=None currents_address=UserAddress.objects.filter(user=request.user) billing_address=UserAddress.objects.get_billing_address(user=request.user) context={'order': new_order ,'address_form':address_form, 'currents_address':currents_address,'billing_address':billing_address} template="orders/checkout.html" return render(request,template,context) -
How to create single Dockerfile for multiple containers without using docker-compose.yml?
Here I have 2 cases: Case 1: I have created a Django project called Counterproj which uses a default db called Sqlite3. I have dockerized this project using Dockerfile and pushed to Azure ACI which worked well in both the cases local and cloud. Case 2: The problem starts here when I migrated from Sqlite3 to PostgreSQL I have dockerized Django project using Dockerfile and docker-compose.yml with the services web and db these are working fine in my local but when I Push to Azure ACI the containers Counterproj_web:test and postgres:test are not able to communicate with each other and the instance is being terminated. Here my query is that can we create a single Dockerfile without using any docker-compose.yml for Django project containerization using PostgreSQL as db. If we can create single dockerfile please suggest me the best way which should run both in local and in cloud. Below are my Dockerfile, docker-compose.yml and database settings for your reference. Dockerfile: #syntax=docker/dockerfile:experimental # Python Version(Base Image) FROM python:3 # Set Envirment variable ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set Working directory WORKDIR /app # Add all the things into app ADD . /app # Instruct docker to install all … -
Linkedin Oauth2 giving null values, while integrating with django
I am trying to integrate login with linkedin, But I am not able to get profile picture, email address,profile url and other important details. here is what I have done till now. SOCIAL_AUTH_LINKEDIN_OAUTH2_KEY = 'Client ID' SOCIAL_AUTH_LINKEDIN_OAUTH2_SECRET = 'Client Secret' SOCIAL_AUTH_LINKEDIN_OAUTH2_SCOPE = ['r_liteprofile', 'r_emailaddress',] # SOCIAL_AUTH_LINKEDIN_OAUTH2_FIELD_SELECTORS = ['profile_url', 'email_address', 'headline', 'industry'] SOCIAL_AUTH_LINKEDIN_OAUTH2_FIELD_SELECTORS = ['email-address', 'formatted-name', 'profile-url', 'picture-url'] SOCIAL_AUTH_LINKEDIN_OAUTH2_EXTRA_DATA = [ ('id', 'id'), ('firstName', 'first_name'), ('emailAddress', 'email_address'), ('lastName', 'last_name'), ('displayImage', 'profilePictures'), ('publicProfileUrl', 'profile_url'), ] I also trying setting up pipelines like this SOCIAL_AUTH_PIPELINE = ( 'social.pipeline.social_auth.social_details', 'social.pipeline.social_auth.social_uid', 'social.pipeline.social_auth.auth_allowed', 'social.pipeline.social_auth.social_user', 'social.pipeline.user.get_username', 'social.pipeline.user.create_user', 'social.pipeline.social_auth.associate_user', 'social.pipeline.social_auth.load_extra_data', 'social.pipeline.user.user_details' ) I tried different combinations with _,- etc but nothing works, all giving same output as { "auth_time": 1623340190, "id": "lIkisJgyIT", "expires": 5184000, "first_name": {"localized": {"en_US": "Akash"}, "preferredLocale": {"country": "US", "language": "en"}}, "last_name": {"localized": {"en_US": "Rathor"}, "preferredLocale": {"country": "US", "language": "en"}}, "email_address": null, "profilePictures": null, "profile_url": null, "access_token": "fulltokenid" token_type": null } Also there is one confusion, when I logged in with linkedin on my application and again try to login with linkedin it's seniding and obvious error that user already authenticated, I am not sure how I set up the condition , if user already authenticated then user will not be able to try login again. … -
I am using CreateView in django but getting error- The view blog.views.PostCreateView didn't return an HttpResponse object. It returned None instead
I am having a post model with a user having OneToMany Relationship with inbuilt user model for authentication my urls.py from django.contrib import admin from django.urls import path, include # from views import PostView from . import views urlpatterns = [ path('', views.PostView.as_view(), name='blogHome'), path('post/<int:pk>/', views.PostDetailView.as_view(), name='post-detail'), path('post/new/', views.PostCreateView.as_view(), name='post-create'), path('about/', views.about, name='about') ] my views.py from django.shortcuts import render from django.http import HttpResponse from .models import Post from django.views.generic import ( ListView, DetailView, CreateView ) # Create your views here. def home(request): context = { 'posts': Post.objects.all() } return render(request, 'blog/home.html', context) def about(request): return render(request, 'blog/about.html') class PostView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_published'] class PostDetailView(DetailView): model = Post class PostCreateView(CreateView): model = Post fields = ['title', 'body'] #to add author before validation def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) Post Model from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) body = models.TextField() date_published = models.DateTimeField(default=timezone.now) def __str__(self): return self.title I am using post_form.html as the template name post_form.html {% extends 'blog/layout.html' %} {% load crispy_forms_tags %} {% block body %} <div class="content-section … -
how to solve two model circular dependency in django
I have a file in django project models.py: from django.db import models class Product(models.Model): id = models.IntegerField(unique=True,primary_key=True) title = models.CharField(max_length=200) description = models.TextField(max_length= 100000) price = models.FloatField() count = models.IntegerField(default=1) file_content = models.ManyToManyField(ProductImage, related_name='file_content', blank=True, null=True) offer= models.BooleanField(default=False) def __str__(self): return self.title class ProductImage(models.Model): property_id = models.ForeignKey(Product,on_delete=models.CASCADE) image = models.FileField(upload_to='pics') def __str__(self): return '%s-image' % (self.property_id.title) It says that ProductImage is not defined, which is clear because it is defined below. If I tries to move it up above like this: class ProductImage(models.Model): property_id = models.ForeignKey(Product,on_delete=models.CASCADE) image = models.FileField(upload_to='pics') def __str__(self): return '%s-image' % (self.property_id.title) class Product(models.Model): id = models.IntegerField(unique=True,primary_key=True) title = models.CharField(max_length=200) description = models.TextField(max_length= 100000) price = models.FloatField() count = models.IntegerField(default=1) file_content = models.ManyToManyField(ProductImage, related_name='file_content', blank=True, null=True) offer= models.BooleanField(default=False) def __str__(self): return self.title Now it says Product is not defined . Can any body tell me the remedy? What I have done so far? I tried to make a separate file called img.py and class ProductImage wrote there.Then I tried to import it here. Now it says: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\hussnain\appdata\local\programs\python\python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "c:\users\hussnain\appdata\local\programs\python\python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File … -
Navbar not showing properly
The navbar is not showing properly. It's not becoming how it's shown on the bootsrap website. I have copied the following code from the Navbar section in Bootstrap <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Dropdown </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="#">Action</a></li> <li><a class="dropdown-item" href="#">Another action</a></li> <li><hr class="dropdown-divider"></li> <li><a class="dropdown-item" href="#">Something else here</a></li> </ul> </li> <li class="nav-item"> <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a> </li> </ul> <form class="d-flex"> <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success" type="submit">Search</button> </form> </div> </div> [enter image description here][1] -
Using Django and Charts.js, no data sent to template from view
I'm using charts.js with Django and I have an issue with the data I'm sending from the view to the chart in the template. Here is my code: model.py (only relevant fields): STATUS = ((0,"Tender"), (1,"Live"), (2,"Archived")) class Project(models.Model): project_number = models.CharField(max_length=5, unique=True) project_name = models.CharField(max_length=200, null=True) slug = models.SlugField(max_length=200, unique=True) project_value = models.DecimalField(max_digits=7, decimal_places=0) project_designer = models.ForeignKey(User, on_delete=models.PROTECT, default=0, related_name='project_designer') project_manager = models.ForeignKey(User, on_delete=models.PROTECT, default=0, related_name='project_manager') is_fire = models.BooleanField(default=False) project_status = models.IntegerField(choices=STATUS, default=0) #progress progress_abdrawings = models.IntegerField(default=0, validators=[MaxValueValidator(100),MinValueValidator(0)]) @property def abdrawings_remaining(self): remaining = 100 - self.progress_abdrawings return remaining class Meta: ordering = ['-project_number'] def __str__(self): return self.project_number views.py (only relevant fields): I only want to display two fields on this chart: progress_abdrawings and abdrawings_remaining def ProjectDetail(request, slug): model = Project template_name = 'detail-project.html' project = get_object_or_404(Project, slug=slug) return render(request, 'detail-project.html',{'project':project}) class ChartView(View): def get(self, request, *args, **kwargs): return render(request, 'dashboard.html') class ChartAbProgress(APIView): authentication_classes = [] permission_classes = [] model = Project def get(self, slug): self.slug = slug labels = ['COMPLETED', 'REMAINING'] chartLabel = "FAB DRAWINGS" chartdata = [] queryset = Project.objects.filter(slug=self.slug).order_by('-project_number') for project in queryset: chartdata.append(project.progress_abdrawings) chartdata.append(project.abdrawings_remaining) abProgData = { "labels":labels, "chartLabel":chartLabel, "chartdata":chartdata, } return Response(abProgData) url.py (only relevant fields): urlpatterns = [ # The home page path('', views.DashView.as_view(), … -
How can I show in cart items in my index view?
I'm working on an ecommerce app, and I have a template that displays all my products. I want to show how many of the item are in the cart. But I can't seem to figure out how to get that information from my for loop. Code: template {% for product in products %} {{product.title}} - {{product.quantity_in_cart}} {% endfor %} (As of right now, product.quantity_in_cart does nothing. I would like it to show how many of this product are in the cart) view def product_index(request): title = "My Products" products = Product.objects.all() order = get_cart(request) cart = Order.objects.get(id=order.id, complete=False) items = cart.orderitem_set.all() context = { 'title' : title, 'products' : products, 'cart' : cart, 'items': items } return render(request, "store/product_index.html", context) models class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) complete = models.BooleanField(default=False, null=True, blank=False) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) class Product(models.Model): name = models.CharField(max_length=64) slug = models.SlugField(unique=True, null=True) description = RichTextField(blank=True) price = models.DecimalField(max_digits=8, decimal_places=2) quantity = models.IntegerField() -
Django and Microsoft azure services
Is it possible to integrate Microsoft azure services like Custom vision in the Django app? I want to build a web app where users can upload images and train a model using those images. -
django form implement AJAX for show hidden fields
So I got a simple form of COUNTRY, AREA, DISTRICT, CITY. In this form there are 4 more fields: What I'm trying to do is to filter the data. So when the user select a Country, the area field(select) will show all the areas that belong to this Country. Also when the user select a area, the module field(select) will show all the districts that belong to this field. If you check the code, you will see it's kinda simple. I know how to filter the queryset but I don't know how to use AJAX to do that. Tried many tutorials but couldn't find something so I'm sorry for not posting code. If you can point me to the right tutorial, example or give me some code to start working on it... my views.py class OrderCreateView(OrderViewMixin, core.CreateView): form_class = OrderForm template_name = '.....' def form_valid(self, form): .... return super().form_valid(form) def get_ajax(request): if request.is_ajax: logs = Order.objects.filter(country_id=request.GET['country']) data = serializers.serialize("json", logs) return HttpResponse(data, content_type='application/json') urls.py path('get_ajax/',views.get_ajax,name='get_ajax'), forms.py class OrderForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(OrderForm, self).__init__(*args, **kwargs) self.fields['country'].queryset = Order.objects.all() self.fields['area'].queryset = Order.objects.none() class Meta: ..... Here I need using SELECT and option in AJAX open area if I choose country, but … -
document.querySelectorAll('*[id]') doesn't show all form fields ids in django
I am trying to connect js with django (because I am using js google maps api). In the first line of JS I have written: console.log(document.querySelectorAll('*[id]')) I obtain the following results: results I have this django's form: from django import forms class DateInput(forms.DateTimeInput): input_type='date' class userRequest(forms.Form): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) lat_Origin = forms.FloatField(widget=forms.HiddenInput(attrs={'id':'lat_Origin'}),required=False,initial=181) lon_Origin = forms.FloatField(widget=forms.HiddenInput(attrs={'id':'lon_Origin'}),required=False,initial=181) lat_Dest = forms.FloatField(widget=forms.HiddenInput(attrs={'id':'lat_Dest'}),required=False,initial=181) lon_Dest = forms.FloatField(widget=forms.HiddenInput(attrs={'id':'lon_Dest'}),required=False,initial=181) origin_address=forms.CharField(max_length=200,widget=forms.TextInput(attrs={'class':'data_aux data','id':'origin_address'})) destination_address=forms.CharField(max_length=200,widget=forms.TextInput(attrs={'class':'data_aux data','id':'destination_address'})) date=forms.DateField(widget=DateInput(attrs={'class':'data_aux data','id':'data_id'})) #date2=forms.DateField(widget=DateInput(attrs={'class':'data_aux data','id':'data_id2'})) maxPrice=forms.FloatField(label='Max price:',widget=forms.NumberInput(attrs={'class':'data_aux data order','step': '0.1'}),required=False) CHOICES_ORDERTYPE =( ('NONE', 'NONE'), ('ASC', 'ASC'), ('DESC', 'DESC'), ) OrderType = forms.ChoiceField(label='Order',choices = CHOICES_ORDERTYPE,initial='NONE',required=False,widget=forms.Select(attrs={'class':'data order'})) CHOICES_ORDERBY =( ('PRICE', 'PRICE'), ('DURATION', 'DURATION'), ) OrderBy = forms.ChoiceField(label='Order by',choices = CHOICES_ORDERBY,initial='PRICE',required=False,widget=forms.Select(attrs={'class':'data order'})) I don't know why lat_Origin, lon_Origin, lat_Dest, lon_Dest are not in document.querySelectorAll('*[id]') Do you have some idea how to fix this ? Thank you -
Download zip and save unzip
I´m working with an react native app that use a rest created in django. This app has an offline mode, for that reason I need be able to download zip files from the server to be played when offline mode will work. I've already tried using the dload library from python it works downloading and unziping the file but it download the file in the same script path (server). I need to save the zip file in the phone. Actual code looks like this... def download(request): url ="https://someirl/sco1.zip" dload.save_unzip(url, "../../") return HttpResponse( content_type="application/json") According with dload documentation second parameter in save_unzip is the folder when the zip will be downloaded and unzipped ¿How can I made to download on the phone? If you know a better way using Django or react native I would be pleasure to testing it -
django template inheritance: how to NOT display a block from parent template?
how can we hide a block in child template which is being rendered by paent template? for ex: my parent template base.html contains- <!DOCTYPE html> <html lang="en"> .... <body> {% block messages %} <div class="alert alert-{% if message.tags == 'error'%}danger{% else %}{{ message.tags }}{% endif %} alert-dismissible fade in" role="alert"> {{message}} </div> {% endblock %} ... </body> </html> and I have inherited this base.html in login.html but I do not want to use {% block messages %} in login.html, any suggestions? Thanks in advance for any solution😊. -
Django error with sites package: "The model Site is already registered in app 'sites'"
I am trying to install the sites package and upon running makemigrations am receiving the error: django.contrib.admin.sites.AlreadyRegistered: The model Site is already registered in app 'sites'. This is my admin.py: from django.contrib import admin # Register your models here. from django.apps import apps models = apps.get_models() for model in models: try: admin.site.register(model) except admin.sites.AlreadyRegistered: pass And here are my installed apps: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'webpage', 'django_user_agents', 'analytical', 'corsheaders', 'django.contrib.sites', ] Any idea what might be causing this issue? Please let me know if there is information missing. -
How to add condition to a manytomany relationship
I'm a little new to Django, so my question may be basic, but bare with me. Let's say I'm sharing my posts with some of my friends (who are manytomany relation with the post), but also giving an extra condition for whether they can comment on it, or not. This condition, together with the name of the user to be shared with are submitted through a forum. Now my problem is that I don't know how/where to save this condition. I will show you some of my code. Models.py class Task(models.Model): name = models.CharField(max_length=50) text = models.TextField() deadline = models.DateTimeField() created = models.DateField(auto_now_add=True) updated = models.DateField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='taskset') shared = models.ManyToManyField(User, blank=True, related_name = 'shared_list') def __str__(self): return f"{self.name}-{self.user.username}" class Comment(models.Model): text = models.TextField() task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name='comments') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='comments') created = models.DateField(auto_now_add=True) def __str__(self): return f"{self.user.username}-{self.task}" Share form html {% extends 'base.html'%} {% load crispy_forms_tags %} {% block content %} <h3>Enter the Username of the Friend you want to share with</h3> <form method="POST"> {% csrf_token %} {{form|crispy}} <input type="submit", value="Share"> </form> {% endblock content %} And the view processing it def share(request, id): task = Task.objects.get(id = id) if request.method == 'POST': … -
Ran 0 tests in 0.000s even when I have the file tests.py on windows 10
I have my app installed INSTALLED_APPS = [ ... "table_booker.apps.TableBookerConfig", "django_nose", ] My tests.py file I have from django.test import TestCase class AnimalTests(TestCase): def test_name(self): self.assertEqual(True, False) When I try to run my tests with python manage.py test I get Ran 0 tests in 0.000s -
How to send and receive dropdown selected option using AJAX
I have been working on a Django-based web application and I'm trying to send the selected option from a dropdown to services.py which handles models.py updating. I want the user to select one of the options in the dropdown and then send it to services.py to filter the payload coming from AWS. This is my dropdown: <div class="dropdown is-active" style="margin-bottom:10px"> <div class="select" id="dropdown-menu" role="menu"> <select class="dropdown-content" id="select"> <option class="dropdown-item" selected> AWS Accounts </option> <option value="558232680640" class="dropdown-item"> 558232680640 </option> <option value="903500686888" class="dropdown-item"> 903500686888 </option> <option value="183070076065" class="dropdown-item"> 183070076065 </option> <option value="885703380506" class="dropdown-item"> 885703380506 </option> <hr class="dropdown-divider"> <option value="*" class="dropdown-item"> All Accounts </option> </select> </div> </div> This is the javascript: $(document).ready(function() { var dropDown = $("#select"); dropDown.click(function() { $.ajax({ url: "{{ api_refresh_url }}", method: "POST", data: $("#select").val(), dataType: 'json', cache: false, }); }); }); and this is where I want to receive the data in services.py: class AWSEC2InstanceConnector: """ AWS Boto3 wrapper for connecting to the EC2 client and viewing EC2 instances """ last_update_time = datetime.min def update(self): self.last_update_time = datetime.now() instances = [] lambda_client = boto3.client('lambda') lambda_response = lambda_client.invoke(FunctionName='arn:aws:lambda:us-east-1:183070076065:function:cbi-instance-info') lambda_payload = json.loads(lambda_response['Payload'].read()) # HACK: using json.loads seems to avoid escaping the lambda response lambda_response = json.loads(lambda_payload['body']) for instance in lambda_response: instances.append(EC2Instance( … -
How to pass jquery variable into a custom django template tag?
I have a custom template tag that I got from this post. The tag is as follows: @register.filter def get_item(dictionary, key): return dictionary.get(key) In my Django template script: $(document).on('click', function() { var id = "'" + $(this).prop('id') + "'" $('img').prop('src', '{{dict|get_item:id}}'); }); Where dict is a dictionary that I pass to my Django template from my view. When I run the above code, django reads id as 'id' and not the value of the variable I set. How do I pass the jqeury variable into my custom template tag? -
Django prefetch query looping is quite slow
I have the following models. class ReportUserAnswers(models.Model): .... answers = models.ManyToManyField(ReportQuestionAnswerChoices, blank=True) ... class ReportQuestionAnswerChoices(models.Model): name = models.CharField(max_length=500) In my view i need to get all answers users have given. The choices they select are stored in 'answers' field. To get the answers i use the following query: answers = ReportUserAnswers.objects.filter( ... ).prefetch_related( "answers", ).distinct() I then need to loop over to find the answers chosen. for ans in answers: last = len(ans.answers.all()) - 1 for i, answer_given in enumerate(ans.answers.all()): answer_text += answer_given.name if not i == last: answer_text += "|" In a queryset I have 5000 answers, this loop takes around 20 seconds. Which seems very slow (crashes live server). I looked at the prefetch query directly in SQL, and that returns 2270 rows. So i guess the logic is looping 5000 times and looking in a table of 2270 for answers.all() The question is, is there a better approach or any thing i can do to cut the loop time? -
Django Follow-Unfollow System Issue
I'm developing a social media to chat with friends. And I added a follow-unfollow system in the project. However, when it try to view some profiles it gives me an error and I can't figure it. Here's the code: from django.shortcuts import render, redirect from .models import UserProfile from Posts.models import Posts from django.views import View from django.contrib.auth.mixins import UserPassesTestMixin, LoginRequiredMixin # Create your views here. class ProfileView(LoginRequiredMixin, View): def get(self, request, pk, *args, **kwargs): profile = UserProfile.objects.get(pk=pk) user = profile.user posts = Posts.objects.filter(author= user).order_by('-created_on') followers = profile.followers.all() if len(followers) == 0: is_following = False for follower in followers: if follower == request.user: is_following = True break if follower == request.user: is_following = False number_of_followers = len(followers) context= { 'user': user, 'profile': profile, 'posts':posts, 'number_of_followers': number_of_followers, 'is_following': is_following, } return render(request, 'Profiles/profile.html', context) class AddFollower(LoginRequiredMixin, View): def post(self, request, pk, *args, **kwargs): profile = UserProfile.objects.get(pk=pk) profile.followers.add(request.user) return redirect('profile', pk=profile.pk) class RemoveFollower(LoginRequiredMixin, View): def post(self, request, pk, *args, **kwargs): profile = UserProfile.objects.get(pk=pk) profile.followers.remove(request.user) return redirect('profile', pk=profile.pk) Any suggestions or help will be very helpful. If there are any other alternative to this. -
Onclick of update table button want to show form as a popup in Django
I'm trying to use modal popup as a edit form but I don't know good way. Currently my views.py is like this. #update dependency management def update_jiradata(Request,id): if Request.method == 'POST': pi = jira_Story.objects.get(pk=id) fm = jira_StoryReg(Request.POST, instance=pi) if fm.is_valid(): fm.save() fm = jira_StoryReg() return HttpResponseRedirect('/DependencyManagement') else: pi = jira_Story.objects.get(pk=id) fm = jira_StoryReg(instance=pi) jira = jira_Story.objects.all() return render(Request, 'hello/EditManagement.html', {'jiraform': fm, 'JIRA': jira}) Here's the template files for the view: {% extends 'hello/Dependency_Management.html'%} {% block editmanagement %} <style> </style> <div id="myModal1" class="modal1"> <div class="modal-content1"> <span class="close1">&times;</span> <div class="row"> <div class="col-sm-8 offset-2"> <h4 class="alert alert-info">Update JIRA Stories</h4> <form action="" method="post"> {% csrf_token %} {{jiraform.as_p}} <input type="submit" value="Update" class="btn btn-success"> <!-- <a href="{% url 'addrow' %}" class="btn btn-info">Back to Dashboard</a> --> </form> </div> </div> </div> </div> <script> // document.getElementById('parameter').style.display = 'none'; </script> {% endblock editmanagement %} I want some this like that onclick on my view button -
what is the best way to take user input in multiple step process of registration
I am developing an application using django framework- which has following. model class User: firstname = models.CharField(max_length=50,blank=True, null=True ) lastname = models.CharField(max_length=50,blank=True, null=True ) username = models.CharField(max_length=50,blank=True, null=True ) class A user = models.OneToOneField(User, on_delete=models.CASCADE) field1 = models.CharField(max_length=50,blank=True, null=True ) field2 = models.CharField(max_length=50,blank=True, null=True ) field3 = models.CharField(max_length=50,blank=True, null=True ) class B user = models.OneToOneField(User, on_delete=models.CASCADE) field4 = models.CharField(max_length=50,blank=True, null=True ) field5 = models.CharField(max_length=50,blank=True, null=True ) field6 = models.CharField(max_length=50,blank=True, null=True ) class C user = models.OneToOneField(User, on_delete=models.CASCADE) field7 = models.CharField(max_length=50,blank=True, null=True ) field8 = models.CharField(max_length=50,blank=True, null=True ) field9 = models.CharField(max_length=50,blank=True, null=True ) form class UserForm(forms.ModelForm): firstname = forms.CharField(label='', required=True) lastname = forms.CharField(label='', required=True) username = forms.CharField(label='', required=False) class Meta: fields = ("firstname", "lastname", "username", ) model = models.User class AForm(forms.ModelForm): field1 = forms.CharField(label='', required=True) field2 = forms.CharField(label='', required=True) field3 = forms.CharField(label='', required=False) class Meta: fields = ("field1", "field2", "field3", ) model = models.A class BForm(forms.ModelForm): field4 = forms.CharField(label='', required=True) field5 = forms.CharField(label='', required=True) field6 = forms.CharField(label='', required=False) class Meta: fields = ("field4", "field5", "field6", ) model = models.B class CForm(forms.ModelForm): field7 = forms.CharField(label='', required=True) field8 = forms.CharField(label='', required=True) field9 = forms.CharField(label='', required=False) class Meta: fields = ("field7", "field8", "field9", ) model = models.C views def createuser(request): if request.method == 'POST': … -
Dynamically display crypto prices from cryptocompare using django
I'm trying to make a simple webpage in django where I can display the price of some cryptocurrencies. The user stores in the database the name of the crypto and its initial price. Then I want to fill a table with the ticker and the initial price taken from the database and the current price of each crypto taken with cryptocompare. This is where the problem begin: the value of 'current price' is taken using cryptocompare, but how can I dinamycally display the value of the current price of each crypto in the table? Maybe the problem is easy to solve but I'm really new and I'm stuck, thanks in advance! This is how the index look like -> tabel in the index page models.py from django.db import models # Create your models here. class crypto(models.Model): ticker = models.CharField(max_length=200) initial_price = models.FloatField() def __str__(self): return self.ticker views.py from .models import crypto def index_view(request): chart = FuncAnimation(plt.gcf(), animate, interval=1000) ticker_list = crypto.objects.all() return render(request, 'cryptochart/index.html', {'chart': chart, 'ticker_list': ticker_list}) and last, in a file called utils.py I wrote the functions to get the price import cryptocompare #get price of cryptocurrency def get_crypto_price(cryptocurrency,currency): return cryptocompare.get_price(cryptocurrency,currency=currency)[cryptocurrency][currency] #get fullname of the cryptocurrency def get_crypto_name(cryptocurrency): … -
Admin only foreign key field with support for autcomplete search?
I'm trying to implement a simple system that can send emails directly from a model's change form, as well as have templates that I can use to fill in the subject and text fields. I currently have a foreign key to my template model which I can select from an autocomplete dropdown. Since I only need this field to fill in admin form values. How can I avoid adding the foreign key field to the MailInstance model while still keeping django's autocomplete working? models.py class MailTemplate(Model): subject = CharField(max_length = 1000) text = TextField() class MailInstance(Model): subject = CharField(max_length = 1000) text = TextField() emails = ArrayField(base_field = CharField(max_length = 300), null = True, blank = True) template = ForeignKey(MailTemplate, null = True, blank = True, on_delete = SET_NULL) admin.py class MailInstanceAdmin(admin.ModelAdmin, DynamicArrayMixin): fields = ['subject', 'text', 'template', 'emails'] autocomplete_fields = ['template'] -
I have an issue (Django)
in views.py from django.contrib.auth.decorators import login_required @login_required def index(request): user = request.user posts = Post.objects.filter(user=user) In this code I can't understand inline @login_required Why should we use the decorator And user=request.user user ?? In this project, we hadn't created models named user. Please explain to me. Thanks a lot