Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I change my profile image in django?
I'm Trying to develop a social website, and in my user profile page I want to display the user's selected image from the registration page. I provided a default.jpg in my media folder in case the user dosen't want to upload an image. But everytime I'm trying to register a new user, even if I'm selecting a different image, the default image is being displayed. Can anyone please help me out? my models.py from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') CHOICES = ( ('AB+', 'AB+'), ('AB-', 'AB-'), ('A+', 'A+'), ('A-', 'A-'), ('B+', 'B+'), ('B-', 'B-'), ('O+', 'O+'), ('O-', 'O-'), ) bloodgroup = models.CharField(max_length=100, choices= CHOICES) bio = models.TextField(max_length=300) def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) my forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('image', 'bloodgroup', 'bio') class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class … -
Django: can't get the url for update action to work with ModelViewSet
I am using ModelViewSet and Modelserializer for a blog like project. It could be my difficulty in understanding the implementation; I can't get the update action to work via calling it through router, only the list action is working with the route I have defined. When I put the url : 127.0.0.1:8000/api/blogs/1, to return the blog with ID 1 to edit, it returns {"Detail": "Not Found."}. This is my view: class ArticleViewSet(viewsets.ModelViewSet): queryset = Article.objects.all() serializer_class = ArticleSerializer I have also overridden the save and update methods in the serializer class, don't know whether it was needed for ModelViewSet in ModelSerializer. class ArticleSerializer(serializers.ModelSerializer): def create(self, validated_data): article = Article.objects.create( article_title = self.validated_data['article_title'], article_content = self.validated_data['article_content'], ... ) return article def update(self, instance, validated_data): instance.article_title = validated_data.get('article_title', instance.article_title) instance.article_content = validated_data.get('article_content', instance.article_content) ... instance.save() return instance class Meta: model = Article fields = ... And the urls.py file: router = DefaultRouter() router.register(r'blogs', ArticleViewSet, basename='articles-list') urlpatterns = router.urls My question is: 1. How do I specify urls for the ModelViewSet actions (in my case the update action)? 2. Will defining only one url suffice all my needs with every ModelViewSet actions? if so how? What am I doing wrong? I'm new to … -
Django with apache in centos 8. don't have permission to access / on this server(newly deployed)
filesystem path '/var/www/mysite/mysite/wsgi.py') because search permissions are missing on a component of the path [Fri Mar 20 06:35:04.536515 2020] [core:error] [pid 8177:tid 140498932373248] (13)Permission denied: [client 192.168.1.4:54121] AH00035: access to /favicon.ico denied (filesystem path '/var/www/mysite/mysite/wsgi.py') because search permissions are missing on a component of the path, referer: http://192.168.1.2/ [Fri Mar 20 06:36:23.588628 2020] [core:error] [pid 8503:tid 140498958239488] (13)Permission denied: [client 127.0.0.1:53958] AH00035: access to / denied (filesystem path '/var/www/mysite/mysite/wsgi.py') because search permissions are missing on a component of the path -
Redis Flushall command in Heroku Scheduler (Python/Django Project)
For a Django application, I want Heroku Scheduler to perform the following commands: heroku redis:cli flushall exit (ctrl-c) I do this myself once a day now in terminal, but it would be a lot easier if I can schedule these commands. My question is, is it possible to put these commands in a Python script, or do I need to work in another way? Does anyone has experience with this? -
django computation in aggregate
I have this computation in my views that using filter and aggregate method first is i distinct the select the StudentSubjectGrade models and in the overall i filter the average and i use aggregate to compute the average and for every grading categories i have to multiply it by its PercentageWeight. this is the computation average = average * Grading_Categories__PercentageWeight / 100 students = StudentSubjectGrade.objects.filter( grading_Period=period).filter( Subjects=subject).order_by( 'Students_Enrollment_Records', 'Grading_Categories','id' ).values('id','Grading_Categories','Average', 'Grading_Categories__PercentageWeight') overall = StudentSubjectGrade.objects.filter( grading_Period=period).filter( Subjects=subject).aggregate(average_grade=Avg('Average') * students[ 'Grading_Categories__PercentageWeight'] / 100) this is their models class StudentSubjectGrade(models.Model): GradeLevel = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Students_Enrollment_Records = models.ForeignKey(StudentsEnrolledSubject, related_name='+', on_delete=models.CASCADE, null=True) Grading_Categories = models.ForeignKey(gradingCategories, related_name='+', on_delete=models.CASCADE, null=True, blank=True) grading_Period = models.ForeignKey(gradingPeriod, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Gradedates = models.DateField(auto_now_add=True) Average = models.FloatField(null=True, blank=True) class gradingCategories(models.Model): CategoryName = models.CharField(max_length=500, null=True) PercentageWeight = models.FloatField() this is the error i get -
Has Django version 3 stoped the need to register new apps in settings.py installed apps list?
I am new to django and the apps i create are working with out any need for them to be registered in settings.py of the project. Has django version 3 started to do this or is this a bug in my side? -
Django change form page data change after each refresh
I currently have a Fake model which based on of a view on mysql: class Transaction(models.Model): id = models.BigIntegerField(primary_key=True) transaction_id = models.IntegerField(default=0) user = models.IntegerField(null=True) transaction_type = models.CharField(null=True, max_length=255) to_bank = models.IntegerField(null=True) to_address = models.CharField(null=True, max_length=255) to_account = models.IntegerField(null=True) to_card = models.IntegerField(null=True) method = models.PositiveIntegerField() currency = models.IntegerField() amount = models.DecimalField(max_digits=65, decimal_places=0, default=0) fee = models.DecimalField(max_digits=65, decimal_places=0, default=0) status = models.PositiveIntegerField() created = models.DateTimeField() confirmed = models.DateTimeField() class Meta: managed = False db_table = 'v_transactions' verbose_name = 'Transaction History' verbose_name_plural = 'Transactions History' And MySQL view has the following query : CREATE VIEW v_transactions AS SELECT row_number() OVER () as id, transaction_id, user, transaction_type, to_bank, to_address, to_account, to_card, method, currency, amount, fee, status, created, received FROM (SELECT id as transaction_id, user_id AS user, "top up" AS transaction_type, NULL AS to_bank, NULL AS to_address, user_id AS to_account, NULL AS to_card, method, currency_id AS currency, amount, fee, status, created, received AS confirmed FROM topups WHERE deleted IS NULL UNION ALL SELECT id as transaction_id, user_id AS user, "transfer" AS transaction_type, NULL AS to_bank, to_address, to_account, NULL AS to_card, method, currency_id AS currency, amount, fee, status, created, confirmed FROM transfers WHERE deleted IS NULL UNION ALL SELECT id as transaction_id, user_id AS user, … -
How to open an uploaded saved file in another template?
my django app acts as an emailing service, emails that are sent are view-able and it's possible to send html emails. How do I display the html emails on the view-mail page rather than just displaying the name of the file ? (the following is the mail-view for an html email): How would I display the actual html in the body of this page? This is my views.py: def outbox(request): #Mail_Item.objects.all().delete() if request.method == "POST" and request.POST.get('Username', False)!=False: username = request.POST.get('Username') password = request.POST.get('Password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user, backend='django.contrib.auth.backends.ModelBackend') print(username + " has logged in") messages = Mail_Item.objects.filter(user=request.user.username) args = {'messages':messages} return render(request, 'outbox.html', args) else: return render(request, '404.html') elif request.POST.get('Username', False) == False and request.POST.get('mail_body_field', False) == False: pass elif request.method == "POST" and request.POST.get('mail_subject_field')!=False: subject = request.POST.get('mail_subject_field') body = request.POST['mail_body_field'] file = "" try: file = request.FILES['filename'] except: pass print("sending mail:") for i in range(1, len(Res)+1): y = Res['ID' + str(i)].email print("sent to " + y ) msg = EmailMessage(subject, body, 'email@example.com', [y]) msg.content_subtype = "html" if (str(file)) != "" and (str(file))[-4:] != 'html': msg.attach_file(str(file)) obj = Mail_Item(subject=subject, body=body, user=request.user.username, file_name=(str(file))) obj.save() print("email stored in database") elif (str(file)) != "" … -
How can i exit the python shell to the terminal in Pycharm?
For example, I wrote the code; SyntaxError: invalid syntax python manage.py command File "", line 1 python manage.py command* to get to the shell now I can't return back to the command line in Pucharm -
How to make a web app using both django and express? How would you interchange data between the two platforms?
I was trying to make a web app with a complicated idea and at some point realised that I couldn't do it alone. When, I started to look around for friends with a skill set with node in their bag, I found out that everyone had experience with pure php or django. I was thinking if I could make the web app by combining different backend technologies. But I can't really understand where and how to start. What would I need to learn? How would I exchange values or data between the two frameworks or programming languages? What things would I have to learn? Where would I start? -
django-allauth: how to avoid requesting friends list?
I have set user registration via Facebook with django-allauth. When I am trying to login with Facebook, Facebook notifies me that the app wants to get the list of my users. However, these data are not stored in my database after the login, nor are they included in my settings.py. How can I disable requiring the list of friends? Django-allauth settings from settings.py: SOCIALACCOUNT_PROVIDERS = \ { 'facebook': {'METHOD': 'oauth2', 'SCOPE': ['email','public_profile', 'user_friends'], 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'FIELDS': [ 'id', 'email', 'name', 'first_name', 'last_name', 'verified', 'locale', 'timezone', 'link', 'gender', 'updated_time'], 'EXCHANGE_TOKEN': True, 'LOCALE_FUNC': lambda request: 'path.to.callable', 'VERIFIED_EMAIL': False, 'VERSION': 'v2.4'}, 'google': { 'SCOPE': ['https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email'], 'AUTH_PARAMS': {'access_type': 'online'}, } } -
Django HighChart with Api
I'm new at Django please help me, I read some articles vlogs seems I cannot find the right code here's my code in views.py and i want it to disply in in HTML index.html and the result is it wont display I dont know what is wrong with my code from django.shortcuts import render from django.http import JsonResponse,HttpResponse import requests import pandas as pd import json def home(request): response = requests.get('https://coronavirus-ph-api.now.sh/cases').text # li = list(response.split(",")) res = json.loads(response) maleCount = 0 femaleCount = 0 for i in res: if i['gender'] == 'M': maleCount += 1 else: femaleCount += 1 TotalCount =[ { "name": "MALE", "data": [maleCount]}, { "name": "FEMALE", "data": [femaleCount] } ] return render(request,'index.html',{'data':TotalCount}) and here my code in html in index.html tru views.py it wont display my data in html seems my code wont work what is the problem of my code? please help thank you <!doctype html> <html lang="en"> <body> <div class="container-fluid"> <div class="border" id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div> </div> <script src="https://code.highcharts.com/highcharts.js"></script> <script src="https://code.highcharts.com/modules/exporting.js"></script> <script src="https://code.highcharts.com/modules/export-data.js"></script> <script> Highcharts.chart('container', { chart: { type: 'column' }, title: { text: 'Total fruit consumtion, grouped by gender' }, xAxis: { categories: ['asd','asd'] }, yAxis: { allowDecimals: false, min: … -
Django compare Datefield in template
I am trying to make a Django template page that uses Chart.js. The idea is that it would have fields for the user to add 'From' and 'To' date range to pass to Django template data to fill the Chart.js. In order for me to figure out how to do that I need to know how to compare dates in Django templates but I can't seem to figure it out, again the below is just a test to figure out how you would compare dates in a template, simplified so I can try the harder parts. entriesFuel.0.day is equal to March 5, 2020 and is a Django form DateField. I have tried the below {% if entriesFuel.0.day == "5 March 2020" %} <h1>{{entriesFuel.0.day}}</h1> {% else %} <h1>{{entriesFuel.1.day}}</h1> {% endif %} {% if entriesFuel.0.day == "March 5, 2020" %} <h1>{{entriesFuel.0.day}}</h1> {% else %} <h1>{{entriesFuel.1.day}}</h1> {% endif %} {% if entriesFuel.0.day == "2020-03-05" %} <h1>{{entriesFuel.0.day}}</h1> {% else %} <h1>{{entriesFuel.1.day}}</h1> {% endif %} Is it possible to compare the data this way or am I barking up the wrong tree by doing it this way? Thank you, -
python manage.py runserver : the given ( http://127.0.0.1:8000/ ) not working after doing my project
heloo iam new to django and while doing my first clone blog project when im trying:* python manage.py runserver it is showing: enter image description here Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). March 19, 2020 - 13:15:32 Django version 3.0.4, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) Git GitHub Create Repository Initialize /home/user/Desktop/project with a Git repository Create repository .............................etc But cant access in browser via [http://127.0.0.1:8000][2] instead it is showing enter image description here Unable to connect Firefox can't establish a connection to the server at 127.0.0.1:8000. The site could be temporarily unavailable or too busy. Try again in a few moments. If you are unable to load any pages, check your computer's network connection. If your computer or network is protected by a firewall or proxy, make sure that Firefox is permitted to access the Web. -
Django PasswordChangeForm not displaying message
I am using the Django PasswordChangeForm def change_password(request): if request.method == 'POST': form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) # Important! messages.success(request, 'Your password was successfully updated!') return redirect('change_password') else: messages.error(request, 'Please correct the error below.') else: form = PasswordChangeForm(request.user) url = 'registration/change_password.html' return render(request, url, {'form': form}) But on success the messages.success does not appear What can I do? -
How to display the selected filter value as selected in django template?
Here I have a simple form for filtering. The filtering works fine totally but one problem is the filter parameter is not displaying into the option as selected. I want to display the filter title which is recently used to filter as selected after filtering. How can I do it? template <form action="{% url 'filter' %}" class="form-inline"> <select name="title" class="custom-select"> {% for category in categories %} <option value="{{category.title}}" >{% if title %}{{title}} {% endif %}{{category.title}}</option> {% endfor %} </select> <input type="submit" class="btn btn-info" value="Filter"> </form> <h6> Results for {{title}}: </b> views def filter_by_title(request): title = request.GET.get('title') results = MyModel.objects.filter(title=title) categories = Cateogory.objects.all() return render(request, 'template', {'results': results, 'title': title, 'categories': categories}) -
Django CSRF Issues While Using Dynamic Formsets and Django Formtools
I am using Django formttools to create a multistep wizard. In one of the forms I have a question option where users need to add as many question as may be need. I have achieved the dynamic formsets through Django Dynamic Formset but although I have the {% csrf_token %} in my template I still get CSRF issues. Here is my template: {% block content %} <p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p> <form action="" method="post" enctype="multipart/form-data" id="job-question">{% csrf_token %} <table> {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form }} {% endfor %} {% else %} {{ wizard.form }} {% endif %} </table> {% if wizard.steps.prev %} <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">{% trans "first step" %}</button> <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans "prev step" %}</button> {% endif %} <input type="submit" value="{% trans "submit" %}"/> </form> <script type="text/javascript" src="{% static 'js/jquery-min.3.4.1..js' %}"></script> <script type="text/javascript" src="{% static 'js/jquery.formset.js' %}"></script> <script type="text/javascript"> $(function() { $('#job-question').formset(); }) </script> {% endblock %} -
Django-like web framework for go
I am looking for a web framework that has a django-like pattern for go. Important features are: Database "out of the box": Just like django naturally comes up with an SQLite database Object mapping & auto-migration Optional nice-to-have: Admin-site for managing the database Yet, I haven't found anything in go that offers these features or has an django-like structure at all. -
Submit django form in a modal popup
I render my form inside a modal: view: @login_required def task_edit(request, pk): member = get_object_or_404(Tasks, pk=pk) if request.method == "POST": form = TasksForm(request.POST or None, instance=member) if form.is_valid(): reg = form.save(commit=False) reg.save() return HttpResponse( '<script type="text/javascript">window.close();</script>') else: form = TasksForm(instance=member) return render(request, 'TaskProj/task_edit.html', {'form': form}) my html rendered in a modal popup: {%load staticfiles %} <div class="row"> <div class="col-lg-12"> <div class="panel"> <div class="content-box"> <h3 class="content-box-header bg-primary"> <span class="icon-separator"> <i class="glyph-icon icon-tasks"></i> </span> <span class="header-wrapper"> Eidt Tasks </span> </span> </h3> <div class="panel"> <div class="panel-body"> <form method="POST" class="form-horizontal bordered-row" autocomplete="off"> {% csrf_token %} <div class="example-box-wrapper"> <div class="form-group"> {{ form.as_p }} </div> </div> <button type="submit" class="btn btn-primary btn-lg btn-block">Salva</button> </div> </div> </form> <script type="text/javascript"> $(document).on('click','.submit',function(){ }); </script> {% endblock %} This form is rendered inside a modal popup. I try to save but nothing happen. I think there is a problem with submit button... Any idea? TY -
Sending Wrong Mail at Time
i have a task to sending mail take the time in database in celery but when it work it send all to user in all time but not one user in their time , (example : A has sent to 8:30 and b has send to 9:30) but when it work it send both to A and B in 8:30 , A and B in 9:30 , how can i fix that ? @shared_task def send_email_spetime(): top_article = Article.objects.all()[0] article1 = Article.objects.all()[1:3] article2 = Article.objects.all()[3:5] last_article = Article.objects.all()[5:8] context = { 'top_article': top_article, 'article1': article1, 'article2': article2, 'last_article': last_article, } #Sending the email to UserMail # Sending the Email users_mail = UserMail.objects.all() for each_user in users_mail: if each_user.auto_send_mail == False: msg_plain = render_to_string('timeset/email_templates.txt') msg_html = render_to_string('timeset/index3.html', context) subject = "NEWS" recepient = each_user.user_mail send_mail(subject, msg_plain, EMAIL_HOST_USER, [recepient], html_message=msg_html, fail_silently=False) send_email_spetime.apply_async(eta=each_user.time_set + timedelta(minutes=1)) -
How can I get item from a model field
I'm a Django beginner, how can I get profile_pic from Profile Model connecting it to 'to_user' field in FriendRequest Model. I was able to get the names of users in 'to_user' field by this: {% for data in sent_friend_request %} {{ data.to_user.username }} {% endfor %} How do I get the profile_pic for each users? class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) profile_pic = models.ImageField() class FriendRequest(models.Model): to_user = models.ForeignKey(settings.AUTH_USER_MODEL) from_user = models.ForeignKey(settings.AUTH_USER_MODEL) def following_view(request, username): p = Profile.objects.filter(user__username=username) all_profile_users = [] button_status_list = [] for user_obj in p: u = user_obj.user all_profile_users.append(u) sent_friend_request = FriendRequest.objects.filter(from_user=u) context = {'sent_friend_request':sent_friend_request} -
Can't make my python code work with Django and Mysql
Guys i am new with Django and would highly appreciate your help. The data is retried form DB. The idea is that a user enters product name in the search field and get its info and analysis: views.py def home(request): if request.method == "POST": form = StockingForm(request.POST) if form.is_valid(): form_f = form.save(commit=False) prinf = form_f.prinf prod=Product.objects.get(product=prinf) sales2019=Sales_2019.objects.get(product=prinf) sales2018=Sales_2018.objects.get(product=prinf) context={ 'product':prod , 'sales_2019':sales2019,'sales_2018':sales2018,} return render(request, 'staff/info.html', context) else: form = StockingForm() return render(request, 'staff/all.html', {'form': form}) model.py class Sales_2019(models.Model): product=models.CharField(max_length=200) gloves=models.DecimalField(decimal_places=3,max_digits=100000000) bags=models.DecimalField(decimal_places=3,max_digits=100000000) I have created seperate file code.py within the application as the code is much bigger: gloves=[sales2019.gloves,sales2018.gloves] bags=[sales2019.bags,sales2018.bags] analysis_1=[a/b for a,b in [gloves,bags] My questions: how to make the code from code.py to work in view. py where it takes values from user input and sents back to code.py and make calculation and how to show result analysis_1 ? Would be helpful if you could share some example of code to better understand. -
Hello everybody. And log in class when try to migrate or runserver my whole project , this error is appearing again and again
enter image description herePlease help me to solve this question. I tried a lot but still this is appearing. -
TypeError at /register/ 'AnonymousUser' object is not iterable
I am currently developing a blogging webapp and I tried to extend my Django User Framework With a One To One Field, everything is working fine, but when I'm trying to register a new user, it's throwing a TypeError. It is also worth noting that the user is being created and stored(I checked it from the admin page). It is saying that this statement profile.user = Profile.objects.get(user=request.user) in my views.py is creating the problem. Can anyone please help me with this? my models.py: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') CHOICES = ( ('AB+', 'AB+'), ('AB-', 'AB-'), ('A+', 'A+'), ('A-', 'A-'), ('B+', 'B+'), ('B-', 'B-'), ('O+', 'O+'), ('O-', 'O-'), ) bloodgroup = models.CharField(max_length=100, choices= CHOICES) bio = models.TextField(max_length=300) def __str__(self): return f'{self.user.username} Profile' my views.py from django.shortcuts import render, redirect from .models import Profile from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import UserRegisterForm, ProfileForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) profile_form = ProfileForm(request.POST) if form.is_valid() and profile_form.is_valid(): form.save() profile = profile_form.save(commit=False) profile.user = Profile.objects.get(user=request.user) profile.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in') return redirect('login') … -
Using toggle in for loop
In my Django template, I am retrieving the data from DB and displaying it in table format. Now, when I click on "Name" field, I want to show some data of that person. Initially, while displaying, only the table should be visible, which means the data of the particular person should remain hide and when I click on that person's name, the information about that person should be shown. Now, I have 2 problems. 1st is, when I click on any name, the information about all the persons gets displayed. For example, if there are 3 entries in my DB and if I click on the name of any person than the information about all the 3 people will get displayed. I just want to display the information of the person on which I clicked on. And the second problem is that after clicking on the name, the data is displayed on the top of the table. I want that suppose I am clicking on the second row, then the information should be displayed below the 2nd row and above the 3rd row. <table> <tr> <th>id</th> <th>Name</th> <th>Status</th> </tr> {% for records in obj %} <tr> <td>{{records.id}}</td> <td id="pop">{{records.name}}</td> <div …