Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can't save tags in django
i am using django-taggit to save tags. It save some tags but now its not working and idk why! still finding the solution. Please help me to find out what i am doing wrong. I am not getting any errors. But when i save the form using form.save_m2m() nothing is saved in my database. I have also checked my admin pannel. Nothing is storing in my db. Is there is any way to check this. I am also attaching the template. views.py from django.shortcuts import render,redirect,get_object_or_404 from django.http import HttpResponse from django.contrib.auth.decorators import login_required from . models import UserCreatedNote from django.template.defaultfilters import slugify from . forms import AddNoteForm from taggit.models import Tag # Create your views here. @login_required def notes(request): if request.method=='POST': form = AddNoteForm(request.POST) if form.is_valid(): form_data = form.save(commit=False) form_data.user = request.user key = form_data.note_title form_data.slug = unique_slug_generator(slugify(key)) form_data.save() #to save tags form.save_m2m() notes = UserCreatedNote.objects.filter(user=request.user) form = AddNoteForm() context = {'notes': notes,'add_note_form':form} return render(request,'usernotes.html',context) notes = UserCreatedNote.objects.filter(user=request.user) form = AddNoteForm() context = {'notes': notes,'add_note_form':form} return render(request,'usernotes.html',context) @login_required def edit(request,slug): note = get_object_or_404(UserCreatedNote, slug=slug) tagsList = [] for tag in note.note_tags.all(): tagsList.append(tag.name) print(tagsList) if request.method == 'POST': form = AddNoteForm(request.POST, instance=note) if form.is_valid(): form_data = form.save(commit=False) form_data.user = request.user … -
ERROR: Your WSGIPath refers to a file that does not exist
I'm having trouble in deploying my django-react app. This is my directory tree. . ├── .elasticbeanstalk └── backend ├── .ebextensions ├── auth │ ├── management │ │ └── commands │ └── migrations ├── client │ └── build │ └── static │ ├── css │ ├── js │ └── media ├── config │ └── settings ├── postings │ ├── management │ │ └── commands │ └── migrations └── uploads # /.ebextensions/django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: config/wsgi.py NumProcesses: 3 NumThreads: 20 # /backend/config/wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.deploy") application = get_wsgi_application() And application enviroment on aws website, WSGIPath: config/wsgi.py, NumProcesses: 3, NumThreads: 20 I can't find what should I fix. -
Overrinding a field in different table on django
I want when i save new order, to save the order.id_order on company.last_order class Company(models.Model): name = models.CharField(max_length=240) last_order = models.DecimalField(max_digits=20, decimal_places=0) class Order(models.Model): company = models.ForeignKey('Company', on_delete=models.CASCADE) id_order = models.DecimalField(max_digits=20, decimal_places=0) -
Can i have multiple views and serializers for single model in django rest framework
I am building an application in which an owner is posting a job post and multiple user will apply for that job application. I have provided an endpoint to user to apply for a certain job post and it went successful. Then, I tried to provide a separate endpoint to an owner in which I want to view the application and edit the status of the application. To implement this I used a separate serializer which allows only status field to be updated and making rest of the fields as read only. Additionally, I created the separate view as well for the owner to update the status of the application based on id filter. Lastly, creating a separate URL as well. So, the 2 URLs are: /api/job/application (for user) /api/job/application-status (for owner) But I ended up in a situation where I am getting the same URL for both of the job application endpoint and job application status endpoint because they are using same model. So, is it possible to have multiple views and serializers for a single model? If Yes, then how can I achieve this and what permissions should I use for owner. -
Spotify authentication using Spotipy not showing and my redirect uri is refusing to connect?
Using Spotipy(A spotify module to access data using the Spotify API) and Django, I am trying to use the Authorization Code Flow for authentication but I keep running into an error when I use the login route. The URL http://localhost/?code=AQDaVeJPteLHVgQG7P41mX5XMmoriJtbpx7vjRYdTXBR64Fal2IMHXQfnSoEdrYrZnYwM-xjyyr_ME_t_gsbqR6-72A4sRBQZ1aaoJd7Xcr2rqT_9aF_kDND0XmZZMhRQzN4oAujH6Uawl9d-tEJmnE_Q-yISGAGTuIHlONwbPEretR9XdPXQg with an error localhost refused to connect comes up after I use the login route urls.py urlpatterns = [ path("login/" , views.login , name = "login" ), path("home/", views.home, name= "home"), path("callback/" , views.callback , name="callback") ] views.py #get_authorize_url()method returns a Spotify API endpoint https://accounts.spotify.com/authorize?client_id=83654ff787fc48c7a38cc7976238628a&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%2F&scope=user-library-read def login(request): authorize_url = oauth.get_authorize_url() return redirect(authorize_url) get_access_token() returns the access token def callback(request): code = request.GET.get("code") if code is not None: oauth.get_access_token(code) return redirect(reverse("home")) else: return redirect(reverse("login")) def home(request): return HttpResponse("Welcome") -
How to change the beginning id in django?
I'm trying to set an AutoField starting point to 1000, instead of 1, 2, 3, ... I want to make it 1001, 1002, 1003, ... here's the model: class User(models.Model): id = models.AutoField(min_length=4) getting this error after running makemigrations command. Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Python38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Python38\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Python38\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Python38\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Python38\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\test\Desktop\mhlogo\users\models.py", line 5, in <module> class User(models.Model): File "C:\Users\test\Desktop\mhlogo\users\models.py", line 6, in User id = models.AutoField(min_length=4) File "C:\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 2357, in __init__ super().__init__(*args, **kwargs) TypeError: __init__() got an unexpected keyword argument 'min_length' using django 3.1 and mariadb 10.4 -
Django, MVC pitfalls for POSTs when rev proxy down, caching failed POSTs, none user Auth
Disclaimer Firstly, I understand SO is for code based answers, I did some research on where to ask this questions, and it seems like according to the community SO got 20 votes for asking: Questions about deployment and support of applications past release, in particular towards design for maintainability. Intro My question is I personally spent last 2 years working on a Django project for a factory, it uses the standard MVC pattern. The app uses the factory IP for authentication for terminals in the factory. It was my first web project and I have learnt a lot from it, and hence re-written many aspects of it. 3 Problems with Django MVC However I have now reached a point where I am wondering if it needs a re-write since I see no great solutions to the following problems with the MVC pattern: I wish to be able to POST data, and control what happens if it fails on the client side. With a normal POST, once one has submitted the form, one let's go of control. This means if the server is restarting, or receiving an update, and the reverse proxy (UWSGI) is not up yet, Nginx shows an error … -
Error while trying to pip install mysqlclient in my django project?
ERROR: Command errored out with exit status 1: ... cwd: /tmp/pip-install-0w18_khs/mysqlclient/ Complete output (12 lines): /bin/sh: 1: mysql_config: not found /bin/sh: 1: mariadb_config: not found /bin/sh: 1: mysql_config: not found Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-0w18_khs/mysqlclient/setup.py", line 15, in <module> metadata, options = get_config() File "/tmp/pip-install-0w18_khs/mysqlclient/setup_posix.py", line 65, in get_config libs = mysql_config("libs") File "/tmp/pip-install-0w18_khs/mysqlclient/setup_posix.py", line 31, in mysql_config raise OSError("{} not found".format(_mysql_config_path)) OSError: mysql_config not found ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. -
Django. How do I add a field to a query result?
I have a Room model and I want to add the is_member boolean field to a queryset with rooms. How can do this? I was thinking of using .annotate (), but that doesn't work for my task. models.py from django.db import models class Room(models.Model): name = models.CharField(max_length=150) members = models.ManyToManyField(User, blank=True) views.py from rest_framework.views import APIView from rest_framework.response import Response from .serializers import RoomSerializer from .models import Room class RoomView(APIView): def get(self, request): rooms = Room.objects.all() # get all rooms user = request.user # get current user for room in rooms: members = room.members.all() # get members is_member = user in members # set boolean value room.is_member = is_member # set in room serializer = RoomSerializer(rooms, many=True) return Response(serializer.data) serializers.py from rest_framework import serializers from .models import Room class RoomSerializer(serializers.ModelSerializer) is_member = serializers.BooleanField(read_only=True) class Meta: model = Room fields = "__all__" I solved this issue this way, but is there any other options to do it? Help me please -
Django | REST | Three related tables to JSON
please I need advice - is possible to reach a JSON output like this: data: code: A, get_code_display: ATV makes: Honda: model_set: Rancher SXS500 M code: T, get_code_display: Automobile makes: BMW: model_set: X6 535i Audi: model_set: A8 A6 A4 code: M, get_code_display: Motorcycle makes: Honda: model_set: CB1000R CB500F Yamaha: model_set: R1 R6 With model of database, like this: models.py: TYPE_CHOICES = ( ('A', 'ATV'), ('T', 'Automobile'), ('M', 'Motorcycle'), ) class Make(models.Model): name = models.CharField(max_length=64) class Type(models.Model): code = models.CharField(max_length=1, choices=TYPE_CHOICES, unique=True) class Model(models.Model): make = models.ForeignKey(Make, on_delete=models.CASCADE) type = models.ForeignKey(Type, on_delete=models.CASCADE) name = models.CharField(max_length=64) class Vehicle(models.Model): make = models.ForeignKey(Make, on_delete=models.CASCADE) model = models.ForeignKey(Model, on_delete=models.CASCADE) name = models.CharField(max_length=64) With Django Rest Framework? What I am able to do, is get model_set from a Make and Type, but is there any way, how to combine these? Or this DB model is bad? I have added ForeignKey of Type to Model table, because for example Honda can produce Automobiles and also Motorcycles - just name of its vehicle model will be different. Another option here, is to use two serializers - for Make and Type with Filtering in Rest framework via django-filter, but when I created solution, which should work, I am able … -
Django application mod_wsgi error with apache
I'm hosting Django app on AWS ec2 with ubuntu 20.04 lts. I can run the app with venv on various ports. I want to bind the app with apache so that my users can visit my app with just the public DNS no ports, only on the default port. So I have installed apache2, mod_wsgi. My virtual host configuration. <VirtualHost *:80> ServerAdmin test@example.com DocumentRoot /var/www/html/app_folder ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /var/www/html/app_folder/static <Directory /var/www/html/app_folder/static> Require all granted </Directory> Alias /static /var/www/html/app_folder/media <Directory /var/www/html/app_folder/media> Require all granted </Directory> <Directory /var/www/html/app_folder/main_app> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess app_folder python-path=/var/www/html/app_folder python-home=/home/ubuntu/.local/lib/python3.8/site-packages/django/__init__.py WSGIProcessGroup app_folder WSGIScriptAlias / /var/www/html/app_folder/main_app/wsgi.py </VirtualHost> So after configuring this vhost i restart my apache2 but I get nothing on the public dns. Instead I get the following error logs on my /var/log/apache2/error.log [Wed Dec 02 08:50:05.967958 2020] [wsgi:warn] [pid 121300] (13)Permission denied: mod_wsgi (pid=121300): Unable to stat Python home /home/ubuntu/.local/lib/python3.8/site-packages/django/__init__.py. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Python path configuration: PYTHONHOME = '/home/ubuntu/.local/lib/python3.8/site-packages/django/__init__.py' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 import site … -
Bootstrap popover does not work with downloaded js and css
I am having some weird problem with using popover in my django app. When using the css and js of a latest version of bootstrap it simply does not work. When I use link to 3.4.1 version I found in some tutorial everything works just fine. I'm attaching code that doesn't work and the one that does. Did popover function got removed in latest bootstrap? Works (3.5.1): <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="{% static 'js/jquery-3.5.1.min.js' %}"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <a href="#" data-toggle="popover" title="Popover Header" data-content="Some content inside the popover">Toggle popover</a> <script> $(document).ready(function(){ $('[data-toggle="popover"]').popover(); }); </script> Does not work (4.5.x): <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <script src="{% static 'js/jquery-3.5.1.min.js' %}"></script> <script src="{% static 'js/bootstrap.min.js' %}"></script> <a href="#" data-toggle="popover" title="Popover Header" data-content="Some content inside the popover">Toggle popover</a> <script> $(document).ready(function(){ $('[data-toggle="popover"]').popover(); }); </script> -
how to add category to blog project django
i developed a blog project by watching many open-source courses and create my own django custom admin dashboard where i want to add a category option to my blog project, i have watched some tutorial on as well but couldn't find them helpful models.py from django.db import models from django.forms import ModelForm from farmingwave.models import BaseHeader,Submenu class Category(models.Model): mainmenu=models.ForeignKey(BaseHeader,null=True,on_delete=models.SET_NULL) submenu=models.ForeignKey(Submenu,on_delete=models.CASCADE) class AdSideMenu(models.Model): title_id = models.AutoField(primary_key=True) title_name = models.TextField() url = models.TextField() priority = models.IntegerField() submenu_status = models.TextField() class Meta: db_table = 'admin_side' class CreateBlog(models.Model): id = models.AutoField(primary_key=True) blog_Title = models.TextField(max_length=100) content = models.TextField(max_length=5000) category = models.ForeignKey(Category,null=True,on_delete=models.SET_NULL) class Meta: db_table = 'create_blog' they are inhereting data from another app models.py `class BaseHeader(models.Model): main_id = models.AutoField(primary_key=True) title_name = models.TextField() url = models.TextField() priority = models.IntegerField() submenu_status = models.TextField("false") class Meta: db_table = 'base_header' class Submenu(models.Model): sub_id = models.AutoField(primary_key=True) main_id = models.IntegerField() sub_name = models.TextField() url = models.TextField() priority = models.IntegerField() mainmenu=models.ForeignKey(BaseHeader,on_delete=models.CASCADE) class meta: db_table = 'base_subheader'` and the view function: def create_blog(request): if request.method =='POST': form = CreateBlogForm(request.POST) if form.is_valid(): form.save() form = CreateBlogForm() else: form = CreateBlogForm() base = BaseHeader.objects.all() sub = Submenu.objects.all() create = CreateBlog.objects.all() category = Category.objects.all() context = { 'form' : form, 'createblog' : create, 'category' : category, … -
Translating code from Django version 1.9 to version 2.0
I am currently trying to get started with Django. But the book am using is using Django version <1.9 while the current version is >2.0 The problem am facing right now is this code: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'', include('learning_logs.urls', namespace = learning_logs')) ] I have looked around and this is what I have written from django.contrib import admin from django.urls import include, path app_name = 'learning_logs' urlpatterns = [ path('admin/', admin.site.urls), path('learning_logs/', include('learning_logs.urls', namespace = 'learning_logs')), ] but when I run the server I get the error: raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. Any help with this. Thanks in advance -
Reverse for 'staff_info_update' with arguments '('',)' not found. 1 pattern(s) tried: ['admin/staff/info/edit/(?P<pk>[0-9]+)/$']
I want to update additional information of staff class from update view of user class, where staff class has one to one relation with user class. These are my codes models class StaffInfo(models.Model): user = models.OneToOneField(User, related_name='staff_information', on_delete=models.CASCADE) views class StaffUpdateView(UpdateView): model = User form_class = StaffEditForm template_name = 'forms/staff_edit_form.html' context_object_name = 'staff' templates <a href="{% url 'staff_info_update' staff.staff_information.pk %}"> Additional Information </a> url path('admin/staff/info/edit/<int:pk>/', StaffAddInfoUpdateView.as_view(), name='staff_info_update'), -
How to use Django and angular together?
I've a django backend and angular frontend, on my local machine to use both together, I've to run both server's using ng serve and python manage.py runserver but now I'm planning to deploy it to heroku and I've no idea how will it work, also is there any official guide for using django and angular together. P.S. - I'm using django-rest-framework for making api calls from frontend to backend. -
How to decrypt django pbkdf2_sha256 algorthim password?
I need user_password plaintext using Django. I tried many ways to get plaintext in user_password. but It's not working. So, I analyzed how the Django user password is generated. it's using the make_password method in the Django core model. In this method generating the hashed code using( pbkdf2_sha256) algorthm. If any possible to decrypt the password. Example: pbkdf2_sha256$150000$O9hNDLwzBc7r$RzJPG76Vki36xEflUPKn37jYI3xRbbf6MTPrWbjFrgQ= -
How to redirect http://www.example.com to https://example.com with middleware
I got lost in deployment of my first django-application. The task I'm standing in front of is to redirect http://www to bare https://. The following is already working: https://www » bare https:// bare http:// » bare https:// But if I just type in www. I land on the standard Ubuntu/Apache site. middleware.py from django.http import HttpResponsePermanentRedirect class WwwRedirectMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): host = request.get_host().partition(':')[0] if host == "www.example.com": return HttpResponsePermanentRedirect( "https://example.com" + request.path ) else: return self.get_response(request) example.conf 1 <VirtualHost *:80> 10 ServerName example.com 11 ServerAdmin marcel@example.com 12 DocumentRoot /var/www/html 31 RewriteEngine on 32 RewriteCond %{SERVER_NAME} =example.com 33 RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] 34 </VirtualHost> example-le-ssl.conf 1 <IfModule mod_ssl.c> 2 <VirtualHost *:443> 11 ServerName example.com 12 ServerAdmin marcel@example.com 13 DocumentRoot /var/www/html 60 SSLCertificateFile /etc/letsencrypt/live/example.com-0001/fullchain.pem 61 SSLCertificateKeyFile /etc/letsencrypt/live/example.com-0001/privkey.pem 62 Include /etc/letsencrypt/options-ssl-apache.conf 63 </VirtualHost> 64 </IfModule> This is what I get with curl ~$ curl -I http://example.com HTTP/1.1 301 Moved Permanently Date: Wed, 02 Dec 2020 08:03:02 GMT Server: Apache/2.4.46 (Ubuntu) Location: https://example.com/ Content-Type: text/html; charset=iso-8859-1 ~$ curl -I http://www.example.com HTTP/1.1 200 OK Date: Wed, 02 Dec 2020 08:03:21 GMT Server: Apache/2.4.46 (Ubuntu) Last-Modified: Wed, 11 Nov 2020 22:26:44 GMT ETag: "2aa6-5b3dc4a55bcd4" Accept-Ranges: bytes Content-Length: 10918 Vary: … -
Django-Save form's Toggle Switch Values as 0's or 1's(as int) in the database
class postspage(models.Model): user=models.ForeignKey(settings.AUTH_USER_MODEL,models.CASCADE, default=1 Spot_Light_Button_Hall=models.IntegerField(blank=True, null=True) Tube_Light_Button_Hall=models.IntegerField(blank=True, null=True) Fan_Slide_Hall=models.IntegerField(blank=True, null=True) Outside_Light_Button_Hall=models.IntegerField(blank=True, null=True) Tube_Light_Button_Kitchen=models.IntegerField(blank=True, null=True) Small_Light_Button_Kitchen=models.IntegerField(blank=True, null=True) Fan_Slide_Kitchen=models.IntegerField(blank=True, null=True) Exhaust_Fan_Slide_Kitchen=models.IntegerField(blank=True, null=True) Tube_Light_Button_Bedroom=models.IntegerField(blank=True, null=True) Small_Light_Button_Bedroom=models.IntegerField(blank=True, null=True) Fan_Slide_Bedroom=models.IntegerField(blank=True, null=True) Bathroom_Light_Button_Bedroom=models.IntegerField(blank=True, null=True) Tube_Light_Button_Admin_Room=models.IntegerField(blank=True, null=True) Small_Light_Button_Admin_Room=models.IntegerField(blank=True, null=True) Fan_Slide_Admin_Room=models.IntegerField(blank=True, null=True) Bathroom_Light_Button_Admin_Room=models.IntegerField(blank=True, null=True) Socket1_Button_Admin_Room=models.IntegerField(blank=True, null=True) Socket2_Button_Admin_Room=models.IntegerField(blank=True, null=True) class postform(forms.ModelForm): class Meta: model=postspage fields=['Spot_Light_Button_Hall', 'Tube_Light_Button_Hall', 'Fan_Slide_Hall', 'Outside_Light_Button_Hall', 'Tube_Light_Button_Kitchen', 'Small_Light_Button_Kitchen', 'Fan_Slide_Kitchen', 'Exhaust_Fan_Slide_Kitchen', 'Tube_Light_Button_Bedroom', 'Small_Light_Button_Bedroom', 'Fan_Slide_Bedroom', 'Bathroom_Light_Button_Bedroom', 'Tube_Light_Button_Admin_Room', 'Small_Light_Button_Admin_Room', 'Fan_Slide_Admin_Room', 'Bathroom_Light_Button_Admin_Room', 'Socket1_Button_Admin_Room', 'Socket2_Button_Admin_Room', ] widgets = { 'Fan_Slide_Hall': RangeInput(attrs={'type':'range', 'step': '1', 'min': '0', 'max': '4'}), 'Fan_Slide_Kitchen': RangeInput(attrs={'type':'range', 'step': '1', 'min': '0', 'max': '4'}), 'Fan_Slide_Bedroom': RangeInput(attrs={'type':'range', 'step': '1', 'min': '0', 'max':'4'}),} def posts_update(request,id): instance=get_object_or_404(postspage,id) form=postform(request.POST or None,request.FILES or None,instance=instance) if(form.is_valid()): instance=form.save(commit=False) instance.save() messages.success(request,"Successfully Edited") return HttpResponseRedirect(instance.get_absolute_url()) context ={ "instance":instance, "form":form, } return render(request,'update.html',context) Update.html: <form method='GET' action='' enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} <input type="checkbox" id="xxx" value="{{ field.value }}" name="{{ field }}" onclick="calc();"/> <script> function calc() { if (document.getElementById('xxx').checked) { var s = document.getElementById(xxx); s.value = 1; } else { s.value = 0; } } </script> <!-- {% endfor %} </form> I want to display a django model form with toggle switches. If the user pushes the toggle button i.e.. true then 1 must be saved as the field value to the database else 0. The user … -
How to change variable in html template DJANGO
I wrote this variable(refactor) in my context dict. @login_required(login_url='/login') def lessont(request, id): if request.method == 'POST': form = ChapterForm(request.POST, request.FILES) if form.is_valid(): new_chapter = Chapter.objects.create(lesson_id=id) new_chapter.name = form.cleaned_data['name'] new_chapter.description = form.cleaned_data['description'] new_chapter.document = form.cleaned_data['document'] new_chapter.save() return redirect('/lessont/lesson/<int:id>') get_lessons = Lesson.objects.get(id=id) get_chapter = Chapter.objects.all().filter(lesson=id) get_group = StudentsGroup.objects.all().filter(lessons=id) form = ChapterForm() refactor = False refactor_id = 0 context = { 'get_lesson': get_lessons, 'get_chapter': get_chapter, 'get_group': get_group, 'form': form, 'refactor': refactor, <----- HERE 'refactor_id': refactor_id, } template = 'core/lessont.html' return render(request, template, context) <----- pass it here Then in my HTML template, I have an access to "refactor" variable and I want to change by clicking the button <button type="submit" name="button">Add</button> I want to make something like: <button type="submit" name="button" onClick={set "refactor" to True}>Add</button> -
Extracting data from the database table and display in view
I want to fetch the data from a table which is in database and then display it in tabular format in my webpage. Only the html column name is being shown but not the data from the database table. Can anyone please help me out with this? My codes: views.py: def display_majorheads(request): outputs = ProcessedOutputs.objects.all() be_year = 0 context = { 'processed_outputs':outputs, 'be_year':be_year, } return render(request, 'website/mhead.html', context ) mhead.html: <table class="table table-striped"> <tr> <th>MajorHead</th> <th>BeSalary</th> <th>BeGiaSalary</th> <th>BeOther</th> <th>BeTotal</th> <th>BeNextyrSalary</th> <th>BeNextyrGiaSalary</th> <th>BeNextyrOthrs</th> <th>BeNextyrTotal</th> </tr> {% for processed_outputs in outputs %} <tr> <td>{{ processed_outputs.major_cd }}</td> <td>{{ processed_outputs.be_salary }}</td> <td>{{ processed_outputs.be_gia_salary }}</td> <td>{{ processed_outputs.be_other }}</td> <td>{{ processed_outputs.be_total }}</td> <td>{{ processed_outputs.be_nextyr_salary }}</td> <td>{{ processed_outputs.be_nextyr_gia_salary }}</td> <td>{{ processed_outputs.be_nextyr_others }}</td> <td>{{ processed_outputs.be_nextyr_total }}</td> </tr> {% endfor %} </table> -
Django migrate/makemigrations does not work when postgres server is running
When the server is up and I give python manage.py makemigrations, it does nothing. It looks like it is waiting for something indefinitely. When I shutdown my pgAdmin4 server, it works fine. What could be the problem here? -
DJango model -Exception on crate :TypeError(\"save() got an unexpected keyword argument
I was building my api in DJango and rest framework . Please see my model file class StaffUser(models.Model): staff_id=models.CharField(max_length=100,null=True,) name=models.CharField(max_length=100,null=True) user=models.OneToOneField(User, on_delete=models.CASCADE,related_name='staffs') roles=models.ManyToManyField(BranchRole,related_name='holding_staffs') published_date = models.DateTimeField(blank=True, null=True) class Meta: db_table = 'staff_details' def save(self,*args,**kwargs): email =kwargs['email'] password=kwargs['password'] del kwargs['email'] del kwargs['password'] self.published_date = timezone.now() self.user=User.objects.create_user( email=email, password=password, is_staff=True, is_active=1 ) super(StaffUser,self).save(**kwargs) return self def __str__(self): return self.name When I am trying to call this save function in viewset , I am getting following exception. "Exception on crate :TypeError("save() got an unexpected keyword argument 'name'" Please help me to resolve this error. Please see my code in viewset class StaffUserViewSet(viewsets.ModelViewSet): """ This api deals all operations related with module management You will have `list`, `create`, `retrieve`, update` and `destroy` actions. Additionally we also provide an action to update status. """ serializer_class = StaffUserSerializer permission_classes = [permissions.AllowAny] queryset = StaffUser.objects.all() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.ARG={ 'staff_id':str, 'phone_number':str, 'email':str, 'name':str, 'password':str, 'address':str, 'id':int, 'roles':dict, } self.REPLACING_VALUES={ 'model_name':'content_type__model_name', 'content_type_id':'content_type__id', 'app_name':'content_type__app_label' , 'app_label':'content_type__app_label' } self.DEFAULT_PARAMETERS={ 'content_type__status__active':True } self.VIEW_PARAMETERS_LIST=[ ] self.detailed_view=False # if any user argument having another label that model relation # will replace the smame with replacement values""" self.api_model=StaffUser() def create(self, request): #over ride create method in view set status='Sucess' # set … -
Django - Pass a dictionary to template through the get_queryset function of a class based view
Is there a way to return a dictionary through the get_queryset function of a class based view in Django? I want to pass the array tickets and the string email to my template, but I am only able to pass tickets right now. Content of views.py: class UserTicketListView(ListView): model = Ticket template_name = 'ticket_system/user_tickets.html' context_object_name = 'tickets' ordering = ['-date_posted'] paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) email = User.objects.get(username=user).email return Ticket.objects.filter(author=user).order_by('-date_posted') -
Outputting two colums of dataframe into Django template using For Loop
I am trying to parse 2 columns of my dataframe(my_tweet_df) from views to Django. The dataframe is off Tweets data which I fetched from Tweepy. I hope for my output to look like this: USERNAME TWEET username1 tweet of username1 username2 tweet of username2 ..... ..... In my HTML page, code looks like this: <table class="table table-hover"> <tr> <th><h4>Username</h4></th> <th><h4>Tweet</h4></th> </tr> {% for key in my_tweet_df %} <tr> <td>{{key.author}}</td> <td>{{key.text}}</td> </tr> {% endfor %} </table> I do not know how to do so using for loop. I have tried passing dataframe: {% for key in dataframe %} with {{key.user}} and {{key.text}}. I know this approach is not correctenter code here as it is looping through range of dataframe not values of one column. I have tried converting to single columns and back to dataframe and passing like: my_tweet_df = pd.DataFrame(list(zip(my_tweet_df.user, my_tweet_df.text)), columns=['username', 'status']) But that again doesn't work because it is a 2D arary now and has a range of 2 only. Even if I try to pass them separately, I don't know how to do so using 2 for loops, like: {% for key in text %} <tr> <td>{{key}}</td> <td>{{key}}</td> </tr> {% endfor %} But in the above approach …