Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to find the percentage of employee scores using django
I have a table called Task. It captures task, task score and the employee it is assigned to. I want to calculate the performance of the employee using his total task scores for the week (duration should be dynamic. preferably input field) and the total scores allocated. I am thinking of aggregating the actual scores then dividing buy total score then multiply by 100 to get the percentage. My major challenge is where to perform this calculation. Should I create a model called performance and use a function? Or if can anyone show me how to go about this? Here is the model; class Task(models.Model): scores = models.IntegerField(null=True, blank=True) def __str__(self): return self.name Here is the formula I want to use. Performance(%) = actual score / total score * 100. Total score should be input field. -
How to fix error: 'str' objects is not maaping
<form action={% url "likeblog" article.pk %} method="post"> {% csrf_token %} <button style="height: 30px" type="submit" name="like" id="btnLike" value="{{ article.id }}"> <i class="far fa-thumbs-up"></i> </button> </form> and my urls: urlpatterns = [ path('like/<int:pk>', views.LikeBlog, name='likeblog'), ] but django error: 'str' object is not a mapping when the i using httpReponseRederit or redict django error str is not mapping! help me please -
Django model query - how to join string list with F expression
I have a model with array field and now a new string field required to hold content from array field with string format. class MyModel(models.Model): array_field = ArrayField( models.CharField( max_length=255, blank=True, null=True ), blank=True, null=True ) text_field = models.TextField(null=True, blank=True) I intend to use F() with update() like below MyModel.objects.filter(array_field__isnull=False).update(text_field="; ".join(F("array_field"))) But it gives me below error TypeError: can only join an iterable Does F() work with join()? -
Django (DRF) trailing slash issue
I have problem with PUT request in DRF, and it is basically about the url not having trailing slash, but even when i add a trailing slash to the required URL, it gives error (page not found 404) on the backend side, thus the data is not fetched in the frontend side anyway if someone has any solution, please tell here is my code: urls.py from django.contrib import admin from django.urls import path,include from rest_framework import routers from main import views router = routers.DefaultRouter() #Creating a router object which i assume is the web API root router.register(r'todos/', views.TodoView, 'todo') #mapping views URL'S to the router (web api root) urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)) #including all views urls/route in the same url path (api/) ] if frontend side also matters: app.js handleUpdate(item){ if(item.id){ axios.put(`http://localhost:8000/api/todos/${item.id}`) return } } -
Django Radio Buttons:
I have this following HTML Page: <p> Defect? <input type="radio" name="radAnswer" id="defect-yes"/> <label for="defect-yes">Yes</label> <input type="radio" name="radAnswer" id="defect-no"/> <label for="defect-no">No</label> </p> <p> Action Correctly Captured? <input type="radio" name="radAnswer2" id="defect-yes"/> <label for="defect-yes">Yes</label> <input type="radio" name="radAnswer2" id="defect-no"/> <label for="defect-no">No</label> </p> That displays this: And I have a field called Audit Outcome, that contains yes no or blanks as an input, and I wanted to know how to display radio buttons accordingly. I was thinking of something like : {% block content %} <form method="POST" action=""> {% csrf_token %} {% for item in items %} {% if item.Audit_outcome = "Yes" %} <input type="radio" name="radAnswer" id="defect-yes"/> <label for="defect-yes">Yes</label> {% else %} <input type="radio" name="radAnswer2" id="defect-no"/> <label for="defect-no">No</label> {% endif %} {% endfor %} </form> {% endblock %} But i know for a fact that this is not even close to what needs to be done... If anyone could give me their input or if you require more information. Thanks! -
Customizing Django's contrib.auth views for password reset
Since Django 3.0, the django.contrib.auth views are class-based views. So when developing a password reset on a website, you would have to import do something like from django.contrib.auth import views as av av.PasswordResetDoneView.as_view(template_name="accounts/password_reset_sent.html") However, I want to add some custom features to my site like sending an email AFTER the password has been reset by the user. Where can I add my custom functions and how? Note: I already configured an SMTP to my site and I also have the password reset setup with my custom templates. -
Django "Model class <Class> doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS" after separating models
I'm getting this error and I've been trying to fix it for many hours, it came up once I separated my models.py into a directory with multiple files. This is the current structure of my project. I have omitted many files, but these are the relevant ones: Project_folder academy app1 app2 manage.py models _ _ init _ _.py content.py session.py app3 config static Before, I had all my models in a single file inside app2, called models.py. However, as the file started to grow too large, I separated each of the models into different categories. Also, in __init__.py I imported these elements: from academy.app2.models.content import * from academy.app2.models.session import * Now, when I try to make migrations with python manage.py makemigrations app2, as usual, I'm getting this error: RuntimeError: Model class core.models.content.Reward doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. When I searched for this error, I came across this answer, however, when I add the Meta Class declarating the app_label, I get this error: RuntimeError: Conflicting 'reward' models in application 'app2': <class 'academy.app2.models.content.Reward'> and <class 'app2.models.content.Reward'>. This is my Config file for app2: class App2Config(AppConfig): name = 'academy.app2' This is my INSTALLED_APPS: INSTALLED_APPS = [ … -
DRF python ReturnList to JSON
I am trying to query informaicon and then I want to loop through that information to get certain data. The point is that when I try to go through the item "data" in the console I get a message saying "AttributeError: object 'ReturnList' has no attribute 'elements' " when I do "type (data)" I get the following: <class 'rest_framework.utils.serializer_helpers.ReturnList'> without the for (no errors) the information arrives as a JSON to the front. [{id: 1, photo: null ..}, {id: 2, photo: null ..} ... etc] viewSet code: class TecnicosViewSet( mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): queryset = Tecnico.objects.all() serializer_class = Tecnicoserializer def list(self, request): queryset = Tecnico.objects.all() serializer_class = Tecnicoserializer(queryset, many=True) data = serializer_class.data print(type(data)) # for index, item in data.items(): # print('II', index) return Response(data) -
Django Apache Site: Loads Forever
I have a Django Site running on an Apache server which is running with no errors but when i serach for localhost it loads forever and doesn't give a 404 response or anything. Any idea what i am doing wrong? Also, i am doing this using Apache and mod_wsgi. httpd.conf Define SRVROOT "c:/Apache24" ServerName localhost Include conf/extra/httpd-vhosts.conf LoadFile "c:/users/administrator/appdata/local/programs/python/python39/python39.dll" LoadModule wsgi_module "c:/users/administrator/appdata/local/programs/python/python39/lib/site-packages/mod_wsgi/server/mod_wsgi.cp39-win_amd64.pyd" WSGIPythonHome "c:/users/administrator/appdata/local/programs/python/python39" httpd-vhosts.conf <VirtualHost *:80> ServerName localhost ServerAlias localhost WSGIScriptAlias / "C:/Users/Administrator/Desktop/myapp/myapp/wsgi_windows.py" <Directory "C:/Users/Administrator/Desktop/myapp/myapp/"> <Files wsgi_windows.py> Require all granted </Files> </Directory> </VirtualHost> wsgi_windows.py import os import sys import site from django.core.wsgi import get_wsgi_application sys.path.append('C:/Users/Administrator/Desktop/myapp/') os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings' os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') application = get_wsgi_application() -
how to submit two subforms with one parent form using formset , giving formset values to M2M field django
i'm trying to make Hotel management system for an hotel , the scenario is : if the two visitor come for the first time ,they should be registered , using inline formset , and give the values for a M2M field in this case the M2M should accept null, and if those two visitors came again , we dont need to register , and just search for their name in the M2M field , and the admin can upload multiple images these is my models class Booking(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) room_no = models.ForeignKey(Room,on_delete=models.CASCADE,blank=True,related_name='rooms') takes_by = models.ManyToManyField('vistors.Vistor',related_name='vistors',blank=True) check_in = models.DateTimeField(default=timezone.now) check_out = models.DateTimeField(blank=True,null=True) #others class Vistor(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) booking = models.ForeignKey(Booking,on_delete=models.PROTECT,related_name='booking_vistors') full_name = models.CharField(max_length=150) dob = models.DateField(max_length=14) city = models.ForeignKey(City,on_delete=models.CASCADE) #others class Meta: constraints = [ models.UniqueConstraint(fields=['full_name','dob','city'],name='full_information') ] class Document(models.Model): booking =models.ForeignKey(Booking,on_delete=models.PROTECT) docs = models.ImageField(upload_to=upload_docs) my forms.py class BookingForm(forms.ModelForm): takes_by = forms.ModelMultipleChoiceField(queryset=Vistor.objects.all()) class Meta: model = Booking fields = ['takes_by','check_in','check_out',#others] class VistorForm(forms.ModelForm): city = forms.ModelChoiceField(queryset=City.objects.all()) class Meta: model = Vistor fields = ['full_name','dob','city'] VistorsInlineFormset = inlineformset_factory(Booking,Vistor,form=VistorForm,extra=1,can_delete=True) but it wont let me to leave takes_by null , it raise this field is required and i've used Function based view , this is my views.py @login_required def add_booking(request,room_no): room_number = get_object_or_404(Room,room_no=room_no) isnot_checked … -
Django: Hidden form FIELD (not widget) with `form.as_table`
One can add a disabled attribute to a widget by passing in attrs={'disabled':True}. However there also exists a disabled form field (not widget) argument, which tells Django this field is disabled, and then Django handles it accordingly in the validation logic and also setting the HTML disabled attribute. Now similarly with regards to hidden, one can set a widget to be hidden passing in attrs={'hidden':True}, but the problem with this is that it only hides the HTML input widget, the label associated with it still shown. How does one get around this problem (when using form.as_table, I understand one can loop through the visible and hidden fields and manually build up a form, but thats not what I am looking for. Under Core field arguments I would expect to see a hidden attribute. -
Setting up default path to csv files in Django Management Command
I have a management command and would like to, if no file path is explicitly given, read each file and carry out the command. How do I point the management command to the correct directory and have it open each file? class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('csvfile', nargs='?', type=argparse.FileType('r')) # This was set up for multi-tenant use later parser.add_argument('company_name', nargs='?', type=str, default='Fake_Company') def handle(self, *args, **options): contact_ids = [] if options['csvfile'] == None: csv_files = 'apps/user/csv_files' # this is the path to the directory for file in csv_files: with options['csvfile'] as csvfile: csvreader = csv.DictReader(csvfile) for row in csvreader: contact_ids.append(row['\ufeff"Id"']) print(row['\ufeff"Id"']) -
JavaScript: unable to disable/enable an input button
I'm building a web app using the Django framework. I'm attempting to use some JavaScript to disable a button that users can press to submit a text-based review. The JavaScript in the listing.js file looks as follows: document.addEventListener('DOMContentLoaded', function () { hide_submit_review_button(); }); // Hide the 'Submit Review'button until the user begins typing a review // Prevent the user from typing more than 100 characters function hide_submit_review_button() { var submit_review_button = document.getElementById('submit-review-button'); if (submit_review_button !== null) { document.getElementById('submit-review-button').disabled = true; document.getElementById('review-contents').onkeyup = () => { if ((document.getElementById('review-contents').value.length > 0 && document.getElementById('review-contents').value.length <= 100 )) { document.getElementById('submit-review-button').disabled = false; } else { document.getElementById('submit-review-button').disabled = true; } }; } } In my listing.html file, I identify the review-contents and submit-review-button. Here's the code: {% extends "layout.html" %} {% load static %} {% block body %} {% if user.is_authenticated %} <form action="{% url 'review' listing.id %}" method="POST"> {% csrf_token %} <input type="text" class="form-control" name="review" id="review-contents" placeholder="Write a review..."> <input class="btn btn-primary mt-1" type="submit" id="submit-review-button" value="Submit Review"> </form> {% endif %} {% endblock %} {% block script %} {% if user.is_authenticated %} {{ block.super }} <script src="{% static 'listing.js' %}"></script> {% endif %} {% endblock %} An example of a page where the button … -
AJAX request Django and Js
I am not very clear about the sequence in which Ajax works. I have a func in a js file that fires when clicked <! - begin snippet: js hide: false console: true babel: false -> <! - language: lang-js -> d = $ ('. b-popup_btn_email') console.log ('=================================================================='); console.log (d.val ()); console.log ('================================================================='); if (d.val () == 'NEXT') { console.log ('dfafag'); login_form.addEventListener ('submit', e => { e.preventDefault () fd = new FormData () fd.append ('csrfmiddlewaretoken', csrf [0] .value) fd.append ('email', email.value) fd.append ('code', code.value) $ .ajax ({ type: 'POST', url: "", enctype: 'multipart / form-data', data: fd, success: function (response) { console.log ('fsd'); d.val ('LOG IN') console.log (d.val ()); console.log (response.code); }, error: function (error) { console.log (error); }, cache: false, contentType: false, processData: false, }) }) } <! - end snippet -> It should check value and if it == 'Next' send request to django server but instead in console I get this `====================================main.js: 179 LOG IN main.js: 180 ==========================================================main.js: 212 dsad main.js: 197 fsd main.js: 199 LOG IN main.js: 201 undefined` Although value is equal to "LOG IN" he sends a request, I don’t need it and I don’t understand how to fix it. -
Django page not fund for generic View
Why I am getting page not found error. I passed the views in my urls.py. here is my code: class JsonListView(View): def get(self, *args,**kwargs): customer_project = list(CustomerProject.objects.values()) return JsonResponse({'data':customer_project},safe=False) my urls.py urlpatterns = [ #my others urls.... path('json-data/', JsonListView.as_view(), name='json-data'), ] my home page and others page haven't any problems. Only getting the Page not found (404) error for json-data page. console error: Not Found: /json-data/ [04/Aug/2021 03:27:50] "GET /json-data/ HTTP/1.1" 404 6958 -
Celery Beat is getting exited after start
I am running celery beat with command using ==> celery -A config.celery_app beat -l INFO. the above command is running through docker. even i tried using run by passing Scheduler to the above command, but celery beat is getting exited after its start, below is the log. Worker is starting fine and i am able to create the schedules and manually able to run jobs, but due to celery beat is not up and running, so i could not see automatic running of scheduled jobs. Celery Beat Log Attaching to celerybeat celerybeat | PostgreSQL is available celerybeat | celery beat v4.4.6 (cliffs) is starting. celerybeat | __ - ... __ - _ celerybeat | LocalTime -> 2021-08-03 23:00:08 celerybeat | Configuration -> celerybeat | . broker -> redis://redis:6379/0 celerybeat | . loader -> celery.loaders.app.AppLoader celerybeat | . scheduler -> django_celery_beat.schedulers.DatabaseScheduler celerybeat | celerybeat | . logfile -> [stderr]@%INFO celerybeat | . maxinterval -> 5.00 seconds (5s) celerybeat | [2021-08-03 23:00:08,241: INFO/MainProcess] beat: Starting... celerybeat | [2021-08-03 23:00:08,283: CRITICAL/MainProcess] beat raised exception <class 'django_celery_beat.models.PeriodicTask.schedule.RelatedObjectDoesNotExist'>: RelatedObjectDoesNotExist('PeriodicTask has no schedule.') celerybeat | Traceback (most recent call last): celerybeat | File "/usr/local/lib/python3.9/site-packages/kombu/utils/objects.py", line 42, in get celerybeat | return obj.dict[self.name] celerybeat | KeyError: 'scheduler' … -
How can i change queryset on SelectField?
I have a form, and a select input, i need change the queryset of tthat select, how can i make this? my form exemple: class myModelForm(forms.ModelForm): class Meta: model = myModel fields = '__all__' -
How to overide ImageField widget on Django
If someone could please help me with this one, I've been struggling for a while and I really can't find anything that works for me, I am attempting to remove the widgets that come with "ImageField" apart from the button "Choose File". Basically I want to remove: Profile Picture LABEL Currently LABEL Picture Name Clear Box Change LABEL If possible still be able to target the Label No file choosen but if not remove it as well. Image So basically, remove all the labels but still be able to target the button on the html so I can style it. Model.py class Profile(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) profile_pic = models.ImageField(default="#profile_pic.png", null=True, blank=True) Form.py class EditPhoto(ModelForm): class Meta: model = Profile fields = ['profile_pic'] exclude = ['user'] -
How to prevent Heroku clock dyno from sleeping on free tier?
I am using Heroku to host a Django web app. This is just for a fun project that will make no money so paying for the premium service would not make sense. I am using APScheduler to run a cron job once per day. So for this, I have a clock dyno running. The issue is that the clock dyno keeps going idle after 30mins of inactivity. I read that you can ping the app to keep it from idling but unfortunately, this just keeps the web dyno from idling, the clock dyno still idles. Any recommendations? I'm essentially looking for a free way to send scheduled emails once a day. I tried using mailchimp but you have to pay to schedule an email. -
heroku error codeH14 desc No web processes running issue with django project
getting this error post successful deployment of my project in Heroku, log tail show above issue, please help, my Procfile is named Procfile and its content web: gunicorn main.wdgi heroku ps:scale web=1 -
Javascript in Django template for changing Element Background Color
First off I am not a web developer at my core. I user primarily c# and Python and have begun branching out into Django applications over the previous 6-7 months. Javascript is relatively new to me however It's just syntax that I get hung up on so pardon my dirty JS. I am developing an internal evaluation tool using Django that allows the user to set a value based upon a Range slider. I have the model and form working and saving properly however I want the page to be dynamic on the client side in the following way. I want the value of the range input to change the background color of a specific HTML element. I have found out how to do this using strictly html and Javascript however I cannot for the life of me get it to work with the django slider. Here is the HTML. <th scope="col" id="elementToChange"> <input type="range" class="custom-range" min="0" max="100" id={{ form.django_variable }} </th> I would like to change the background of the "th" element with the following script in Javascript. dict = { 1: 'color1', 2: 'color2', etc... } function changeElementColor() { let djangoVariableValue = {{ form.django_variable }}; document.getElementById('elementToChange').style.backgroundColor = dict[djangoVariableValue]; … -
Django get the last part of the path in the URL in the template
I have a path https:///something.com/asset/asset_app/location_laptop/POA/ I want to exract "POA" part and write in my template {{ request.##### }} how would i do that? -
Define a global variable that can be modified in the admin page django, and questions about fields
I need to define a variable (a tax rate) that will be used in other models, and while it can be modified later on in the admin page, it shouldn't modify its value in already defined instances of the other model (Product). Basically I create instance1 with a 5% tax rate defined globally, then I change the tax rate to 10%; instance1 should still have a 5% tax rate. How should I do that? There should only be one instance of the tax rate model (if using a model is recommended/needed). Thanks in advance. -
django djoser missing related field when sending request
I am using django and djoser with custom user here is my user class class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) phone = models.CharField(max_length=15, unique=True) company = models.ForeignKey(Company, related_name='users', on_delete=models.CASCADE) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name' ] this is my company class : class Company(models.Model): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=30) phone = models.CharField(max_length=10) address = models.EmailField(max_length=255,null=True) is_active = models.BooleanField(default=False) Baseusermanager: class UserAccountManager(BaseUserManager): def create_user(self, email, first_name, last_name, company_id, password=None): if not email: raise ValueError('Users must have an email address') email = self.normalize_email(email) user = self.model(email=email, first_name=first_name, last_name=last_name, company_id=company_id) user.set_password(password) user.save() return user and these are my serializers : class CompanySerializer(serializers.ModelSerializer): class Meta: model = Company fields = ('id', 'email', 'name', 'phone', 'address', 'is_active','users') class UserCreateSerializer(UserCreateSerializer): company_id = serializers.PrimaryKeyRelatedField(many=False,queryset=UserAccount.objects.all(),read_only=False) class Meta(UserCreateSerializer.Meta): model = get_user_model() fields = ('id','company_id','email', 'first_name' , 'last_name', 'password','re_password') but every time when I send request to create user I got error told me that the company_id (which is the foreign key) field is missing even if I've sent it (every thing was working perfectly before I added the company foreign key ) -
Could you help me please how i can change my django jinja template code in ajax jquery?
I'm using Django rest framework with ajax submit form. I have done django with jinja template but now i switch to ajax submit form using drf so i didn't need jinja template code but i need jinja template logic in ajax jquery because now i am using ajax jquery with drf so i want to change my following django jinja template code into ajax jquery. My code: {% if ".jpg" in blogs.file.url or ".jpeg" in blogs.file.url} <img class="img-circle" src="{{blogs.file.url}}" height="200" width="200"> <style> .img-circle { border-radius: 50%; } </style> {% endif %} {% if '.mp4' in blogs.file.url or '.AVI*' in blogs.file.url %} <video width='400' controls> <source src="{{blogs.file.url}}" type='video/mp4'> Your browser does not support the video tag. </video> {% endif %} {% if '.mp3' in blogs.file.url %} <audio controls width="320" height="240"> <source src="{{blogs.file.url}}" type="audio/ogg"> </audio> {% endif %} I want change django jinja template code into ajax jquery.How i write that code in ajax jquery. Please help me.