Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Apache 24 Error: Forbidden You don't have permission to access this resource
I am running Django on an Apache24 server which is running but when i search for the localhost i get an error: Forbidden You don't have permission to access this resource.. When i check the logs i see this error: The given path is misformatted or contained invalid characters: AH00036: access to / failed (filesystem path 'C:/Apache24/\xe2\x80\x9cC:') Here are the relevant files: 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> -
Get the value of a specific variable in a html template with django
I am trying to get the value which is stored in a variable as : html <p class="title" name="no">Guarde : {{no}}</p> ... <form action="nextep" method="get"> <button class="btright" name="btnext" action="nextep"> <i class="fas fa-chevron-circle-right"></i> </form> views.py def nextep(request): n = {{ no }} #I would like to get it from the initial value stored (which is 1) return render(request, "episode.html", {'no': n+1}) How could I do that please? I tried different version with request.get['no'] too, but nothing worked, if someone has an idea, thanks for you help -
How can I share a variable between multiple functions of a class in Django?
I want the page load to initialize "self.var" and then share this output with functions 'shared1' and "shared2" within the "main" class. I want to avoid declaring self.var each time I call "shared1" or "shared2". I also do not want to use request.sessions because this requires additional overhead when serializing self.var this is my views.py: class main: def __init__(self): self.var = ['test'] def pageload(request): context = {"nothing": "nothing"} return render(request, "index.html", context) def shared1(self, request): s1 = self.var s1alt = s1.append('test1') context = {"var": s1alt} return JsonResponse(context) def shared2(self, request): s2 = self.var s2alt = s2.append('test2') context = {"var": s2alt} return JsonResponse(context) this is my urls.py: path('home/',views.main().pageload,name="categories"), path('ajaxgets1/',views.main.shared1,name="ajaxgets1"), path('ajaxgets2/',views.main.shared2,name="ajaxgets2"), -
Is there a more efficient way to edit a django many to many field?
Is there a way to edit many to many fields in django that involves removing objects efficiently? lets say you have these models: class PerksAndBenefits(models.Model): name = models.CharField() class Company(object): perks_and_benefits = models.ManyToManyField(PerksAndBenefits) and your user sends in a list from the frontend to update their model: data=['name 1', 'name 2', 'name 3'] But the model has company.perks_and_benefits.all() = Queryset('name 1', 'name 3') is there a way to do this that doesnt involve clearing the company and then bulk creating through the relation model? -
ValidationError: [u'ManagementForm data is missing or has been tampered with.'] when trying to submit a form?
I have already tried the other posted solution to add the management file to the template. The only other answer online is about prefixes which we do not believe is the problem. Any ideas? -
How to run python codes (not in views) periodically in Django Framework?
I am using Django Framework to write a middleware. Basically, every week, it calls an external API to receive a xml file, does some data processing and sends the results to RabbitMQ. I am new to Django Framework. I wrote some python files to achieve the logic, but these files did not execute when running the server. I am wondering how to run these codes periodically which are not inside views. Thank you. -
How to retrieve https api endpoints from an opensource Pylons project: Reddit, specifically?
Reddit was opensource until a while ago, and here's their repo: https://github.com/reddit-archive/reddit I was wondering if it was possible to backtrack all https endpoints they use: for login, for sign-up, for posts, for comments, for follow, etc. Can we backtrack it? It will also be helpful if someone who has already figured this out shares their findings. Thank you. -
Explanation of Django error_messages{}?
With this explanation of implementing a custom user model in django there is the inclusion of error_messages{...} dictionary. Where does 'unique' come from? Where can I find a comprehensive list of the possible options? I have looked at the documentation for built-in field classes here and I have looked in the appropriate fields.py file on github which says EmailField inherits from CharField, which in turn inherits from base Field class. None of these mention 'unique' as a possible key in the dictionary so I'm really confused as to why you can define it. -
How to use a serializer with foreign keys for Django rest api?
I have two django models with a many-to-one relationship (one venue can have many events). I want to produce a page which has all the attributes from each event, and the information about its venue from the venue model. Here is my models.py file: class Venue(models.Model): venueID = models.AutoField(primary_key=True) venueName = models.CharField(max_length=40) venueImage = models.ImageField(upload_to='images/', blank=True, null=True) def __str__(self): return self.venueName class Event(models.Model): venueID = models.ForeignKey( Venue, related_name='events', on_delete=models.CASCADE) venueName = models.CharField(max_length=40) eventID = models.AutoField(primary_key=True) artistName = models.CharField(max_length=100) eventName = models.CharField(max_length=100) def __str__(self): return self.eventName Here is my serializers.py file class VenueSerializer(serializers.ModelSerializer): class Meta: model = Venue fields = "__all__" class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = "__all__" class VenueForGivenEventSerializer(serializers.ModelSerializer): events = EventSerializer(many=True) class Meta: model = Venue fields = '__all__' My urls.py file: (I'm pretty sure that this is not the issue) from django.urls import path from django.urls.conf import include from .views import EventViewSet from .views import VenueViewSet from .views import VenueForGivenEventViewSet from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('events', EventViewSet) router.register('venues', VenueViewSet) router.register('fullevents', VenueForGivenEventViewSet) urlpatterns = [ path('', include(router.urls)) ] At the moment, when accessing /fullevents, I currently get an error saying: int() argument must be a string, a bytes-like object or a number, not 'Venue' … -
Django celery not using default queue
I'm using Django 3.2 and Celery with the following configuration celery.py import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'quiz.settings') celery_app = Celery('quiz') celery_app.config_from_object('django.conf:settings', namespace='CELERY') celery_app.autodiscover_tasks() @celery_app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) and the following settings.py import os from kombu import Queue CELERY_RESULT_BACKEND = 'django-db' CELERY_TASK_DEFAULT_QUEUE = 'tb-account-task-queue' if os.environ.get('CELERY_BROKER_URL', None): CELERY_BROKER_URL = os.environ.get('CELERY_BROKER_URL') CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' CELERY_TASK_QUEUES = [ Queue(CELERY_TASK_DEFAULT_QUEUE) ] CELERY_BROKER_TRANSPORT_OPTIONS = { 'visibility_timeout': 60, 'polling_interval': 60, 'region': os.environ.get('AWS_DEFAULT_REGION', None) } When the task is created, it creates a new queue in SQS with celery instead of using tb-account-task-queue task as defined as the default queue. -
How to maintain Django celery progress for a queue having multiple workers
I have 2-3 tasks which run with 2 workers and as each record is processed i increment the counter and convert it into a percentage and store it in redis against a process_id, which was generated for the queue, but the issue is sometimes worker 2 will complete faster than worker 1 even-though worker 1 was issued the task first and this causes the percentage to drop which will ultimately prevent the final value from not reaching 100%, is there any solution to this?