Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Modal population from values in current html environment
I have a DetailView that utilises a FormMixin that is used to render a template. From this template I have two buttons that are used to call some pop up modals. In these modals I am trying to run a query that extracts data from the model linked to the FormMixin to see what previous users have entered as notes and also all other accounts that are linked to this account via a customer number. Models.py class user_stats(models.Model): User = models.ForeignKey(User, on_delete=models.PROTECT) Action = models.CharField(max_length=100, choices=Action_Choices) Outcome = models.CharField(max_length=100, choices=Outcome_Choices) Notes = models.TextField() Account_Number = models.DecimalField(max_digits=18, decimal_places=0, null=True) action_time = models.DateTimeField(default=timezone.now) def __str__(self): return self.User class Accountinforamtion(models.Model): run_date = models.DateField(db_column='Run_Date', blank=True, null=True) # Field name made lowercase. acct_num = models.DecimalField(db_column='ACCT_NUM', max_digits=18, decimal_places=0, blank=True, primary_key=True) # Field name made lowercase. cust_num = models.DecimalField(db_column='CUST_NUM', max_digits=9, decimal_places=0, blank=True, null=True) # Field name made lowercase. Views.py class AccountDetailView(FormMixin, DetailView): model = Accountinforamtion context_object_name = 'profile' form_class = UserInputForm template_name = 'Home/detail.html' def get_success_url(self): return reverse('home') def get_object(self): try: my_object = Accountinforamtion.objects.get(acct_num=self.kwargs.get('pk')) return my_object except self.model.DoesNotExist: raise Http404("No MyModel matches give the query") def get_context_data(self, *args, **kwargs): context = super(AccountDetailView, self).get_context_data(*args, **kwargs) profile = self.get_object() #form context['form'] = self.get_form() context['profile'] = profile return context def … -
My form data is not being displayed on html template
i made a form and now i am trying to to view the data from the form on the html template but its not working, any help would be helpful i just want the the data entered through the the form to be displayed on the html page. Here is the code views.py from django.shortcuts import render from .models import Post from.forms import TaskForm def add_task(request): form = TaskForm() if request.method == 'POST': print(request.POST) form = TaskForm(request.POST) if form.is_valid(): form.save() context = {'form': form} return render(request, 'List/add_task.html', context) def home(request): return render(request, 'List/home.html') def task_list(request): context = { 'posts': Post.objects.all(), } return render(request, 'List/task.html', context) models.py from django.db import models class Post(models.Model): Task = models.CharField(max_length=50, default='pythons') Detail = models.TextField(max_length=100, default='python') date = models.DateTimeField(auto_now_add=True) forms.py from django.forms import ModelForm from .views import Post class TaskForm(ModelForm): class Meta: model = Post fields = '__all__' task.html {% extends "List/Home.html" %} {% block content %} {% for post in posts %} <h3>{{ post.title }}</h3> <h3>{{ post.detail }}</h3> {% endfor %} {% endblock content %} -
Django Rest API updating-instance problem
I'm new on working with Django Rest API, so I have problem with updating. When I save the instance , I just call save method of serializer instance. But when I update the serializer instance by its id, I must give instance to update method. Right now I have another question. Due to djnago rest API docs class UpdateModelMixin: """ Update a model instance. """ def update(self, request, *args, **kwargs): partial = kwargs.pop('partial', False) instance = self.get_object() serializer = self.get_serializer(instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) self.perform_update(serializer) if getattr(instance, '_prefetched_objects_cache', None): # If 'prefetch_related' has been applied to a queryset, we need to # forcibly invalidate the prefetch cache on the instance. instance._prefetched_objects_cache = {} return Response(serializer.data) def perform_update(self, serializer): serializer.save() def partial_update(self, request, *args, **kwargs): kwargs['partial'] = True return self.update(request, *args, **kwargs) Does it always get instance from db (like this query SELECT *FROM Table1 WHERE id=1) when it updates instance. And it copies all fields one by one due to that docs If it works so, does it execute two query when instance is been updated? And another problem is that if models have nested fields. Please, give me advise there another option to solve this problem -
A problem in serving my Django app with Uwsgi and Nginx
I have built an application with the Django framework and now I am preparing it for productions. I am using Uwsgi server to serve my app but I try to run the below command sudo uwsgi --module=probog.wsgi:application --env DJANGO_SETTINGS_MODULE=probog.settings.pro --master --pidfile=/tmp/project-master.pid --http=127.0.0.1:8000 --socket=127.0.0.1:49152 It throws an error saying uwsgi: unrecognized option '--module=probog.wsgi:application' getopt_long() error And when I remove the sudo the server does get initialize but says that site can't be reached. Can someone tell me where I am going wrong here? -
How to restrict varchar in postgres to allow only specific characters in DB?
I have a case where I need to allow only specific characters in a varchar column in Postgres DB using django. It should restrict the user from entering other characters even if he directly edit using raw SQL queries. Are there any validators that I can use with both Django and Postgres. I found this helpful for using in Django - How can I make a Django form field contain only alphanumeric characters But what if the user modifies the data using raw SQL queries? -
I'm using url embedded with username password in iframe in Django
I'm using url embedded with username password in iframe in Django. error I'm getting in google chrome's console: subresource requests whose URLs contain embedded credentials (e.g. https://user:pass@host/) are blocked. Please help regarding this issue. -
How to fix pyodbc dependency errors when upgrade Django from 2.1 to 2.2.13?
Since version 2.1 has been marked as insecure I need to upgrade at least to >=2.2. Github security suggests installing 2.2.13. I also need to install other packages that only work with Django >=2.2. The Django upgrade is successful but when pipenv tries to lock the dependencies I get this error: Warning: Your dependencies could not be resolved. You likely have a mismatch in your sub-dependencies. I googled this and the only way I stop getting this error is by placing these two dependencies under [dev-packages]: django-pyodbc-azure = "<2.1" django-pyodbc = "<2.1" But when I try to run the server I get this: ImproperlyConfigured("Django %d.%d.%d is not supported." % VERSION[:3]) django.core.exceptions.ImproperlyConfigured: Django 2.2.13 is not supported. I also googled this and the solution that shows up is to manually change the conditions for raising this error. I do that and then I get this other error: django.core.exceptions.ImproperlyConfigured: 'sql_server.pyodbc' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' I googled this too but the solutions that worked for other people didn't work for me. I've been stuck at this point for days. Please send help! Other info: I am using these two params: … -
Paginator not working properly while filtering the querysets?
Here filtering working fine and also paginator works fine on the first page. The issue is while going on the next page if it has any.It shows the remaining data on the next page but if I go on the next page then It displays 0 data. Paginator doesnot working in the filter view only. So I think the issue is in this view only since I have the same template for search and list queryset view and in there the pagination works fine. views def get(self, request): results = MyModel.objects.none() parameter = request.GET.get('param', '') today = datetime.datetime.today() current_month = today.month past_7_days = today - datetime.timedelta(days=7) if parameter == '0': return redirect('show_all_querysets') elif parameter == '1': results = MyModel.objects.filter(datetime__date=today.date()).order_by('-datetime') elif parameter == '2': results = MyModel.objects.filter(datetime__range=[past_7_days, today]).order_by('-datetime') elif parameter == '3': results = MyModel.objects.filter(datetime__month=current_month).order_by('-datetime') querysets = Paginator(results, 10).get_page(request.GET.get('page')) return render(request, 'show_all_querysets.html', {'querysets': querysets}) -
Insert instance data when saving an inline User model in the Django admin
The goal is to add the creation code for the default value for "chat_user_sid" for the teacher (extends User model), which is saved in Django Admin, with an inline form. I'm just going in circles trying to figure out where this code is supposed to go. User models.py class UserProfile(PermissionsMixin, AbstractBaseUser): email = models.EmailField( _('Email Address'), unique=True) password = models.CharField(_('Password'), max_length=255) ... Teacher models.py class TeacherProfile(models.Model): teacher = models.OneToOneField( UserProfile, related_name='teacher', primary_key=True, parent_link=True, on_delete=models.CASCADE) chat_user_sid = models.CharField(max_length=40, default='') ... Teacher forms.py class TeacherProfileForm(forms.ModelForm): portrait = forms.ImageField(required=False) about_me = forms.CharField(max_length=2048, widget=forms.Textarea) chat_user_sid = forms.CharField(max_length=40) ... User admin.py class TeacherProfileInline(admin.TabularInline): add_form = TeacherProfileForm model = TeacherProfile class UserAdmin(BaseUserAdmin): # The forms to add and change user instances form = UserProfileChangeForm add_form = UserProfileForm ... inlines = [ TeacherProfileInline,] code to be executed when the Teacher-User is saved in Admin # create Twilio Chat User Resource account_sid = settings.TWILIO_ACCOUNT_SID auth_token = settings.TWILIO_AUTH_TOKEN client = Client(account_sid, auth_token) teacher_sid = client.chat.services(settings.TWILIO_CHAT_SERVICE_SID) \ .users \ .create(identity=identity, friendly_name=friendlyName) ... store the SID in the DB instance field "chat_user_sid" for the Teacher. I'm guessing there is a form_valid I have to override somewhere. I could be wrong. -
Linking pdf file from directory in html
I am having trouble creating a link to a pdf document in my directory using python/django. The link in the html page looks like this: <a href="pilots/12-and-Holding.pdf" target="_blank" Read Me</a It's a pdf I want to open up on another page and be available for download. The fold it sets in is pilots/12-and-Holding.pdf. Where am I going wrong? The error I'm getting is: Using the URLconf defined in scripts.urls, Django tried these URL patterns, in this order: The current path, pilots/12-and-Holding.pdf, didn't match any of these. Does this require a url path? Thanks, Tony -
Adding comment feature in Django DetailView?
What the simplest logic i can add in class HotelDetailView(DetailView) so users can comment on a particular hotel detail page. And it capture user too. models.py class Hotel(models.Model): name = models.CharField(max_length=150) owner = models.ForeignKey(User, on_delete=models.CASCADE, default=1) image = models.ImageField(upload_to=upload_location, null=True, blank=True) class CommentOnHotel(models.Model): hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField(max_length=200) published = models.DateField(auto_now_add=True) def __str__(self): return '{} - {}'.format(self.hotel.name, self.user.email) Forms.py class CommentOnHotelForm(forms.ModelForm): class Meta: model = CommentOnHotel fields = ['content'] views.py class HotelDetailView(DetailView): model = Hotel ........ -
How to pass a query string to render views context in a template?
I am trying to get my template shows a by enter query string like /q?DictionaryItem where the dictionary is in views. view.py def render_test(request): context = {'foo': 'bar', 'foz': 'baz'} return render(request, 'test.html', context) urls.py ... path('render_test/', views.render_test, name="render_test") ... test.html {{ foo }} {{ foz }} {{ request.GET.q }} the url render_test/?q=foo shows bar baz foo what I want is bar baz bar also for the url render_test/?q=foz it should show bar baz baz -
i want to run this project but still in problem ,i run that project few moths ago. but i facing problem also facing interpreter issue
enter image description here]1 Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. PS G:\python\CounselingChatOne\onlineCounseling> -
Django [Errno13] PermissionError while trying to upload to static folder
I am having an issue using Django Admin to upload an image to my production site. I am running Apache HTTPD server with sqlite db. Uploading works fine when running the development server, but when I attempt to add add a new entry to my site that includes an image I am greeted with the error: PermissionError at /admin/homepage/jumbotron/add/ I've attempted to research this error to the best of my ability but I am at a lost now. I have checked the file permissions including setting the group and owner to http http which is the user that apache httpd server is running under. I went ahead and temporarily gave my static folder full permissions with chmod -R 777 and restarted the httpd server, but the error still remained. I did a full system restart as well. The current file permissions are now: drwxrwxr-x 8 http http 4096 Jul 3 16:48 static I have tried other methods inside my setting.py like changing STATIC_URL to the full path or removing the first slash, so it's static/ and then restarting the server and nothing; no dice. setting.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates'), ] SECURE_SSL_REDIRECT = True INSTALLED_APPS = [ 'django.contrib.admin', … -
How to filter data in categories using django
I have been working on a django project very similar to hoop in which a user can search for friends using an snapchat profile. Well hoop filters the users by region for example before using the app, the user has to select the region the user is right now to later show that profile for the people searching friends in that region, also the app asks the user to select the region where the user wants to search for new friends. Basically I want to do the same filtering but instead of filtering the region, I want to filter by categories. Currently my code just shows the profiles to all the users but I have started to create 2 categories wich are "action" and "sports" but I dont know how to process that filtering, please any idea helps. models CATEGORY_CHOICES = ( ('action', 'action'), ('sports', 'sports'), ) class Mates(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='usermates', unique=True) categories = models.CharField(choices=CATEGORY_CHOICES, default="choose...", max_length=10) req_bio = models.CharField(max_length=400) req_image = models.ImageField(upload_to='requestmates_pics', null=True, blank=True, default=False) views.py def matesmain(request): contents = Mates.objects.all() context = { 'contents': contents, 'form_mates': MatesForm(), } print("nice3") return render(request, 'mates.html', context) def mates(request): if request.method == 'POST': form_mates = MatesForm(request.POST, request.FILES) if form_mates.is_valid(): … -
How to display translations in every password validation help text in Django?
Despite the fact that password validation help texts are translated in the official Greek translation (here), they don't seem to appear in my 3.0.3 application. Here's a screenshot of the custom registration form. As you can see the only working translation appears to be the one corresponding to MinimumLengthValidator while the others appear in English, despite the browser's Greek language setting. I would like to know a way to introduce translations for the entirety of help_text bullets under the password field in the registration form. Some crucial parts of my code settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': { 'min_length': 8, } }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'el' LANGUAGES = [ ('el', _('Greek')), ('en', _('English')), ] LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), ) TIME_ZONE = 'Europe/Athens' USE_I18N = True USE_L10N = False USE_TZ = True forms.py from django import forms from django.contrib.auth import authenticate, login, get_user_model from django.contrib.auth.forms import AuthenticationForm, UserCreationForm, ReadOnlyPasswordHashField from django.urls import reverse from django.utils.html import mark_safe from django.utils.translation import ugettext as _ User = get_user_model() from .models import User, Profile, EmailActivation class RegisterForm(UserCreationForm): … -
How to manage a stop or restart of a task from Django-based site?
I'll be running a script in a server which will automatically create model instances in a database. The idea is to use a infinite loop (e.g while True:) which will be endlessly creating instances until I somehow stop it. I want to use Django to nicely check from my website how big my database is, and from there I want to stop or restart it. What could be a good approach here? I was thinking about Celery, but I don't know how would I don't have clear how to stop it and it kind of looks like an overkill. Any suggestion? -
How can I access all routes, paths and urls from my React App (using react-router-dom) through Django?
The Context I am using React and Django for building a web app. I am using the djangorestframework to handle the API of my app and have successfully deployed the API for requesting information to my Django backend. All routing with the Django API works perfectly I have also made a very simple React website that can successfully request to this API in order to GET the objects from the Django database. I am handling the Routes in React with react-router-dom and their Router and Link components. All routing with React works as well, but ONLY if the components of the React app are clicked Also, everything works perfectly in npm start dev mode, but the django routing stops working when using the build from npm run build The Problem Although routing works when interacting with (clicking) the React components, such as a nav bar link, Routing does not work if the request is made manually by entering the link in the browser or reloading the page. Here's a video showing this issue. The Video Thank you! -
Issues with accessing the admin page
Whenever I Try to create superuser, I get: Type Error: create_superuser() missing 1 required positional argument: 'username' I've been trying different methods to crack this but it still leads me to the same error. -
question and answer system with django channels
I'm working on a question and answer system with django and I was wandering what's the best way to implement a QA system. my problem : I want the app to get a question from an ontology and according the user's answer get the next question. how can I have all the questions and user's answers displayed. i'm new to django, I don't know if I can use session with unauthenticated user and if I need to use websocket with the django channels library. -
Django Retrieve CRSF token
I would like to retrieve the CRSF token so I can do a POST externally from the website e.g via POSTMAN, or other external applications. I have exposed an API endpoint for user to upload files which they can do directly inside of doing it from website. However CRSF token is needed. I wish to extract it (user will login via external client, therefore I wish to be able to pass in CRSF token so they can include it and submit the file, of course it won't be visisble, the program will set it manually when they click upload on the external program) -
HTML Injection with Array from Python to JavaScript in Django
I am building a Django project and trying to send some data from a function in my views.py to the script part of a html template. My Problem is, that I am trying to send an Array of numbers, but the js part only receives NaN. So I tried to send the individual values, because the array is not very big. And tehn assemble the Array in the javascript. Unfortunately also the received numbers are NaN. The End of my views.py function looks like this: return render(request, 'Umfrage/datenauswertung.html', { 'cur_v':cur_v, 'cur_ans1': cur_ans1, 'cur_ans2': cur_ans2, 'cur_ans3': cur_ans3, 'cur_ans4': cur_ans4, 'cur_ans5': cur_ans5, 'cur_ans6': cur_ans6, 'min_v1_f1': min_v1_f1, 'min_v1_f2': min_v1_f2, 'min_v1_f3': min_v1_f3, 'min_v1_f4': min_v1_f4, 'min_v1_f5': min_v1_f5, 'min_v1_f6': min_v1_f6, 'lq_v1_f1': lq_v1_f1, 'lq_v1_f2': lq_v1_f2, 'lq_v1_f3': lq_v1_f3, 'lq_v1_f4': lq_v1_f4, 'lq_v1_f5': lq_v1_f5, 'lq_v1_f6': lq_v1_f6, In the html Template I am first saving the data in individual values and then assembling the array. In Order to check, what has been received I then print out the array, but it only gives an Array of NaN. <script> var cur_v = parseFloat("{{ cur_v|safe }}"); var cur_ans1 = parseFloat("{{ cur_ans1|safe }}"); var cur_ans2 = parseFloat("{{ cur_ans2|safe }}"); var cur_ans3 = parseFloat("{{ cur_ans3|safe }}"); var cur_ans4 = parseFloat("{{ cur_ans4|safe }}"); var cur_ans5 = … -
Requests.get on Django website page not working as expected
Having hard time figuring out what is happening here. I have Django website where I have one webpage with its own urls.py entry, view and template that does not use the Django base.py. I have non-Django Python code that uses requests.get() to retrieve the page and save it somewhere else. When I manually enter the url eg https://website.com/page/ into browser, it opens page as expected eg the resulting page contains just the page html and not the Django base.py. However, when I use requests.get('https://website.com/page/') it returns the page but it is wrapped in the Django base.py`. r = requests.get('https://website.com/page/') print(r.text) prints html for entire base.py with the page code The web page does not have {% extends "base.html" %} so I am really wondering how this is happening? What does requests.get() do or maybe what does Django do when returning requests.get() response? -
How i get image in javascript with html in form
In My javascript and jquery code is not run whats error can you tell and how i use image as text in button in javascript .means how i get image such as i get text in below code ....................................................................................................... template.html <form method="POST" action="{% url 'user_homeview:like_dislike_post'%}" class="like-form" id="{{i.id}}" > {% csrf_token %} <input type="hidden" name='post_id' id='post_id' value="{{i.pk}}"> <button id="like" class="like like-btn{{ i.id }}"> {% if request.user in i.liked.all%} unlike {% else %} like {% endif %} </button> And i want use instead of this code:. temp.html <form method="POST" action="{% url 'user_homeview:like_dislike_post'%}" class="like-form" id="{{i.id}}" > {% csrf_token %} <input type="hidden" name='post_id' id='post_id' value="{{i.pk}}"> <button id="like" class="like like-btn{{ i.id }}"> {% if request.user in i.liked.all%} <img src='{% static "images\like.png" %}' class="mt-2 settin"></button> {% else %} <img src='{% static "images\unlike.jpg" %}' class="settin"> {% endif %} </button> javascript code which is run successfully when i used template.html code. like.js <script> $(document).ready(function(){ $('.like-form').submit(function(e){ e.preventDefault(); console.log('Works done') const post_id=$(this).attr('id') console.log(this) console.log(post_id) const likeText=$(`.like-btn${post_id}`).text() console.log(likeText) const trim = $.trim(likeText) console.log(trim) const url =$('.like-form').attr('action') console.log(url) $.ajax({ type: 'POST', url:url, data:{ 'csrfmiddlewaretoken':$('input[name=csrfmiddlewaretoken]').val(), 'post_id':post_id, }, success:function(){ console.log('success') $.ajax({ type:'GET', url:'http://127.0.0.1:8000/user_homeview/serilized/', success:function(response){ console.log(response) $.each(response,function(index,element){ console.log(index) console.log(element.content) if (post_id==element.id){ if(trim=='like'){ $(`.like-btn${post_id}`).html('like') console.log('unlike') }else if(trim=='unlike'){ $(`.like-btn${post_id}`).html('like') console.log('like') }else{ console.log('ooopss!') } } } )} }) … -
trying to display a Sum on template of each instance of a class field filtered by another field on that same class. python django fantasy sports
I am trying to build a fantasy sports website. I have NBA players (as a class) assigned to (django's built-in) Users (the fantasy team) via a field on the Player Class. I want to sum all of a User's players' salaries for a given year and list that on that User's (aka team's) Player roster page (regardless of who is signed in.) I was able to get this Sum on the django shell for a specific user_id: imported Player class to shell & django.db.models import Sum Player.objects.filter(player_owner__exact='1').aggregate(Sum('player_sal_19_20')) result: {'player_sal_19_20__sum': Decimal('89654339')} But how can I get this sum on the template for the fantasy team's public roster page? I have spent days trying the aggregate function, trying to incorporate it with my get_queryset (see views snippet) function, template tags, and some other methods that went way over my head. I am using django's built-in Users as my teams and have created a player class on models.py: class Player(models.Model): player_full = models.CharField(max_length=50) player_sal_19_20 = models.DecimalField(default=0, max_digits=10, decimal_places=2) player_sal_20_21 = models.DecimalField(default=0, max_digits=10, decimal_places=2) player_sal_21_22 = models.DecimalField(default=0, max_digits=10, decimal_places=2) player_sal_22_23 = models.DecimalField(default=0, max_digits=10, decimal_places=2) player_owner = models.ForeignKey(User, default='26', on_delete=models.CASCADE) Then I created a view for a User's players page on views.py: class UserPlayerListView(ListView): model …