Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django, Changing field values in model before saving to database
class PlayerList(models.Model): name = models.CharField(max_length=300) position = models.CharField(max_length=200) h_code = models.ForeignKey(HList, related_name="h_code", on_delete=models.CASCADE) d_code = models.CharField(primary_key=True, max_length = 200, editable=False) Serializers.py class PlayerSerializer(serializers.ModelSerializer): class Meta: fields = ["name", "position", "h_code", "d_code"] model = PlayerList view.py class PostPlayer(generics.ListCreateAPIView): queryset = PlayerList.objects.all().order_by('-d_code') serializer_class = PlayerListSerializer def get(self, request, *args, **kwargs): d_code = request.data.get('h_code') + 'test' print(d_code) print(d_code) : h000001test When entering a value through api, I want to implement that the entered value is changed to another value in view.py and saved in the db. I want to save d_code processed by def get in db. I don't know what to do. Can you please let me know? There is no answer, so I will post again. -
student management system add_students_save problem in Django python
def add_student_save(request): if request.method != 'POST': return HttpResponse("Method Not Allowed") else: first_name = request.POST.get("first_name") last_name = request.POST.get("last_name") username = request.POST.get("username") email = request.POST.get("email") password = request.POST.get("password") address = request.POST.get("address") session_start = request.POST.get("session_start") session_end = request.POST.get("session_end") course_id = request.POST.get("course") sex = request.POST.get("sex") # try: user = CustomUser.objects.create_user(username=username, password=password, email=email, last_name=last_name, first_name=first_name, user_type=3) user.students.address = address course_obj = Courses.objects.get(id=course_id) user.students.course_id = course_obj user.students.session_start_year = session_start user.students.session_end_year = session_end user.students.gender = sex user.students.profile_pic = "" user.save() # messages.success(request, "Successfully Added Student") # return HttpResponseRedirect("/add_student") # except: # messages.error(request, "Failed to Add Student") # return HttpResponseRedirect("/add_student") enter image description here -
How to order a list in django with name?
Here I tried like this but it is not giving me the correct ordering. from operator import attrgetter ls = [obj.attribute for obj in qs] ordered_ls = sorted(ls, key=attrgetter('name')) -
Python Django issue with makemigrations
I'm new at Django but recently I've been having some errors when entering the python manage.py makemigrations command. I tried to understand my mistake by reading the following log but I really can't: Migrations for 'main': main\migrations\0004_main_about.py - Add field about to main 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:\Users\Nyro\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\Nyro\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Nyro\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\management\base.py", line 341, in run_from_argv connections.close_all() File "C:\Users\Nyro\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\db\utils.py", line 230, in close_all connection.close() File "C:\Users\Nyro\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\Nyro\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\db\backends\sqlite3\base.py", line 261, in close if not self.is_in_memory_db(): File "C:\Users\Nyro\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\db\backends\sqlite3\base.py", line 380, in is_in_memory_db return self.creation.is_in_memory_db(self.settings_dict['NAME']) File "C:\Users\Nyro\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\db\backends\sqlite3\creation.py", line 12, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'WindowsPath' is not iterable -
do i will lose data in database if i delete migration files in django?
I have Django Project and I want to add some table in my database but I'm not able to add it because I have some Problem in Migrations files , Do I will lose my data in database if I removed all migrations files -
Unable to use django template using extends from another app
My Django project templating structure is AuthApp/ login.html MainApp/ base.html I want to use base.html file in login.html file, using below code. {% extends 'MainApp/base.html' %} {% block content %} {% endblock %} But its not inheriting the base template. Please suggest. -
Apexchart graph updateseries function not working?
Working on Apexcharts but my Updateseries in AJAX Call not working kindly help!!! Whenever I am inserting dates in datepicker in front.Data is coming from Backend as I can see in my console but Update Series/Graph is not updating in front end. Working in Django Framework. Please share as many examples of UpdateSeries in Apex Charts as posible -
Update single <td> value in the table row using ajax in django
I am trying to Block/Unblock the user without refreshing the page. If the status=1, it will show Block option, and if the status=0 it will show Unblock option After calling the function, the status will change either 0 or 1 in views.py The function is working fine but it is showing after refreshing the page How to display that value without refreshing the page <table id='usersTable' class="table table-bordered"> <thead> <tr> <th>S.No.</th> <th>Name</th> <th>Email</th> <th>Block/Unblock</th> </tr> </thead> <tbody> {% for userid, name, email, status in comb_lis %} <tr id='usr-{{name}}'> <input type="hidden" id="{{userid}}" name="{{userid}}" value="{{userid}}"> <input type="hidden" id="{{name}}" name="{{name}}" value="{{name}}"> <td>{{forloop.counter}}</td> <td>{{name}}</td> <td>{{email}}</td> <td> <a href="#" onclick="restrictUser(document.getElementById('{{userid}}').value, document.getElementById('{{name}}').value)"> {% if status == "1" %} Block {% else %} Unblock {% endif %} </a></td> </tr> {% endfor %} </tbody> and this is the ajax function function restrictUser(userid, name) { $.ajax({ url: '/restrict-user-ajax/'+userid, dataType: 'json', success: function (data) { if (data.status) { alert("User Blocked!"); } } }); } Any help is appreciated -
Troubles when I pass get_connection to EmailMultiAlternatives (django-post_office)
I need to make the connection dynamic for example: settings.py # EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_BACKEND = 'post_office.EmailBackend' # EMAIL_HOST = 'smtp.office365.com' # EMAIL_USE_TLS = True # EMAIL_PORT = 587 # EMAIL_HOST_USER = '123s@123.sg' # EMAIL_HOST_PASSWORD = '*********' views.py from django.core.mail import EmailMultiAlternatives, get_connection def email_template_participants(): connection = get_connection(host=arg.email_backend.email_host, use_tls=arg.email_backend.use_tls, port=arg.email_backend.port, username=email_back, password=arg.host_password) ....... email_message = EmailMultiAlternatives(subject, body, from_email, to_email, connection=connection) template = get_template('email_participants.html', using='post_office') html = template.render(context_html) email_message.attach_alternative(html, 'text/html') email_message.attach_file(attach_file(id) template.attach_related(email_message) email_message.send() running this code : emails fail. On status: ConnectionRefusedError ( Unable to establish a connection as the target computer expressly denied that connection ) If I uncomment EMAIL_HOST, EMAIL_USE_TLS, etc the connection is denied, because they not always match, only works when they match, 1 in 15. Otherwise. if I only change EMAIL_BACKEND to 'django.core.mail.backends.smtp.EmailBackend'. It works Perfect. What can I do ???? I need all Benefits from post_office, (crons, mails listed, inlined images, etc ) -
Operators can be used to access the fields in the object by Django ORM?
Which of the following Operators can be used to access the fields in the object by Django ORM? (.) Operator (') Operator (,) Operator Both (.) and (') Operator -
! Push rejected, failed to compile Python app. -Heroku
I am trying to depoly my website but I am getting this error I am depolying it with github and the site I am using is called Heroku I am not sure why I am getting this error but I have already done all the steps I need to depoly the My runtime.txt My requirements.txt my Procfile idk if it has annything to do with my apps but here. -
Extending a column in the user table in django is not creating a entry in table
I have extended the Django user table with a boolean variable. class UserLogin(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) isFresher = models.BooleanField() I have made changes in the admin inline. class LoginInline(admin.StackedInline): model = UserLogin can_delete = False verbose_name_plural = 'loginTable' class UserAdmin(BaseUserAdmin): inlines = (LoginInline,) I have got the flag in the admin table. When I add a user to the user table I can see the flag. If I check the flag then I can see an entry True with user_id in the UserLogin table. If the flag is not checked then I can not see an entry in the table? How to make this False entry into the table? -
Stylizing ManyToMany Form (Django)
I have a question regarding the stylizing of a ManyToMany field form submission. Currently, I am using the Checkbox widget. The problem is this field will eventually have 80+ options. I was curious if there are any better widgets for this case? If not, how could I go about implementing a search and select for this field on the front end? Thank you! P.S: I do understand the second question could involve a lot of code, so please feel free to provide an approach to the problem instead. class CourseUpdateForm(forms.ModelForm): activesubjects = forms.ModelMultipleChoiceField( queryset=Subject.objects.all(), widget=forms.CheckboxSelectMultiple, required=True) class Meta: model = Profile fields = ['activesubjects'] -
How do you modify the Django Admin UI?
Whenever I see a tutorial customizing the Admin interface this is always the way they customize it like changing the header text and image, changing the color, etc. Is there a better way of making it more like this implementing the Vue Admin Dashboard to the Django Admin? and also, in this website https://djangopackages.org/grids/g/admin-interface/ is this the Only Admin UI you can use? -
Django rate limiting outgoing requests
I'm new to Django and Python, so my understanding of the fundamentals might be wrong. I'm building an app with Django + Nginx + Gunicorn. For every client request, the app needs to call another service to retrieve information. The information is then used to serve the client. Currently, the app does this by: Establishing a TCP connection to the service Exchange data Closes the connection When the request load is high, this connection overhead becomes an issue. On top of that, I should be worried about the number of sockets being created. I think creating a connection pool to rate limit the number of outgoing requests would be a good idea. However, I don't really know how get started...I have a couple of questions: How can I create a ConnectionPool object in Django that is accessible by all of my Django app? Assuming that I'm able to create a connection pool in Django, and I have two Gunicorn workers, will both workers maintain their own separate connection pools? -
django, Changing field values in model before saving to database
models.py class PlayerList(models.Model): name = models.CharField(max_length=300) position = models.CharField(max_length=200) h_code = models.ForeignKey(HList, related_name="h_code", on_delete=models.CASCADE) d_code = models.CharField(primary_key=True, max_length = 200, editable=False) Serializers.py class PlayerSerializer(serializers.ModelSerializer): class Meta: fields = ["name", "position", "h_code", "d_code"] model = PlayerList view.py class PostPlayer(generics.ListCreateAPIView): queryset = PlayerList.objects.all().order_by('-d_code') serializer_class = PlayerListSerializer def get(self, request, *args, **kwargs): d_code = request.data.get('h_code') + 'test' print(d_code) print(d_code) : h000001test When entering a value through api, I want to implement that the entered value is changed to another value in view.py and saved in the db. I want to save d_code processed by def get in db. I don't know what to do. Can you please let me know? -
In django how to GROUP_BY raw and bellow my question
How to gourp_by() column based on RID. My Actual output HERE IMAGE Whatever values are displayed in the Months Names like [Jan, Feb,...., Des], all the values come from the one table column. I want to display all values in one particular column like the below image. Expected output HERE IMAGE Models.py Here my registration table(primary key table). class Registration(models.Model): Registration_ID = models.IntegerField(auto_created=True,primary_key=True) Surname = models.CharField(max_length=20) FirstName = models.CharField(max_length=20) LastName = models.CharField(max_length=20) MobileNumber = models.IntegerField() Email = models.CharField(max_length=50) Password = models.CharField(max_length=30) Gender = models.CharField(max_length=10) FamilyMembers = models.IntegerField() PlotNumber = models.IntegerField() PlotType = models.CharField(max_length=20) Partition = models.CharField(max_length=10) FlatNumber = models.CharField(max_length=10) Rent = models.CharField(max_length=10) RentalFloor = models.CharField(max_length=10) Is_Active = models.BooleanField(default=0) Is_Admin = models.BooleanField(default=0) Owner_Rent = models.IntegerField(null=True,default=0) Rental_Rent = models.IntegerField(null=True,default=0) Created_Date = models.DateTimeField(auto_now_add=True) Updated_Date = models.DateTimeField(auto_now=True) class Meta: db_table = 'Registration' Here my maintenance table(foreign key table). class Maintenance(models.Model): Maintenance_ID = models.IntegerField(auto_created=True,primary_key=True) Registration_ID = models.ForeignKey(Registration, on_delete=models.CASCADE) ReceiptNumber = models.IntegerField(null=True) ReceiptDate = models.DateField(null=True) FromDate = models.DateField() ToDate = models.DateField() FeeType = models.CharField(max_length=30) PaymentMode = models.CharField(max_length=20) Remark = models.CharField(max_length=20, null=True) BankName = models.CharField(max_length=30,null=True) ChequeNumber = models.CharField(max_length=30,null=True) ChequeDate = models.DateField(null=True) Money = models.IntegerField() Created_Date = models.DateTimeField(auto_now_add=True) Updated_Date = models.DateTimeField(auto_now=True) class Meta: db_table = 'Maintenance' Views.py paginator = Maintenance.objects.all().order_by('Registration_ID_id') page = request.GET.get('page', 1) Qry_All_Maintenance_List = Paginator(paginator, 25) … -
Django --> python manage.py runserver
I had previous django project named 'bike_project'. And i had two settings module for development and production inside settings folder of bike_project. During that project i had set DJANGO_SETTINGS_MODULE = bike_project.settings.development in command prompt. But now when i create new django project (seller bike), the project is created. But when i run python manage.py "command", I get following error. D:\seller_bike>python manage.py runserver Traceback (most recent call last): File "C:\Users\offic\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\offic\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "C:\Users\offic\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\offic\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "C:\Users\offic\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\conf\__init__.py", line 76, in __getattr__ self._setup(name) File "C:\Users\offic\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\conf\__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "C:\Users\offic\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\conf\__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\offic\AppData\Local\Programs\Python\Python38-32\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 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line … -
How do I create a parent user and a child user in Django?
We are building a free education app in Django. I have noticed that if I am logged in as a "superuser" I am able to "switch user" inside the admin app to any of our staff. This education app will have "Parents" who can "Add Child" users. The parents should be able to "switch user" to any of their children. How do we implement this feature on our main app instead of just within the admin. -
Python manage.py runserver is throwing error after Ubuntu upgrade to 20.0
I am getting this error in all the Django projects on my system. I've updated from Ubuntu 18.04 to 20.0 (Focal Fossa). Since then I am getting these errors. Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 10, in main from django.core.management import execute_from_command_line File "/home/thebitshoes/Desktop/Environments/namllpV1_env/lib/python3.6/site-packages/django/__init__.py", line 1, in <module> from django.utils.version import get_version File "/home/thebitshoes/Desktop/Environments/namllpV1_env/lib/python3.6/site-packages/django/utils/version.py", line 6, in <module> from distutils.version import LooseVersion File "/home/thebitshoes/Desktop/Environments/namllpV1_env/lib/python3.6/distutils/__init__.py", line 17, in <module> real_distutils = imp.load_module("_virtualenv_distutils", None, distutils_path, ('', '', imp.PKG_DIRECTORY)) File "/home/thebitshoes/Desktop/Environments/namllpV1_env/lib/python3.6/imp.py", line 245, in load_module return load_package(name, filename) File "/home/thebitshoes/Desktop/Environments/namllpV1_env/lib/python3.6/imp.py", line 217, in load_package return _load(spec) File "<frozen importlib._bootstrap>", line 683, in _load AttributeError: 'NoneType' object has no attribute 'name' -
How to get the uploaded (generated) file name in django
models.py class client_users(AbstractBaseUser): first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) email = models.EmailField(_('email address'), unique=True) password = models.CharField(max_length=150) birthday = models.DateField() phone = models.CharField(max_length=15) profile_image = models.ImageField( upload_to='images/', default="noimage.png") USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email views.py def profile(request): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): try: form.save() except: pass print(client_users.profile_image.field.pre_save) return HttpResponseRedirect('/profile') else: form = UploadFileForm() return render(request, 'profile.html', {'form': form}) This is a picture of the saved files with a code generated by django, because he found an image with the same name Since django generated the code after the name of the picture, i want to get the full file name after the upload so i can update my database, request.FILES['profile_image'] doesn't return the generated value, it returns the name of the file on the upload. Any help, please ? -
Accessing cookie from another sub-domain within my domain
I have two django applications that are deployed at two different sub-domains, for example: data.mysite.com i.mysite.com Both sites use the same django authentication framework and such, setting a cookie called sessionid. I can read the cookie from the current site using: def my_view(request): # suppose this view is within the i.mysite.com application i_session_id = request.COOKIES['sessionid'] data_session_id = ? # how to get this? But then how could I grab the cookies from the -
Django modelform custom widget is_multipart not working
In my modelform, I have used a custom widget. The problem is for some reason the is_multipart returns False, and so I cannot upload the picture class ProjectSetupForm(ModelForm): class Meta: model = Project fields = ['name', 'logo','picture'] widgets = { 'picture': PictureWidget, 'logo': PictureWidget, } def __init__(self, *args, **kwargs): self.fields['logo'].widget.attrs['class'] = 'file_upload blocked' self.fields['picture'].widget.attrs['class'] = 'file_upload blocked' class PictureWidget(forms.widgets.Widget): def render(self, name, value, attrs=None, **kwargs): if value: html = Template("""<img src="$media$link" height=100px width=auto/> <input type="file" name="$name" class=" form-control" style="width: 100%; height: auto" />""") return mark_safe(html.substitute(media=settings.MEDIA_URL, link=value, name=name)) else: html = Template("""<input type="file" name="$name" class=" form-control" style="width: 100%; height: auto" />""") return mark_safe(html.substitute(name=name)) # views.py: class AddProject(View): template_name = 'project.html' model = Project def get(self, request, *args, **kwargs): ... context['form'] = ProjectSetupForm() ... return render(request, self.template_name, context) def post(self, request, *args, **kwargs): ... project_form = ProjectSetupForm(request.POST if any(request.POST) else None, request.FILES or None) if project_form.is_valid() and address_form.is_valid(): ... address_instance = address_form.save() project_instance = project_form.save(commit = False) project_instance.address = address_instance project_instance.save() else: errors = {} if project_form.errors: project_form_errors = project_form.errors errors.update( {'project_form': project_form_errors} ) if address_form.errors: address_form_errors = address_form.errors errors.update( {'address_form': address_form_errors} ) context = {} context['errors'] = errors return render(request, self.template_name, context) # In template: {% if form.is_multipart %} <form action="" … -
Changing a Curl method to a django/DRF view method
I am trying to implement an API but it has only options for cURL, PHP and nodejs, but i feel its possible for me to use python to make the request as the endpoint has been given This is the cURL code, I am hoping to get a way to do it in Django Rest Framework or Django as i am using it to develop and endpoint. curl --location --request GET 'https://api.flutterwave.com/v3/transactions/123456/verify' \ --header 'Content-Type: application/json' \ --header 'Authorization: Bearer {{SECRET_KEY}}' Thanks in advance. -
Django: After Successful Payment Via PayPal how to redirect user to order completed page
I am setting a PayPal payment for my E-commerce project and everything is working fine except that after the payment is executed and the PayPal windows is closed, the website page remains open and the items remain in the cart. I have set the stripe payment to redirect to a page called "order completed" with some order reference code, which I am trying to implement to PayPal payment option. Here is the views.html: def payment_complete(request): body = json.loads(request.body) order = Order.objects.get( user=request.user, ordered=False, id=body['orderID']) payment = Payment( user=request.user, stripe_charge_id=body['payID'], amount=order.grand_total() ) payment.save() # assign the payment to order order.payment = payment order.ordered = True order.ref_code = create_ref_code() order.save() messages.success(request, "Your Order was Successful ! ") # Email when order is made template = render_to_string("payment_confirmation_email.html", {'first_name': request.user.first_name, 'last_name': request.user.last_name, 'order': order}) msg = EmailMessage('Thanks for Purchasing', template, settings.EMAIL_HOST_USER, [request.user.email]) msg.content_subtype = "html" # Main content is now text/html msg.fail_silently = False msg.send() # End of the email send return render(request, "order_completed.html", {'order': order}) class PaymentView(View): def get(self, *args, **kwargs): # order order = Order.objects.get(user=self.request.user, ordered=False) if order.billing_address: context = { 'order': order, 'DISPLAY_COUPON_FORM': False } return render(self.request, "payment.html", context) else: messages.warning( self.request, "You have not added a billing address") return redirect("core:checkout") …