Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django DateTimePicker calendar appears at the bottom of page
I am trying to implement datetimepicker to my django project and i am nearly there. My day field is able to pick a week instead of just a day, but the calendar is appearing at the bottom of the page. html: <script> $(function () { $('#id_day').datetimepicker({ format:'DD-MM-YYYY' }); $('#id_day').on('dp.change', function (e) { var value = $("#id_day").val(); var firstDate = moment(value, "DD-MM-YYYY").day(0).format("DD-MM-YYYY"); var lastDate = moment(value, "DD-MM-YYYY").day(6).format("DD-MM-YYYY"); $("#id_day").val(firstDate + " - " + lastDate); }); }); </script> <body> <form method="post" style="margin-left: 16px"> {% csrf_token %} <table> {{ form }} </table> </form> </body> Can't seem to figure out why it is at the bottom of the page. -
Create dynamically a model in the save() method from another model
I want to create a model within the save method of another model, so the one generated dynamically is named with a field from the static model. Model Code: class Car(models.Model): name = models.CharField(max_length=128) def save(self, *args, **kwargs): attrs = { 'piece': models.CharField(max_length=128), '__module__': 'myapp.models' } model = type('%s_piece' % self.name, (models.Model,), attrs) admin.site.register(model) super(Car, self).save(*args, **kwargs) The model is generated but I don't know how to make the migrations or migrate it to the database. I tried to migrate it with: from django.core.management import call_command call_command('makemigrations') call_command('migrate') But I get an error as I'm executing this in an atomic transaction. -
How to send Django's password reset email using Celery (without third-party package)?
First of all I know this question has been answered previously here which use a third-party package django-celery-email, but I am trying to figure out how to do do such job without relaying on any third-party library. So I need to send password reset email asynchronously with Celery. My forms.py file look like this: from django import forms from accounts.tasks import send_mail from django.contrib.auth.forms import PasswordResetForm as PasswordResetFormCore class PasswordResetForm(PasswordResetFormCore): email = forms.EmailField(max_length=254, widget=forms.TextInput( attrs={ 'class': 'form-control', 'id': 'email', 'placeholder': 'Email' } )) def send_mail(self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None): """ This method is inherating Django's core `send_mail` method from `PasswordResetForm` class """ super().send_mail(subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name) I am trying to send mail via Celery from send_mail method of PasswordResetForm class. I mean calling super().send_mail(...) with Celery. I also have a send_mail function in my Celery's tasks.py file, where I am trying to pass super().send_mail method as an argument to call it from there. Right now my tasks.py file looks something like this: from __future__ import absolute_import, unicode_literals @shared_task def send_mail(): pass I am using RabbitMQ as message broker alongside with Celery -
What is the benefit to use Docker for Django and Channels?
I'm developing a Django web app with Channels. While I'm following this tutorial , it is required to install Docker. I'm working on WSL on windows 10 HOME, and so, it is really painful to install Docker. I just discover Docker, I'm a little confuse about it, I understand it is a tool which facilitates the deployment of a web app on a web hosting later. But I'm not sure. Could you give me your advice ? Could you tell me if it is really important to use Docker for my project ? Would Have I less pain if I would develop on a Ubuntu OS ? Thank you, -
Django Model as Python dictionary key
I need to build a dictionary wich would have Django Models as keys but I get this error on a default made model : TypeError: Model instances without primary key value are unhashable yet, Django documentation says that it takes care of building id as default primary key. So why do I get this error ? -
How do I refer to a OneToOne model in my views.py?
I have no idea how to refer to my OneToOne Field: class Studente(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ore = models.IntegerField() in my views.py file. @login_required(login_url="/home/") def vistaPrivata(request): all_corsi = Corso.objects.all() user = request.user user_ore = [[ I Dont really know what to write in here ]] template = loader.get_template('corsi/vistaPrivata.html') if request.method == 'POST': logout(request) return redirect('Completa') else: context = { 'user_ore' = user_ore, } return HttpResponse(template.render(context, request)) Can you please help me? Would be really appreciated -
Django: How to create form on modal
I'm trying to use form on modal. But it doesn't work well. For the page there are a bunch of entries (Entry obejcts) and I'm using custom templatetag to associate the comment submission with the entry. html is like this. {% for entry in entries %} ... <div class="modal-footer"> {% render_comment_form entry as comment_form %} <form method="POST" novalidate> {% csrf_token %} <div class="form-group"> {{ comment_form.text|add_class:'form-control' }} </div> <button type="submit" name="comment_form" class="btn btn-outline-primary">Post</button> <button type="button" class="btn btn-outline-secondary" data-dismiss="modal">Close</button> </form> ... {% endfor %} and the custom templatetag is like this. @register.simple_tag(takes_context=True) def render_comment_form(context, entry): request = context['request'] if 'comment_form' in request.POST: comment_form = CommentForm(request.POST, entry=entry, user=request.user) if comment_form.is_valid(): comment_form.save() # return to the current page here else: comment_form = CommentForm(entry=entry, user=request.user) return comment_form There are two problems. First when I submit a Comment, the same comment is copied and associate with every Entry object on the page. Like if I post Hello, the comment Hello is copied by the number of Entry objects on the page and associate with them. Second, how can I redirect to a page after submission? I cannot include return HttpResponseRedirect... in the templatetag because it's supposed to return comment_form? Anyone could give me tips to solve … -
passing asynchronous event data from Javascript to Django view
My application should allow me to drag div's around a parent container and when dropped, I would have to save the new x and y position of the element via my Django BE into the database. As this drag and drop is fully asynchronous to anything happening in the Django domain, I need my javascript trigger an event in Django. And I am stuck as I don't know how to do this. Say I use jQuery UI and do some code like below: $('.person').draggable({ containment: 'parent', grid : [50, 50], start: function(element) { console.log("started"); }, stop: function(element) { console.log("stopped", $(this).css("top"), $(this).css("left"), this.id); } }); As you see, the function call on "stop" is fully asynchronous. I should now be able to pass x,y position plus the id of the element bak into a Django view to be saved in the database. I don't think I can use AJAX or similar Any solution for me? thanks -
How to get query from template when foreigKey has related_name in django
Hi i can get query using this line when my foregin key does not have related_name: {{user.provider_set.all}} but when i set a related_name for it it doesn't work any more. how should I get data now -
django-celery-beat doesn't start within supervisor just manually
I've installed Celery[sqs] and django-celery-beat in my Django 1.10 project. I've trying to run them both (worker and beat) using Supervisor on and EBS instance. The Supervisor config is being created dynamically with the following script: #!/usr/bin/env bash # get django environment variables celeryenv=`cat /opt/python/current/env | tr '\n' ',' | sed 's/export //g' | sed 's/$PATH/%(ENV_PATH)s/g' | sed 's/$PYTHONPATH//g' | sed 's/$LD_LIBRARY_PATH//g' | sed 's/%/%%/g'` celeryenv=${celeryenv%?} # create celery beat config script celerybeatconf="[program:celery-beat] ; Set full path to celery program if using virtualenv command=/opt/python/run/venv/bin/celery beat -A phsite --loglevel=DEBUG --workdir=/tmp -S django --pidfile /tmp/celerybeat.pid directory=/opt/python/current/app user=nobody numprocs=1 stdout_logfile=/var/log/celery-beat.log stderr_logfile=/var/log/celery-beat.log autostart=false autorestart=true startsecs=10 ; Need to wait for currently executing tasks to finish at shutdown. ; Increase this if you have very long running tasks. stopwaitsecs = 10 ; When resorting to send SIGKILL to the program to terminate it ; send SIGKILL to its whole process group instead, ; taking care of its children as well. killasgroup=true ; if rabbitmq is supervised, set its priority higher ; so it starts first priority=998 environment=$celeryenv" # create celery worker config script celeryworkerconf="[program:celery-worker] ; Set full path to celery program if using virtualenv command=/opt/python/run/venv/bin/celery worker -A phsite --loglevel=INFO directory=/opt/python/current/app user=nobody numprocs=1 stdout_logfile=/var/log/celery-worker.log stderr_logfile=/var/log/celery-worker.log autostart=true … -
DjangoCMS add childplugin button
I have people PeoplePlugin that can have many of child plugins PersonPlugin. I want to add a button (Add child plugin) to a template of PeoplePlugin, that allows me to open modal to create new 'PersonPlugin', the same way as in side-toolbar. Is that possible? Thank you. -
DJango - Export Json Field in Model to CSV along with other fields
I am working on a DJango project, and in the admin I need to add an action which will export and download the contents of the model. I have successfully added the export action using import-export and it downloads the data just fine. Currently I just subclass using ImportExportActionModelAdmin and it automatically shows the export option in the drop down menu. But now the issue is, one of the fields in the model being downloaded is a JSON field and gets exported to csv as JSON itself, rightly so. I want ideas on how can i convert this JSON field into csv as well. Sample data that gets downloaded in the CSV: {u'course_name': u'ABC', u'notes': u'Test', u'contact_mode': u'Message', u'contact_no': u'9876543210', u'stud_count': u'600', u'date': u'2018-12-19T18:30:00.000Z', u'email': u'kj@test.com', u'exp11': u'YES'} I did some reading and seems import_export.widgets.JSONWidget can do the trick but am not sure how to implement this. Can some one give an example. Thanks in advance. -
Static file issue when deploying an Django app
I understand there are some existing problems/answers about loading static files in production. However, my case is somehow different. My Django app not is deployed as the main app of my website (not in the public_html folder in the server), but an additional app (in a folder outside public_html). The server folder directory is like this home/myaccount/ ├── public_html | └── static (not exist, location 1) ├── mydjango └── static (generated by collectstatic, location 2) └── css, fonts etc. In my settings.py, STATIC_ROOT = os.path.join(BASE_DIR, 'static/') and STATIC_URL = '/static/'. Currently, the browser will look for static files in the non-existing location 1, i.e., www.mypage.com/static/..., instead of location 2. 404 errors return. My question is that how I can change STATIC_ROOT and STATIC_URL or other settings to make the browser look for location 2 instead of location 1? -
Dynamic Drop List for Many to Many relation
I have 2 tables "Client" and "Location". class Client(models.Model): name = models.CharField(max_length=50) class Location(models.Model): name = models.CharField(max_length=50) A Client can be in many Locations and a Location can have many Clients. I created a third table to hold this relationship: class Client_Location(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE) location = models.ForeignKey(Location, on_delete=models.CASCADE) I created a form to test whether i can make the dropdownlist dynamic, so if i were to pick a client, any location linked to that client would only appear. class ClientLocationForm(forms.ModelForm): class Meta: model = Client_Location fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['location'].queryset = Location.objects.none() So far i was only able to make the location field blank. Not sure where to go next as examples i've seen aren't exactly like mine. -
Django django.db.utils.ProgrammingError: relation "ad.tcontainer_format" does not exist
I am writing unit test in Django, but I have problem: django.db.utils.ProgrammingError: relation "ad.tc_format" does not exist LINE 1: ...ze", "ad"."tc_format"."y_size" FROM "ad"... Important issue that is we haven't tools like migrate and makemigrations, all is manually create and own database routers class in addition in database all exists. I think also about databases that I wrongly set default database, because I need two database to test: DATABASES = { 'default': { # Here are users, permissions... 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'panels', 'USER': 'admin', 'PASSWORD': DEFAULT_PASSWORD, 'HOST': HOST, 'PORT': PORT, }, 'ad': { # If I change name to default, then I got error - the ad name is required and here is other datas which I need 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'stats', 'USER': 'postgres', 'PASSWORD': AD_PASSWORD, 'HOST': HOST, 'PORT': PORT, 'TEST': { 'CREATE_DB': False, 'DEPENDENCIES': ['default'] } }, I have tried duplicate database or created mirror: DATABASES = { 'panels': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'panels', 'USER': 'admin', 'PASSWORD': DEFAULT_PASSWORD, 'HOST': HOST, 'PORT': PORT, }, 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'stats', 'USER': 'postgres', 'PASSWORD': AD_PASSWORD, 'HOST': HOST, 'PORT': PORT, }, 'adnetsys': { # Duplicated 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'stats', 'USER': 'postgres', 'PASSWORD': AD_PASSWORD, 'HOST': HOST, 'PORT': PORT, }, Or [...] 'adnetsys': { 'ENGINE': … -
Django - Update with Subqueries
I'm trying to update some "summary models" of my data without using a for loop. These summaries share many of the same field names as the data, so I feel like there should be an easy way to do some sort of Summary.objects.all().update(**Subquery(Data.objects.filter(my_key=OuterRef('my_key')).aggregate(my_value_1=Sum('my_value_1'), my_value_2=Sum('my_value_2')) or something similar and have the values in Summary be updated. However, it's not that simple. For starters, I get the following error: ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. This seems to happen because of the aggregate part, as removing the aggregate fixes that error... but I need the Sum! And of course there's a different error for **Subquery(), and yet another error for .update(Subquery()) I feel like there is a very simple solution to my problem, but I just keep hitting error after error and can't figure out how to get on the right track. Any advice would be greatly appreciated. -
Cannot see installation in docker container when using docker-compose
I'm trying to dockerize my django app which has postresql and apache in it. I have my dockerfile and docker-compose.yml and when I run docker-compose up, everything works fine. However, when I go into my containers, I cannot see my django,apache vs. But all of my file are copied succesfully. I tried docker run -it <mycontainer> bash and then try which python, which django or something and just python is installed. There is no other thing in my container from requirements.txt My question: why cant I see the things which requirements.txt should download in my container ? -
Create and connect other tables to MySQL database in Django
I have a problem regarding how to connect other tables to database using phpmyadmin(mysql) in Django. I have used auth_user table for registering user's account. Now i wanted to create another table which stores data of user regarding his residence,phone number, gender etc. These information i should be stored in other tables. So please help how can i create and connect that table to database of mysql. -
Django form rendering: group fields
I am rendering a form manually and I want show several fields in groups. I need to iterate each group separately, just like we do this: {% for field in form %} I am trying to do this: {% for field in group1 %} I tried defining group1 in the constructor: def __init__(self, *args, **kwargs): # blah self.group1 = [self.field['a'], self.field['b']] self.group2 = [self.field['c'], self.field['d'], self.field['e']] But then when it comes to rendering those fields the __repr__ method is being used instead of __str__. -
Is there a way to present form filled data by the user on the next page for addtional form fields?
I am creating a form for the user to fill fantasy players for their team. On selection of the players for their team, they hit the save/submit button, they should see the selected players on the next page with the option of choosing Captain and Vice-Captain of the team. Could you guide me how to setup these fields after players selection? How to do exception handling that only one player is selected for captain and vice-captain role. I have Player Model for players with a ForeignKey to the Team model. Player(models.Model): .... name = models.CharField(max_length=255) team = models.ForeignKey(team, on_delete=models.CASCADE) captain = models.BooleanField(default=False) vice_captain = models.BooleanFiled(default=False) ..... Team(models.Model): .... name = models.CharField(max_length=255) team_points = models.IntegerField(default=0) .... -
How to fix NoReverseMatch at /user_login when trying to log in from project folder? DJango
I have a project folder mysite and my app folder passwordValidate. When I move the path of user_login to passwordValidate/urls.py, the login works but same is not working from mysite/urls.py. The error message is Reverse for 'user_login' not found. 'user_login' is not a valid view function or pattern name. mysite/urls.py from passwordValidate import views urlpatterns = [ path('',views.home,name='home'), path('passwordValidate/',include('passwordValidate.urls')), path('user_login',views.user_login,name='user_login'), ] passwordValidate/views.py def user_login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username,password=password) if user: if user.is_active: login(request,user) return HttpResponseRedirect(reverse('home')) else: return render(request,'passwordValidate/login.html') passwordValidate/templates/passwordValidate/base.html <li class="nav-item"> <a class="nav-link" href="{% url 'user_login' %}">Log In</a> </li> -
filter posts based on a particular field in django template
I am working on a django application. The application holds a form which when filled will redirect to item_list page where the user can view the item they posted and also delete the item. I want this page to list only the items posted by that particular user who is currently logged in. but right now, this page lists items by every user. I tried adding an if case to the template but this results in displaying none of the posts. what am I doing wrong? this is my code so far items_list template {% extends 'base.html' %} {% load staticfiles %} {% block title %} items {% endblock title %} {% block header %} <link rel="stylesheet" href="{% static 'css/item_list.css' %}"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript" src="{% static 'js/item_list.js' %}"></script> {% endblock header %} {% block content %} <div class="container"> <center><h2>Items</h2></center> <table class='table table-borderless table-hover'> <thead> <tr> <th>Image</th> <th>Title</th> <th>Pattern</th> <th>Color</th> <th>Vendor</th> <th>Upload date</th> <th>Time</th> <th></th> <th></th> </tr> </thead> {% for item in items %} {% if request.user == item.vendor %} <tr> <td> <a href="{{item.img.url}}" target="_blank"><img src="{{item.img.url}}" alt="{{item.title}}" style="width:80px;"></a> </td> <td>{{item.title}}</td> <td>{{item.pattern}}</td> <td>{{item.color}}</td> <td>{{item.vendor}}</td> <td>{{item.date}}</td> <td>{{item.time}}</td> {% endif %} <td> <a href="{% url 'upload_item' %}" class='btn btn-outline-warning btn-sm text-dark' style="width:100px">Edit item</a> … -
Django-pgcrypto EncryptedCharField with Choices breaks the Selectbox in Django Admin View
The EncryptedCharField of Django-pgcrypto breaks the Selectbox in Django Admin View. How can i fix it? Before: class Person(Model): work_hours_mon = models.DecimalField('Montag', default = 8, validators=[ MaxValueValidator(24), MinValueValidator(0) ] ) Selectbox before django-pgcrypto After: class Person(Model): work_hours_mon = pgcrypto.EncryptedDecimalField('Montag', default = 8, validators=[ MaxValueValidator(24), MinValueValidator(0) ], key = settings.KEY_FOR_DJANGO_PGCRYPTO, ) Selectbox after django-pgcrypto Thanks. -
Join in Django with Foreing Key
I am using in-built User Model. Now i want to display in my template first_name, last_name form User Model and timesheet_is_running from TimesheetEntry Model. Models.py class TimesheetEntry(models.Model): timesheet_users = models.OneToOneField(User, on_delete=models.CASCADE,related_name='timesheet_users') timesheet_is_running = models.BooleanField(default=False) class Meta: db_table = "timesheet_entry" View.py class ClockInOutUserListView(LoginRequiredMixin, generic.TemplateView): template_name = 'admin/clock/clock.html' def get_context_data(self, **kwargs): context = super(ClockInOutUserListView, self).get_context_data(**kwargs) company_name = self.request.user.userprofile.user_company context['users'] = User.objects.exclude( Q(userprofile__user_is_deleted = True) | Q(userprofile__user_company__company_is_deleted=True) | Q(userprofile__user_role__acl_role_title='Admin') ).filter( Q(userprofile__user_company =company_name) ) #for user in context['users']: # job_user = TimesheetEntry.objects.get(timesheet_users=user) #print(user.timesheet_entry_set.all()) return context For displaying i am using get_context_data in which context['users'] is printing my users first_name and last_name. But i am not able to display timesheet_is_running which is in Jobs Model. So i was thinking about join. Please help to join two Models User and TimesheetEntry so that i can display in my template template.html {% for user in users %} {{user.first_name}} {{user.last_name}} {{user.timesheet_is_running}} <!-- How can get this value in template --> {% endfor %} -
DRF, "required": "This field is required."
I can't get a valid response, always get this error {"required": "This field is required.", "null": "This field may not be null.", "not_a_list": "Expected a list of items but got type \"{input_type}\".", "empty": "This list may not be empty."} models class Task(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=500, blank=True, default='') pub_datetime = models.DateTimeField() priority = models.CharField(choices=PRIORITY_CHOICES, max_length=1) status = models.BooleanField(default=False) owner = models.ForeignKey('auth.User', on_delete=models.CASCADE) agenda = models.ForeignKey(Agenda, on_delete=models.CASCADE, blank=True, default=None, null=True) def __str__(self): return self.name serializers class TaskSerializer(serializers.ModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') agenda = serializers.ReadOnlyField(source='agenda.name') class Meta: model = Task fields = ('id', 'name', 'description', 'pub_datetime', 'priority', 'status', 'owner', 'agenda') views queryset = Task.objects.filter(owner=self.request.user) serializer = TaskSerializer(data=queryset, many=True) if serializer.is_valid(): return JsonResponse(serializer.data) else: return JsonResponse(serializer.error_messages) I'm not sure, at what place I'm wrong