Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to change "Add user" in the navbar of User Add Page of Django Admin?
I'm working on Django and I want to change the "Add user" in the navbar of the User Add Page as marked in the pic with some other text. my admin.py file is this : from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import CustomUser class CustomUserAdmin(UserAdmin): list_display = ('first_name','last_name','email','is_staff', 'is_active',) list_filter = ('first_name','email', 'is_staff', 'is_active',) search_fields = ('email','first_name','last_name','a1','a2','city','state','pincode') ordering = ('first_name',) add_fieldsets = ( ('Personal Information', { # To create a section with name 'Personal Information' with mentioned fields 'description': "", 'classes': ('wide',), # To make char fields and text fields of a specific size 'fields': (('first_name','last_name'),'email','a1','a2','city','state','pincode','check', 'password1', 'password2',)} ), ('Permissions',{ 'description': "", 'classes': ('wide', 'collapse'), 'fields':( 'is_staff', 'is_active','date_joined')}), ) So it can be changed?? If yes then how?? Thanks in advance!! -
Failled to install Pillow using Pycharm
I am using Pycharm on windows 7 32bit, i am learning to make a website using django. i am trying to make imagefield, so i tried to install Pillow in the command window and it give me this error: (venv) C:\Users\مرحبا\PycharmProjects\TryDjango>py -m pip install Pillow Collecting Pillow Exception: Traceback (most recent call last): File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\pip\_internal\basecommand.py", line 228, in main status = self.run(options, args) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\pip\_internal\commands\install.py", line 291, in run resolver.resolve(requirement_set) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\pip\_internal\resolve.py", line 103, in resolve self._resolve_one(requirement_set, req) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\pip\_internal\resolve.py", line 257, in _resolve_one abstract_dist = self._get_abstract_dist_for(req_to_install) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\pip\_internal\resolve.py", line 210, in _get_abstract_dist_for self.require_hashes File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\pip\_internal\operations\prepare.py", line 245, in prepare_linked_requirement req.populate_link(finder, upgrade_allowed, require_hashes) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\pip\_internal\req\req_install.py", line 307, in populate_link self.link = finder.find_requirement(self, upgrade) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\pip\_internal\index.py", line 484, in find_requirement all_candidates = self.find_all_candidates(req.name) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\pip\_internal\index.py", line 442, in find_all_candidates for page in self._get_pages(url_locations, project_name): File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\pip\_internal\index.py", line 587, in _get_pages page = self._get_page(location) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\pip\_internal\index.py", line 705, in _get_page return HTMLPage.get_page(link, session=self.session) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\pip\_internal\index.py", line 814, in get_page "Cache-Control": "max-age=600", File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\pip\_vendor\requests\sessions.py", line 521, in get return self.request('GET', url, **kwargs) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\pip\_internal\download.py", line 397, in request return super(PipSession, self).request(method, url, *args, **kwargs) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site- packages\pip\_vendor\requests\sessions.py", line 508, … -
Django - passing variable from function into html view
Good afternoon, I have a problem and i can't figure it out how to do it. I try to display in html view weather from api but it't not working. Views.py from urllib.request import Request, urlopen from django.shortcuts import render from django.http import HttpResponse from django.views.generic import TemplateView from django.template.response import TemplateResponse # Create your views here. class DashboardView(TemplateView): template_name = "index.html" def index(request, template_name="index.html"): headers = { 'Authorization': 'my_private_api' } args={} request = Request('https://avwx.rest/api/metar/KJFK', headers=headers) response_body = urlopen(request).read() args['metar'] = response_body return TemplateResponse(request,template_name,args) index.html (template) {%block content %} <div> <h1>Metary</h1> <p> {{ metar }}</p> </div> {%endblock content%} urls.py from django.urls import path from . import views from dashboard.views import DashboardView urlpatterns = [ path('', DashboardView.as_view()), ] So what i want to do is display data from api into view using variable "metar". Thank you very much for help. -
Testing schemas in multi tenant django app
I have multi tenant Django application with a Postgres DB, that follows a shared db and isolated schema approach as detailed here: https://books.agiliq.com/projects/django-multi-tenant/en/latest/shared-database-isolated-schema.html I'm trying to create a test to see if data is properly segregated with users that have the same username but are in different schemas. For example: Schema Tenant A has user John Schema Tenant B has user John I need some guidance on how to setup a test that checks the schema and users associated with that schema. -
How to create a search box in django which can recommend similar movies the movies
This code can recommend the movies in jupyer notebook but now I get stuck while creating search box which can display movies in webpage def recommendations(title, cosine_sim=cosine_sim): # Get the index of the movie that matches the title idx = indices[title] # Get the pairwsie similarity scores of all movies with that movie sim_scores = list(enumerate(cosine_sim[idx])) # Sort the movies based on the similarity scores sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True) # Get the scores of the 10 most similar movies sim_scores = sim_scores[1:11] # Get the movie indices movie_indices = [i[0] for i in sim_scores] # Return the top 10 most similar movies return df['title'].iloc[movie_indices] Here I tried to recommend a movie but failed can anyone can help me to display in web browser by using get method in Django def recomm(request): if request.method == 'GET': query="" movie = recommendations('movie') movie = movie.recommendation(str(query)) return render(request, 'home.html', movie) else: return render(request, 'home.html') return redirect(request, 'home.html') -
Customizing email_confirmation_message.txt of allauth django project gives error what to do?
Invalid block tag on line 7: 'endblocktrans', expected 'endautoescape'. Did you forget to register or load this tag? {% load account %}{% user_display user as user_display %}{% load i18n %}\ {% autoescape off %}{% blocktrans with site_name=current_site.name site_domain=current_site.domain %}Hi from {{ site_name }}! You're receiving this e-mail because user {{ user_display }} has given yours as an e-mail address to connect their account. To confirm this is correct, go to {{ activate_url }} {% endblocktrans %}{% endautoescape %} {% blocktrans with site_name=current_site.name site_domain=current_site\ .domain %}Thank you from {{ site_name }}! {{ site_domain }}{% endblocktrans %} -
How I can use django MedalForm object and Queryset to do login authentication function
My following question is about how I can develop a function that I can compare a POST request data (MedalForm) and existing data of model in queryset. This is mi models.py: class Employee(models.Model): dni = models.CharField(max_length=9, null=False, blank=False, default="12345678R") name = models.CharField(max_length=7) surname = models.CharField(max_length=8) email = models.CharField(max_length=20) telefone_number = models.IntegerField() user_nick = models.CharField(max_length=10, null=False, blank=False, default="user") password = models.CharField(max_length=20, null=False, blank=False, default="password") ticket = models.ManyToManyField(Ticket) forms.py (EmployerLoginForm only to user_nick and password): class EmployerForm(forms.ModelForm): class Meta: model = Employee fields = "__all__" class EmployerLoginForm(forms.ModelForm): class Meta: model = Employee exclude = ['dni', 'name', 'surname', 'email', 'telefone_number', 'ticket'] In this case, to develop login function I am using the EmployerLoginForm in views.py: _logger = nexus_services_logs.Logging(statics.NEXUS_VIEWS_LOGGING_NAME) _views_manager_service = nexus_services_views_manager.ViewsManagerService() _auth = nexus_services_auth.Authentication() class IndexView(View): def post(self, request, *args, **kwargs): form = EmployerLoginForm(request.POST) if(_auth.check_model_employer_authentication(form, _logger, _views_manager_service)): if(_views_manager_service.validate_form(form, _logger)): _views_manager_service.save_form(form, _logger) return redirect('employerPortal') else: return redirect('index') check_model_employer_authentication(form, _logger, _views_manager_service) is the function where I want compare form data and queryset. I find the problem when I cannot compare the objects using for loop (in auth.py): class Authentication(): def __init__(self): self.employer_exist = False def check_model_employer_authentication(self, model, logger, views_manager_service): queryset_all_employers = Employee.objects.order_by("id") context_exployers = views_manager_service.build_context_queryset_employers(queryset_all_employers) for employer in context_exployers["employers"]: if(employer.user_nick == model.user_nick and employer.password == … -
how to check wheater user is logged in or not
I am working on invoice management system in which user can add invoice data and it will save in database and whenever user logged in the data will appear on home page but whenever user logout and try to access home page but it is giving following error. TypeError at / 'AnonymousUser' object is not iterable i tried AnonymousUser.is_authenticated method but still not working. i want if user is logged in then home.html should open otherwise intro.html here is my code views.py from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView ) from .models import Invoicelist def home(request): if request.user.is_authenticated(): context = { 'invoices': Invoicelist.objects.all() } return render(request, 'invoicedata/home.html', context) else: return render(request, 'invoicedata/intro.html', context) home.html {% extends "invoicedata/base.html" %} {% block content %} {% for invoice in invoices %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <small class="text-muted">{{ invoice.date_posted|date:"F d, Y" }}</small> <h2><a class="article-title" href="{% url 'invoice-detail' invoice.id %}">{{ invoice.issuer }}</a></h2> </div> <p class="article-content">{{ invoice.invoice_number }}</p> <p class="article-content">{{ invoice.date }}</p> <p class="article-content">{{ invoice.amount }}</p> <p class="article-content">{{ invoice.currency }}</p> <p class="article-content">{{ invoice.other }}</p> <div class="article-metadata"> <small class="text-muted">{{ invoice.author }}</small> </div> </div> </article> {% endfor %} {% endblock content %} intro.html {% … -
Django pre_save or post_svae is not triggered on through model but post_delete is
So I am working on a google calendar integration. I have users and shifts and in the through model I want to add a google_calendar_id. So right now I have a through model class ShiftUser(models.Model): shift = models.ForeignKey("shift.Shift", models.DO_NOTHING, related_name="shift_users") user = models.ForeignKey(User, models.DO_NOTHING, related_name="user_shifts") google_calendar_id = models.CharField(max_length=1024, null=True) class Meta: unique_together = (("shift", "user"),) But the save method does not work on through model so I added a pre_save on the model: @receiver(pre_save, sender=ShiftUser) def shift_user_change(instance, **kwargs): GoogleIntegration.create_event(instance) I tried this approach with pre_save and post_save but both are not triggered. But when I use post_delete it does work. Does anybody know why this is? For the record. I tried m2m_changed but I need to know which users changed and from what I gathered I can't do that without doing two queries per change in the relationship. This is of course not the worst but I think the pre_save is a cleaner solution. -
Django functional Based view to FormView
I have my code written in functional-based views and I came to know about the generic views which are built into Django. I have made changes using Views, TemplateViews but I got stuck at FormView. Functional Based View: def NewTeam(request): form = NewTeamForm() if request.method == 'POST': form= NewTeamForm(request.POST, request.FILES) if form.is_valid(): form.save(commit = True) return teams(request) else: print("Invalid Form") return render(request,'teamform.html', {'form':form}) FormView I tried class NewTeam(FormView): template_name = 'teamform.html' form_class = NewTeamForm success_url = '.' def get_context_data(self,**kwargs): context = super(NewTeam, self).get_context_data(**kwargs) form = NewTeamForm() if request.method == 'POST': form= NewTeamForm(request.POST, request.FILES) if form.is_valid(): form.save(commit = True) return teams(request) else: print("Invalid Form") context['form'] =form return context I can understand that I need to get the context in the first function and create a new function form_valid. I have seen the documentation and other stack answers but I couldn't get it like how to validate the form with in it. Thanks in Advance. -
Instance of 'ForeignKey' has no 'price' member
I get an error when i try to use the price and discount_price objects from the Equipment class in the EquipmentOrderItem class here is the class in my models.py file class EquipmentOrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) equipment = models.ForeignKey(Equipment, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) objects = models.Manager() def __str__(self): return f"{self.quantity} of {self.equipment.name}" def get_total_equipment_price(self): return self.quantity * self.equipment.price def get_total_discount_equipment_price(self): return self.quantity * self.equipment.discount_price here is the class i want to get the object from class Equipment(models.Model): name = models.CharField(max_length=200) pic = models.ImageField(upload_to='gallery') description = models.TextField(default='about item') price = models.FloatField(default=0) discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=3, default='VID') label = models.CharField(choices=LABEL_CHOICES, max_length=1, default='P') slug = models.SlugField() objects = models.Manager() def __str__(self): return self.name def get_absolute_url(self): return reverse('create:equipment_detail', kwargs={ 'slug': self.slug }) def get_add_to_cart_url(self): return reverse("create:add_to_cart", kwargs={ 'slug': self.slug }) def get_remove_from_cart_url(self): return reverse("create:remove_from_cart", kwargs={ 'slug': self.slug }) -
Override generics.RetrieveAPIView called with slug field
I'm using generics.RetrieveAPIView in DRF to return details using a slug lookup field. I get the slug from the url www.../slug, and then fetch the required data from the API: http://...api/slug/. It works fine when the user enters the 'slug' in the url however when they login, they don't enter the slug so I set it with code. In my code, I set the slug to anonymous. At this points, I use the User in request to fetch the details but it's not working. Please help. Here's my generics view: class StoreDetail(generics.RetrieveAPIView): lookup_field = 'slug' serializer_class = StoreSerializer def get_queryset(self): if self.kwargs: slug = self.kwargs['slug'] if slug != 'anonymous': # means slug is in URL return Store.objects.filter(slug=slug) else: # manually get slug from db id = self.request.user.id store = Store.objects.get(account=id) slug = store.slug # Everything up to here works however it returns 404(Not found) return Store.objects.filter(slug=slug) -
Updating User and extended User Profile in one API Call in Django Rest Framework
I have a form on my frontend where the user can update some info - part of the fields are supposed to update the default Django User Model, while others should update the User Profile model, which has a One-To-One Relationship to the User. I am running the code below but get the following error: AttributeError: 'str' object has no attribute '_meta' api.py # Get and Update User API class UserAPI(generics.RetrieveUpdateAPIView): permission_classes = (permissions.IsAuthenticated,) serializer_class = UserSerializer def retrieve(self, request, *args, **kwargs): serializer = self.serializer_class(request.user) return Response(serializer.data) def update(self, request, *args, **kwargs): user_data = request.data['user'] profile_data = request.data['profile'] user_serializer = self.serializer_class(request.user, data=user_data, partial=True) user_serializer.is_valid(raise_exception=True) user_serializer.save() if profile_data: profile_serializer_class = ProfileSerializer profile_serializer = ProfileSerializer(request.user.username, data=profile_data, partial=True) print(profile_serializer) profile_serializer.is_valid(raise_exception=True) profile_serializer.save() response = {'user': user_serializer.data, 'profile': profile_serializer.data} return Response(response) # UserProfile API class ProfileAPI(generics.RetrieveAPIView): lookup_field = 'user' serializer_class = ProfileSerializer queryset = Profile.objects.all() serializers.py # User Serializer class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'first_name', 'last_name') # Profile Serializer class ProfileSerializer(serializers.ModelSerializer): user = serializers.SlugRelatedField(read_only=True, slug_field="username") class Meta: model = Profile fields = '__all__' I am making a patch request in the following format: { "user": { "username": "testuser" }, "profile": { "bio": "hello this is my bio" } … -
Form attributes not displaying on webpage
I am trying to add classes to my forms but the classes are not being applied. I cannot find what I'm doing wrong. Any help would be greatly appreciated. I'm hoping to set bootstrap classes, so I'd like , if possible. class PersonalInformation(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=200, default='') surname = models.CharField(max_length=200, default='') dob = models.DateTimeField('Date of birth (mm/dd/yyyy)', null=True, default=now) preferred_subjects = models.CharField('Are there subjects you would prefer doing?', max_length=200, default='') class PersonalInformationForm(forms.ModelForm): OPTIONS = ( ("ANI", "Animals"), ("ART", "Art"), ("COM", "Communication"), ) preferred_subjects = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple( attrs={ 'class' : 'not working', 'id' : 'not working' } ), choices=OPTIONS) class Meta: model = PersonalInformation fields = ['first_name', 'surname', 'dob', 'preferred_subjects'] widgets = { 'dob': DatePickerInput( options={ "format": "MM/DD/YYYY", "showClose": False, "showClear": False, "showTodayButton": False, } ), } Thank you. -
Django MYSQL Application Deployment in AWS EB
could someone guide me how I can upload my Django application with mysql connectivity on AWS. I have checked many videos and forums but i am still not getting the solution to it. App Tree: . │ .gitignore │ db.sqlite3 │ manage.py │ requirements.txt │ ├───.ebextensions │ django.config │ ├───.elasticbeanstalk │ config.yml │ └───aquaponics │ settings.py │ urls.py │ wsgi.py │ __init__.py │ └───__pycache__ settings.cpython-36.pyc urls.cpython-36.pyc wsgi.cpython-36.pyc __init__.cpython-36.pyc Here is my .ebextensions\django.config: option_settings: aws:elasticbeanstalk:container:python: WSGIPath: aquaponics/wsgi.py Requirements.txt: awsebcli==3.18.0 botocore==1.15.46 cement==2.8.2 certifi==2020.4.5.1 chardet==3.0.4 colorama==0.4.3 Django==2.1.5 docutils==0.15.2 future==0.16.0 idna==2.7 jmespath==0.9.5 mysqlclient==1.4.6 numpy==1.18.3 opencv-python==4.2.0.34 pathspec==0.5.9 pypiwin32==223 python-dateutil==2.8.0 pytz==2019.3 pywin32==227 PyYAML==5.3.1 requests==2.20.1 semantic-version==2.5.0 six==1.11.0 termcolor==1.1.0 urllib3==1.24.3 wcwidth==0.1.9 Error: 2020-04-26 10:57:12 INFO Environment update is starting. 2020-04-26 10:57:15 INFO Deploying new version to instance(s). 2020-04-26 10:57:29 ERROR Your requirements.txt is invalid. Snapshot your logs for details. 2020-04-26 10:57:30 ERROR [Instance: i-055a8412cc9b0dd5e] Command failed on instance. Return code: 1 Output: (TRUNCATED)...) File "/usr/lib64/python2.7/subprocess.py", line 190, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1. Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. 2020-04-26 10:57:30 INFO Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. 2020-04-26 10:57:30 ERROR Unsuccessful command execution on instance … -
How to create editable custom field in Django admin interfce
I have a property inside a model and I want to make the admin interface to relate to that property. I don't find any easy way to do that. The model property: @property def weight(self): weight_unit = self.restaurant.weight_unit if weight_unit is WeightUnits.KG: return self.weight_kg if weight_unit is WeightUnits.OZ: return Weight(kg=self.weight_kg).oz @weight.setter def weight(self, value): weight_unit = self.restaurant.weight_unit if weight_unit is WeightUnits.KG: self.weight_kg = value if weight_unit is WeightUnits.OZ: self.weight_kg = Weight(oz=self.weight_kg).kg Any ideas? -
Django, combine two querysets and sort them by a common m2m field
I have two models: class Course(models.Model): course_type = models.ForeignKey(CourseType, related_name='course_type_courses', on_delete=models.PROTECT) name = models.CharField(max_length=255) course_category = models.ForeignKey(CourseCategory, related_name='category_courses', on_delete=models.PROTECT) course_format = models.ForeignKey(CourseFormat, related_name='format_courses', on_delete=models.PROTECT) school = models.ForeignKey(School, related_name='school_courses', blank=True, null=True, on_delete=models.PROTECT) room = models.IntegerField(blank=True, null=True) active_status = models.IntegerField(default=1, blank=True, null=True) description = models.CharField(max_length=255, blank=True, null=True) schedule = models.ManyToManyField(Schedule) sessions = models.IntegerField(default=0) progress = models.CharField(max_length=100, default="P1W1") start_date = models.DateField(blank=True, null=True) class Demo(models.Model): course_category = models.ForeignKey(CourseCategory, related_name='category_demos', on_delete=models.PROTECT) date = models.DateField(blank=True, null=True) schedule = models.ManyToManyField(Schedule) weekly = models.BooleanField(default=False) pm = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='pm_demos', on_delete=models.PROTECT) cf = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='cf_demos', on_delete=models.PROTECT) active_status = models.BooleanField(default=1) demo = models.BooleanField(default=1) Both share a common m2m relationship to a 'Schedule' model: class Schedule(models.Model): day = models.ForeignKey(Weekdays, on_delete=models.PROTECT) start_time = models.TimeField() end_time = models.TimeField() I have one more table linking users to courses class UserCourse(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='user_courses', on_delete=models.PROTECT) course = models.ForeignKey(Course, related_name='course_user_courses', on_delete=models.PROTECT) I want to retrieve all the courses associated with one user: def courses(self): from holos_apps.holos.models import Course all_user_courses = self.user_courses.all().values_list('course', flat=True) return Course.objects.filter(id__in=all_user_courses).distinct().order_by('schedule__day', 'schedule__start_time') def active_courses(self): return self.courses().exclude(active_status=0) and all the demos associated with one user def demos(self): if self.user_type.name == 'PM': return self.pm_demos.all().distinct().order_by('schedule__day', 'schedule__start_time') return self.cf_demos.all().distinct().order_by('schedule__day', 'schedule__start_time') and I want to combine them but keep them ordered by that schedule day and schedule start … -
Django:How to load new recent comments in Django template without refreshing a page?
Actually, i am working with the comments section in Django. comments model in models.py from django.db import models from django.contrib.auth.models import User class comment(models.Model): message=models.CharField(max_length=300) time=models.DateTimeField(auto_now_add=True) user=models.ForeignKey(User,related_name="my_comment",on_delete=models.CASCADE) post=models.ForeignKey(posti,on_delete=models.CASCADE,related_name="post_comment") #posti is a post model class Meta: ordering=['time'] def __str__(self): return self.message simple view in views.py to create a new comment. @csrf_exempt def add_comment(request,pk): if request.method == "POST": obj=posti.objects.get(pk=pk) value=request.POST.get("message") new=comment(message=value,user=request.user,post=obj) new.save() return HttpResponse(new) HTML file to load posts as well as comments. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> </head> <body> <div> <p>{{post_data}}</p> </div> <br> <div id="add"> {% for i in comments%} <div><p>{{i.message}}</p><br><span>{{i.time}}{{i.user}}</span></div> {% endfor %} </div> <div> <form id="my_form" action="{% url 'a' pk=id %}" method="POST"> {% csrf_token %} <input name="message" type="text"><br> <button id="click" type="submit">Comment</button> </form> </div> <h1></h1> <script> $(document).ready(function(){ $("#my_form").submit(function(){ $.ajax({ url:$(this).attr("action"), type:$(this).attr("method"), data:$(this).serialize(), success:function(data){ //$("h1").text(data['time']); console.log(data); } }); return false; }); }); </script> </body> </html> Here I'm using ajax so that users can post new comments on a post without refreshing a page. New comments in the database are storing without refreshing a page but how I can load new comments in this HTML file without a refreshing page. If you have any idea please tell me. -
Type error when trying to (apply py -m pip install Pillow?)
I am using Pycharm on windows 7 32bit, i am learning to make a website using django. i am trying to make imagefield, so i tried to install Pillow in the command window and it give me this error: (venv) C:\Users\مرحبا\PycharmProjects\TryDjango>py -m pip install Pillow Collecting Pillow Exception: Traceback (most recent call last): File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_internal\basecommand.py", line 228, in main status = self.run(options, args) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_internal\commands\install.py", line 291, in run resolver.resolve(requirement_set) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_internal\resolve.py", line 103, in resolve self._resolve_one(requirement_set, req) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_internal\resolve.py", line 257, in _resolve_one abstract_dist = self._get_abstract_dist_for(req_to_install) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_internal\resolve.py", line 210, in _get_abstract_dist_for self.require_hashes File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_internal\operations\prepare.py", line 245, in prepare_linked_requirement req.populate_link(finder, upgrade_allowed, require_hashes) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_internal\req\req_install.py", line 307, in populate_link self.link = finder.find_requirement(self, upgrade) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_internal\index.py", line 484, in find_requirement all_candidates = self.find_all_candidates(req.name) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_internal\index.py", line 442, in find_all_candidates for page in self._get_pages(url_locations, project_name): File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_internal\index.py", line 587, in _get_pages page = self._get_page(location) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_internal\index.py", line 705, in _get_page return HTMLPage.get_page(link, session=self.session) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_internal\index.py", line 814, in get_page "Cache-Control": "max-age=600", File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_vendor\requests\sessions.py", line 521, in get return self.request('GET', url, **kwargs) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_internal\download.py", line 397, in request return super(PipSession, self).request(method, url, *args, **kwargs) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_vendor\requests\sessions.py", line 508, in request resp = self.send(prep, **send_kwargs) File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_vendor\requests\sessions.py", line 658, in send r.content File "C:\Users\مرحبا\AppData\Local\Programs\lib\site-packages\pip_vendor\requests\models.py", … -
How does a document/file storage website 'full stack' work?
Hi there Stackoverflow, I have dabbled with coding in the past and built very simple apps with python and java. During the lockdown my mind has become more inquisitive and i'm peeling the onion of how websites, back and front end work. I have sporadically been learning about html, java(script), node.js, nginx, apache, mongoDB, amazon aws, then django, ruby on rails etc etc. However, one thing i haven't been able to find in any one location is the component layers of a website that would hosts files that users might interact with, what the best infrastructure of Full Stack for such a website might be and how the role of each of the languages/interfaces works. I would be very grateful if someone could shed some light on the subject, or direct me to the best place to learn about this. Specifically to my case I would like to know how a file hosting website might work, an example being a legal datasite that can grant users different permissions, or DocuSign contract lifecycle management. Many Thanks. -
Sending image from Android Retrofit to Django server
The problem is that I’m probably sitting already a day and racking my brains. It is required to send a regular multipart / form-data request with an image and several lines. Here is the Retrofit interface code: @Multipart @POST("edit/profile/image") Call<ImageAddResponse> change_avatar(@Part MultipartBody.Part image, @PartMap Map<String, RequestBody> requestBodyMap); There is also a backend to Django. Testing everything locally, everything works perfectly, but when I put django on a real server, I get this error when requesting above: Traceback (most recent call last): File "/usr/local/lib/python3.7/dist-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.7/dist-packages/django/core/handlers/base.py", line 115, in _get_responseHow to send an object with data and an image in retrofit to Django server response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.7/dist-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.7/dist-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/ioienv/ioi/api/views.py", line 349, in edit_user_image userid = request.POST.get('userid' , 1) File "/usr/local/lib/python3.7/dist-packages/django/core/handlers/wsgi.py", line 102, in _get_post self._load_post_and_files() File "/usr/local/lib/python3.7/dist-packages/django/http/request.py", line 326, in _load_post_and_files self._post, self._files = self.parse_file_upload(self.META, data) File "/usr/local/lib/python3.7/dist-packages/django/http/request.py", line 286, in parse_file_upload return parser.parse() File "/usr/local/lib/python3.7/dist-packages/django/http/multipartparser.py", line 154, in parse for item_type, meta_data, field_stream in Parser(stream, self._boundary): File "/usr/local/lib/python3.7/dist-packages/django/http/multipartparser.py", line 640, in __iter__ for sub_stream in boundarystream: File "/usr/local/lib/python3.7/dist-packages/django/http/multipartparser.py", line 464, in __next__ … -
Modifying app_index (AdminSite)
So I'm in the middle of modifying my Django sites admin pages. I'm currently trying to move all apps/models over to a sidebar that will exist on every admin page. This is going pretty well as you can see here my issue now is that the sidebar changes depending on where you are in the admin panel, and I've come to assume that this is due to the app_label here def app_index(self, request, app_label, extra_context=None): app_dict = self._build_app_dict(request, app_label) if not app_dict: raise Http404("The requested admin page does not exist.") # Sort the models alphabetically within each app. app_dict["models"].sort(key=lambda x: x["name"]) app_name = apps.get_app_config(app_label).verbose_name context = { **self.each_context(request), "title": _("%(app)s administration") % {"app": app_name}, "app_list": [app_dict], "app_label": app_label, **(extra_context or {}), } request.current_app = self.name return TemplateResponse(request, self.app_index_template or [ "admin/%s/app_index.html" % app_label, "admin/app_index.html" ], context) as this is the docstring for _build_app_dict Build the app dictionary. The optional label parameter filters models of a specific app. So I followed the docs on customizing the adminsite-class in hopes of being able to overwrite this one function and solve my issues, but sadly when I enable this overwrite no apps at all show up in the sidebar. As seen here: Here … -
Requesting django UpdateView via post method and passing argument
I want to open an UpdateView in Django via post method and I want to pass custom parameter via html input hidden. However, Django tells me that request (from request.POST['parameter']) is not defined. How could I access the post data? I have read a lot how the CBV manages all methods and processes them in some way before it gets translated for the callable the URL conf needs, but I do not understand everything of that. -
Unable to pass the values to django through ajax
I have a html file with many select tag coming from the view.py , I want to calculate the score each time the user click on the drop-down, for that i need to pass the value of the drop-down to view.py through ajax. Below are my html & ajax code html <form method="post" id="test"> {% csrf_token %} {% for x in data %} <select class="form-control" id="{{ x }}" name="{{ x }}" required> <option>Yes</option> <option>No</option> </select> {% endfor %} </form> ajax $(document).ready(function(){ $("#test select").change(function(){ $.ajax({ url: "/quality/auto_audit_score_calculation", type: "GET", dataType: "json", data:{ $("#text select").each(function(e){ var result =$(this).val() var parameter = $(this).attr("id") parameter : result, }); } success: function(data) { $("#score_output").text("Success"); } }); }); }); I am unable to pass the value there. request someone to help me out of this problem. -
Django : adaptive form
I want to create an adaptive form with the following models : class MetaInstance(models.Model): name = models.CharField() options = models.ChoiceField(choices = mychoices) class Instance1(models.Model): param1 = models.IntegerField() param2 = models.IntegerField() class Instance2(models.Model): param4 = models.IntegerField() param5 = models.IntegerField() In the view : if the user chooses the option 1 of the MetaInstance then he will create the model Instance1 if he chooses the option 2, then he will create the Instance2 How can I do it in Django 3 ?