Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to import and use a modified npm library packages dynamically
I am using a sigmajs library for creating node based graph visualisations. But the library package had a few bugs, so I modified a few files in the source code of the library and fixed them. I have hosted my graphs on django server, and whenever I host it, the sigma package in the package.json gets loaded dynamically each time. The static library files on my machine which I had modified and fixed bugs don't get loaded. So,I get the same old package and not the modified one. How do I access the modified library package dynamically when I host the server. -
Django - passing an object to a view through template
Is there any way to pass an object to a template and through the template pass it back to another view? Is there any technique which could do that? Reason: From my django application (MYAPP) I'm using a 3rd party django application (3APP, also maintained by me). 3APP would like to use MYAPP's Object, but I've no idea how can I pass it in this construction: MYAPP's view (MV1) is calling the 3APP's view (3V1) method, which renders the template. The template has an ajax call to another 3APPS's view (3V2) function, and this one would like to use the MYAPP's Object. (During the first pass [MV1 calls 3V1 method] it's not a problem of course, it just simply passes it through an argument, but the problem is to pass it from 3V1 to 3V2, because 3V1 renders the template, and from there an ajax call calls the 3V2) Is there any way to do this? Either pass the object to the template and from there back to the 3APP's view, or any other way? Even if there's a solution, I know it won't be too djangonic... . -
How to update ManytoManyField in UserChangeForm in Django?
I want to update user info with UserChangeForm and things go pretty well except for the ManyToManyField. When I render the page I can see that all user informations are displayed in correct order of each field like user's username will be in the username field but it's blank in manytomanyfield. #model.py class Department(models.Model): name = models.CharField(max_length=100) class CustomUser(AbstractUser): username = None email = models.EmailField(_('Email Address'), unique=True) department = models.ManyToManyField(Department) # some other fields # forms.py class EditUserForm(UserChangeForm): class Meta: model = CustomUser fields = ['email', 'department', ..] widgets = {'department': forms.CheckboxSelectMultiple()} # view.py def home(request): template_name = "app/home.html" edit_form = EditUserForm(instance=request.user) if request.method == "POST": edit_form = EditUserForm(request.POST, instance=request.user) if edit_form.is_valid(): edit_form.save() return JsonResponse({'success': True}, status=200) else: return JsonResponse({'error': edit_form.errors}, status=400) return render(request, template_name, {'edit_form': edit_form}) # template <form action="{% url 'home' %}" method="POST"> <div class="row"> {{edit_form.email}} {{edit_form.first_name}} {% for department in edit_form.department %} <h6 id="checkbox">{{department.tag}} {{department.choice_label}}</h6> {% endfor %} </div> </form> it render out the checkboxes and the names but nothing is checked inside the checkboxes. It supposed to check what i have checked when registered. -
Can i get any help to build a questionnaire/mcqs application with multiple scoring categories in django
I am a begginner in django and I have been given a project to build a questionnaire or an Mcq's web application with categorical scoring system... Did anyone can provide me the link or help related to this type of application... Thank You -
how to count anohter model django?
Hope You Are Good I Have These Models: class Task(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) description = models.TextField() priority = models.CharField(max_length=124, choices=priority_options, default="Low") status = models.CharField(max_length=124, choices=status_options, default="In Progress") start_date = models.DateField() end_date = models.DateField() invite = models.ManyToManyField(User, related_name="invite", blank=True) def __str__(self): return self.name class Issue(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) task = models.ForeignKey(Task,on_delete=models.CASCADE) issue = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.task.name Now i Have used this Command To Count Tasks: Task.objects.filter(user=request.user,status="Completed").count() now I want to find the task which created by this user and status is completed issues how can i do that? -
python package that connect social accounts per object - django
The default behaviour of python-social-auth and other social auth package is that it bind user with a social accounts, but how can u achieve social auth per object. Here is my case. I am userX, in my django app i have a model named Company, userX managed multiple companies, and each company have their own twitter and other social accounts. So userX will add each company twitter account but after verification from twitter. Is there a way i can modify python-social-auth or all-auth package to achieve this or any other python package you can recommend. I don't want to put CharField and let user fill in the social url manually. -
In django, is it possible to have a foreign key defined to some superclass, but having returned the subclass when queried?
Assuming I have the following models: class SomeSuperClass(models.Model): ... class SomeSubClassA(SomeSuperClass) ... class SomeSubClassB(SomeSuperClass) ... class SomeConnector(models.Model): reference = models.ForeignKey(SomeSuperClass, on_delete=models.CASCADE) ... Now what I would want to have is somehow when iterating over objects of SomeConnector I always want to have right away objects of the respective subclasses, not of the superclasses. E.g. for sc in SomeConnector.objects.all(): # somehow get the correct subclass of this `reference` field here, # assuming it to be callable under sc.reference_correct_subclass: print(sc.reference_correct_subclass.__class__.__name__) could produce for example: 'SomeSubClassA' 'SomeSubClassB' 'SomeSubClassA' 'SomeSubClassA' But never should an object of the superclass be used. I know of django-model-utils and I could do something similiar by querying directly on the superclass, like this: SomeSuperClass.objects_inheritance.select_subclasses() where objects_inheritance is the InheritanceManager attached to SomeSuperClass. However I could not figure out yet how to reproduce this when the superclass is used as foreign key in another class which I want to use for querying. -
python manage.py runserver is not working but only pops up a python interpreter window
please I'm working on a django project and after creating the conda environment for the project using the anaconada shell and activated it. I opened the project up in pycharm and tried to run the server using (itachi) C:\Users\Abdul\Desktop\github\codedaddies_list>python manage.py runserver 'itachi' is my environment name but nothing happens....it shows no error codes, it only pops up the window with message Python 3.8.5 (default, Sep 3 2020, 21:29:08) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32 Type "help", "copyright", "credits" or "license" for more information. this is the image of the window the python pop up window please I've been stuck for days, if anyone at all can provide a solution i will be grateful thanks this is the image of my pycharm terminal where a ran the code my pycharm terminal -
How to validate one field by another in Django models?
On saving data to the model I want to validate one field by another (they are in the same model). Here is my model: class String(models.Model): key = models.CharField(max_length=60, unique=True) name = models.CharField(max_length=60) value = models.CharField(max_length=230) maxSize = models.PositiveSmallIntegerField() I want to validate value field by max size taken from field maxSize and return specific error to user when validation is failed. How to do that? -
DJANGO-increment global variable in function by every get. Request
the first code is the file that named tes.py and in this file is a function that named Program. for every url.request(second code) it proceses many things and will save to my db table. at this first code I defined id as a "increment count" global varible . I want for every get.Request in urls.py, the value of id will update by this relation: id= id+1 But its value does not change. And I dont know why even though I defined id as Global variable ! HELP PLEASE. import sqlite3 from .models import OrdersStudent ,OrdersStudent1 ,EditStudentDatasheet ,OrdersDouble , Nodecode from math import sin, cos, sqrt, atan2, radians from django.http import HttpResponse from django.shortcuts import render from django_globals import globals global j def Program(request): id = request.session.get('id') if not id: id = 1 request.session['id'] = id R = 6378.0 zz = 0 conn = sqlite3.connect("db.sqlite3") j = 0 sql = 'DELETE FROM orders_Double' cur = conn.cursor() cur.execute(sql) conn.commit() EditStudentDatasheet.objects.filter(UserId=41907).delete() EditStudentDatasheet.objects.filter(UserId=41787).delete() Nodecode.objects.filter(studentidof=41907).delete() Nodecode.objects.filter(studentidof=41787).delete() NodecodeNumberOfSubscriptions = list(Nodecode.objects.all()) Datasheet = list(EditStudentDatasheet.objects.all()) orders_student = {} orders_student={}.copy() x = Datasheet[0].Lat Dictionary1 = {} MinOfPair = 50 capacity = 3 while (MinOfPair <= 500): ThisCheck = True DoubleMergePairLAST={} DoubleMergePair = {} DoublePair={} DoubleMergePair = {} ObjectDatasheet = … -
TypeError: save() missing 1 required positional argument: 'self' : DjangoRestframework
I'm getting an error, save() missing 1 required positional argument: 'self' . I have no idea where I made mistake, it would be great if anybody could figure out the mistake, they would be much appreciated. serializers.py UserOtherInfo_obj = User( device_token = device_token, device_type = device_type, phone_number = phone_number, country_code = country_code, login_type = login_type ) UserOtherInfo_temp = User.save() temp_user1 = User.objects.filter(user=temp_user) print('temp_user1',temp_user1) UserOtherObj = temp_user1.first() -
Throttle a detail view in django rest framework
I have a custom throttle: from rest_framework.throttling import UserRateThrottle class OncePerDayUserThrottle(UserRateThrottle): rate = '1/day' I use this throttle in a class api view as such: class PostHitCount(APIView): throttle_classes = [OncePerDayUserThrottle] def post(self, request, hitcount_pk, format=None): # my post method The url corresponding to this view is path('add-hitcount/<int:hitcount_pk>/', PostHitCount.as_view()) If i access this view for the first time via url add-count/1/, i am permitted. If i later post to the same url, i am not permitted (which is ok!). Now if i post to the url add-count/2/, the request is rejected since the user already accessed that view! How can i permit requests with another detail url? Also, is it possible to set the throttle rate to say 1/year or even 1/lifetime ? How ? -
Djangorestframwork api on production patch method not more and return rest
I am create in an api using django as backend and react as front-end using docker. in local docker all things right done ! i have tree container -django and gunicorn -pstgres -nginx django == 3.1.1 python 3.8.1 but in in vps production environment PATCH method return this error PATCH http://x.x.x.x/api/v1/product_service/product/ewrewr HTTP/1.0 400 Bad Request Date: Wed, 23 Sep 2020 10:23:41 GMT Content-Type: text/html Content-Length: 5 X-Cache: MISS from jet_appliance X-Loop-Control: 255.255.255.255 B1267694C1EE70D52467A8BA99A4D50F Connection: close reset -
Using Django "sites" framework to handle subdomains?
I am developing a language-based web application using Django. I would like to separate content using language subdomains (similar to Wikipedia, Quora, and other multilingual websites). For instance, if my website were example.com, I would like to have en.example.com for the English version of my website, es.example.com for the Spanish version of my website, and so on and so forth. I came across different Django third-party libraries that could help with subdomains but I was considering using the "sites" framework from Django itself. However, its documentation is not very explicit about subdomains but rather just talks about "websites" and it's not clear whether the framework would be suitable for my purpose. So, my question is: is the Django "sites" framework a good option for handling subdomain in a fashion similar to the one described above? -
Django FileField to upload html and send it via Email
I have a problem, I got a model with a FileField to upload an HTML template. I upload it to the MEDIA folder. I'm trying to get that template in python and send an email with it. But I have a lot of problems with the encode.  , € ... These are some of the characters i'm getting. I tried a lot of things, my actual code: template2 = default_storage.open(grupo.email.correo.path, 'r') template = template2.read() template = unidecode(template) template = Template(template) html = template.render(Context({})) email = EmailMessage( subject, html, to=[to_email] ) email.content_subtype = 'HTML' email.send(fail_silently=False) The variable grupo.email.correo is the FileField. The result: As you see, in the right of each number should be €. I tried a lot of combinations, and I get a lot of other characters, but I can't get a good decoded string, anyone knows more about this? -
Django app does not work when DEBUG_VALUE=False and using django_heroku
I tried deploying my Django website using heroku and used a library called Django-Heroku. When setting my settings.py for deployment, it returns Server Error (500) when setting DEBUG_VALUE = False, importing import django_heroku and writing django_heroku.settings(locals()) at the last line of my settings.py file. How can I check the settings set by django_heroku that disables disables my django website for production? -
modelformset not working when applying style, How to show image inside formset
I'm trying to define a modelformset_factory on the model"Offer" When I'm form fields are not wrapped inside a div they are working fine (create and delete forms). As soon as I wrap them inside a div the functionality dosen't work. I also want to display the image inside modelformset_factory Here is my view function and html def offers(request): OfferFormSet = modelformset_factory(Offer, fields=('name', 'url', 'image', 'active'), can_delete=True) formset = OfferFormSet() if request.method == 'POST': formset = OfferFormSet(request.POST, request.FILES) if formset.is_valid(): instances = formset.save(commit=False) for instance in instances: instance.save() for instance in formset.deleted_objects: instance.delete() return redirect('.') formset = OfferFormSet() context = {'formset': formset} return render(request, 'offers.html', context) The Html is here: {% extends 'base.html' %} {% block content %} <style media="screen"> .form_div { padding: 20px 40px; margin: 20px; display: flex; flex-direction:row; flex-grow: 1; align-items: center; justify-content: space-between; background: #eee; border-radius: 2%; box-shadow: 0 0 10px 10px rgba(0, 0, 0, 0.1); } .form_grp{ display: flex; flex-direction: column; } </style> <div class="container"> <div class="formset"> <form method="post" enctype="multipart/form-data" class="forms"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <div class="form_div"> <div class="form_grp"> <label for="">{{ form.name.label_tag }}</label> {{ form.name }} </div> <div class="form_grp"> <label for="">{{ form.url.label_tag }}</label> {{ form.url }} </div> <div class="form_grp"> … -
Add new subclass to CharField
I want to add extra subclass to my CharField. It would look like: first_row = models.CharField('General', extra_subclass="data", help_text='q122', max_length=30, blank=True, null=False) The code I tried and failed: class extra_subclass(models.CharField): def __init__(self, *args, **kwargs): self.kwargs['extra_subclass'] super(extra_subclass, self).__init__(*args, **kwargs) -
How can I add a magnifying glass to my website?
I'm a junior developer in charge of developing a website for elderly people using Django. My idea was to add a button that when you click it it generates a magnifying glass that biggens the words. Unfortunately I couldn't find any clear code related to this. Could anyone give me some clues about how to do this? It would be very much appreciated. -
Unable to update model data by using html based form
I am trying to update my pre existing model(ShiftChange) and in model based form i have used CHOICES and for update i thought to use html based form because i wanted to display content to end user(Is there any way to do by using django model based form?).When I am moving the cursor over the update button I can see it is showing the correct url but when clicking for submit after changing a few fields from dropdown option it is not redirecting. 1.model.py from django.db import models SHIFT_CHOICES = ( ('9.00-6.00','9.0-6.0'), ('6.30-3.30', '6.30-3.30'), ('12.30-3.30','12.30-3.30'), VENDOR_CHOICES = ( ('genesys','Genesys'), ('rmsi', 'RMSI'), ('tcs','TCS'), ('Cognizant', 'Cognizant'), ('CTS', 'CTS.') ) class ShiftChange(models.Model): ldap_id = models.CharField(max_length=64) Vendor_Company = models.CharField(max_length=64,choices=VENDOR_CHOICES,default='genesys') EmailID = models.EmailField(max_length=64,unique=True) Shift_timing = models.CharField(max_length=64,choices=SHIFT_CHOICES,default='General_Shift') Reason = models.TextField(max_length=256) # updated_time = models.DateTimeField(auto_now=True) 2.update.html <p>User information Update Form</p> <!-- <h5><span3>Note:</span3> For timing please use this format e.g 1.Morning Shift = <span2>6.30-3.30</span2> <br>2.Second Shift= <span1>3.30-12.30</span1><br>3.general Shift =<span4>9.00-6.00</span4></h5>--> <form method="post" class="post-form"> <!-- {{form.as_p}} #i'm not passing any form from view--> {%csrf_token%} <!-- #Now writing html form here instead of model based form because we want to show content also:)--> <!-- here name should be same variable as per the model we have defined.--> Ldap ID: <input type="text" … -
Django Filter taking list of foreign key model
I have this two model Route and Project and a relation models: class ProjectRoute(models.Model): #Fk project = models.ForeignKey(Project, null = False, on_delete = CASCADE) route = models.ForeignKey(Route, null = False, on_delete = CASCADE) Having project ID I want to retrieve a list of routes. relations = ProjectRoute.objects.filter(project__id = project_id) With this filter, I have a list of ProjectRoute. What I whant is the queryset of only route. Something like this (that doesn't work): routes = ProjectRoute.objects.filter(project__id = project_id).value_list(route) Is it possible? -
Is there is any way to use jinja inside the django flatpage?
{% load social_tags %} {% social_icon as social %} {% for i in social %} {{ i.title }} {% endfor %} my flatpage content which I write from django-admin the same code is working fine in simple django templete render page -
Passing data from django model into a list
I'm trying to pass data from a db record into a list. Here's my code: (it's inside my view) dates_queryset = Profile.objects.all().filter(user=request.user) dates = [] weights = [] num = 1 for qr in dates_queryset: dates.append(qr.date) weights.append(qr.weight) num += 1 -
Hey guys please i am getting SMTP error after running my code
I am trying to send an email to my second email account using gmails SMTP but i have been seeing errors. This is the error i keep getting SMTPConnectError at /register/ (451, b'Request action aborted on MFE proxy, SMTP server is not available.') This is in my settings.py file EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'my-gmail@gmail.com' EMAIL_HOST_PASSWORD = '*****' EMAIL_PORT = 587 EMAIL_USE_TLS = True This is my views.py file email = EmailMessage("Subject Here", "Testing hello world", "", ["therealemaluser96@gmail.com"] ) -
Django log configuration ignored despite config
I am trying to set up logging in my Django app. My logging configuration is defined in the settings.py: LOGGING_CONFIG = None LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'test': { 'format': '%(asctime)s %(levelname)-8s %(message)s' } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'test' } }, 'loggers': { '': { 'handlers': ['console'], 'level': 'DEBUG' } } } import logging.config logging.config.dictConfig(LOGGING) Then in my code: import logging ... logger = logging.getLogger(__name__) logger.info("info") logger.debug("debug") logger.warn("warn") logger.critical("critical") logger.error("error") But I only get: warn critical error The log level and the formatter dont work. Why is my configuration not taken into account ?