Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Datapicker in django data input
I tried to implement this solution to create a form field with a data picker. The field appears, but it does not show a calendar. It is a regular input field. I don't know if I'm missing any include. Could you help please? My forms.py: class CreateProjectForm(forms.Form): project_expiration = forms.DateField(widget=forms.TextInput(attrs={'class':'datepicker'})) def __init__(self, *args, **kwargs): super(CreateProjectForm, self).__init__(*args, **kwargs) self.fields['project_expiration'].label = "Expiration Date:" My template: {% for field in form %} <div class="form-group"> <div class="col-sm-3"> <label for="{{ field.id_for_label }}" class="control-label">{{ field.label }}</label> </div> <div class=" col-sm-9"> {{field}} </div> </div> {{field.non_field_errors }} {{field.errors}} {% endfor %} And my includes: <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script> <link href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" /> -
Django Login Form Returning false on is_valid() if username already exists
I have a login form I created from Django's User model: forms.py: class LoginForm(ModelForm): class Meta: model = User fields = ['username', 'password'] widgets = { 'username': forms.TextInput(attrs={'placeholder': '@username'}), 'password': forms.PasswordInput(attrs={'placeholder': 'Password'}) } views.py: reg = LoginForm(request.POST or None) if reg.is_valid(): return HttpResponse('Success: valid form') else: return HttpResponse('Error: invalid form') Now if I try login in with a username that is not registered it returns Success: valid form but if it is a username that already exists, it says Error: invalid form. I tried doing this in command line and below is what I get (I first tried it with a username that is register, yax): In [2]: data = {'username':'yax', 'password':'wrong_password'} In [3]: form = LoginForm(data) In [4]: form.is_valid() Out[5]: False In [6]: form.errors Out[7]: {'username': [u'A user with that username already exists.']} In [8]: data = {'username':'wrong_name', 'password':'wrong_password'} In [9]: form = LoginForm(data) In [10]: form.is_valid() Out[11]: True In [12]: form.errors Out[13]: {} Would be glad I can know why I am getting this error and how do I solve it. -
Google App Engine import error, for django.urls
I'm trying to learn Django, so I completed their multi-part tutorial (Python 2.7) and ran it locally. I got it working fine on my PC. I need the following import, in a views.py file: from django.urls import reverse When I upload it to GAE, it gives me the following error: Exception Type: ImportError Exception Value: No module named urls Is this module unavailable for the GAE, or am I doing something wrong? (By the way, I need this import so I can use the "reverse" method, after a user submission is received in the polls app, like: HttpResponseRedirect(reverse('polls:results', args=(question.id,))) ) -
What is 'success_url' variable default value
I am creating a form in Django by extending the CreateView class and everything works fine. But what I don't quite understand is that when the form is submitted, web browser automatically redirects me to the url specified by model's get_absolute_url() method. Is it a default behavior that 'success_url' field is at some point assigned by an url returned by that method? -
How to access google shopping api without open web browser using python/django script?
I want to access google shopping api without open web browser. Please specify the way to login to google account from command line and authorize google shopping api with proper example in python/django. -
How to generate a schedule booking table
I am currently working on a project that requires me to create a schedule from which users can book different periods. In practical terms, users need to have the possibility to subscribe to our services for the length of their choice (eg. from 4 to 7pm). Here is my question.. I would like to know what is the most efficient way to manage every subscription and to display all the data gathered. Is there any "plugin" that would allow me to manage this easily? Otherwise could you please tell me what is the best approach to adopt? At this stage, when they register, they can choose : - one day of the week - an hour of beginning - an hour of ending (Registration form --> http://www.leclubdesdevoirs.be/inscriptions/) In my opinion, the best is to tabulate the information. What do you think? And Could I implement this? Here is an example : ---------------- | student 1 | student 2 | student 3 | Student 4 | Total 16.00-16.15 |XXXXXXX |XXXXXXX |000000000|000000000| 2 students 16.15-16.30 |XXXXXXX |XXXXXXX |XXXXXXX |000000000| 3 students 16.30-16.45 |XXXXXXX |000000000|XXXXXXX |XXXXXXX | 3 students 16.45-17.00 |XXXXXXX |000000000|XXXXXXX |XXXXXXX | 3 students Where : - XXXXXXX means present - … -
Application Error occured when deploying django app with heroku
When I'm trying to deploy django app with heroku using git push heroku master it worked correctly. After that I used heroku open and I got an error on browser. Application Error An error occurred in the application and your page could not be served. Please try again in a few moments. If you are the application owner, check your logs for details. This is the error.How can I solve this error? -
Showing database in admin page model
I have a MySQL database. It has a table named "rqst". I want to show it in admin page. I mean I want to execute "SELECT * FROM rqst;" and show all columns with their values in the model. I really don't know which field I should use and how to perform it. I am using Django 1.10.1 Thanks -
How do I send a query parameter which have '+' in the string in the value
I have a webapp on django. My url is http://localhost?state=mCLap0iv7XYFOZBG/WKv/EZBAC6butVk2tuJC44o8q/6U6PdDbPhxPQl4cTxAmvU06/s1HpkpJWqwqK8fbWECoydMYQjOBqyOzhStK24pVhM3OUejfPLR4JVIwVO9VEAtL0DjToYArBcC8mG/3bm0LYmLUbwcrulTBsLtd+eSkY=&code=aa28b2256deeaf311fa4b4311807f4a I am getting this string by doing bin_data = RSAKey.encrypt(string) encoded_data = base64.urlsafe_b64encode(bin_data) On backend when I check the get parameter I get mCLap0iv7XYFOZBG/WKv/EZBAC6butVk2tuJC44o8q/6U6PdDbPhxPQl4cTxAmvU06/s1HpkpJWqwqK8fbWECoydMYQjOBqyOzhStK24pVhM3OUejfPLR4JVIwVO9VEAtL0DjToYArBcC8mG/3bm0LYmLUbwcrulTBsLtd eSkY= . Here"+" is getting replaced by " ". The string is encrypted by RSA in python. Basically I want to do a base64.urlsafe_b64decode(encoded_string) on the string. -
Django - multiplechoicefield save to more database rows
I have a ModelForm with a multiplechoicefield in Django. Is it possible to save every choice in a separate database row. Example ("Colors" is the multiplechoicefield): Name: Peter Colors: green, blue Rows in database: 1 | Peter | green 2 | Peter | blue -
Django Set custom field in form not required
Update Form class UpdateForm(forms.ModelForm): connector = forms.ModelChoiceField(queryset=Connector.objects.all(), widget=forms.Select(attrs={'disabled':'disabled'}), initial='multiplate') class Meta: model = Instrument fields = ['connector','name'] I have set initial value for the ChoiceField. But when i access the change of the model and Save, it prompt me "This field is required" for the field connector. How can I make the field not mandatory in this case? Because it will always have a value there. -
Is there any package or means to change existing templates as non blocking UI templates in Django
I am working in a Django(version-1.6) project. And I wanted to implement the Non-blocking UI for the existing templates. Right now the template structure is breaking when the page is loading for the first time. I wanted to implement it without using AngularJs or ReactJs or BackboneJs. I have gone through this blog and it says as if the above mensioned frame works are mandatory to accomplish this. I would be grateful for your help. Thanks in advance. -
Ealasticsearch results exactly as parameter
I'm trying to filter logs based on the domain name. for example i only want the results of domain: bh250.example.com. when i use the following query: http://localhost:9200/_search?pretty&size=150&q=domainname=bh250.example.com the first 3 results have a domainname: bh250.example.com where the 4th having bh500.example.com I have read several documentations on how to querry to elasticsearch but I seem to miss something. I only want results having 100% match with the parameter. so -
Passing value from ModelAdmin to ModelForm
InstrumentAdmin(admin.ModelAdmin) def get_form(self,request, obj=None, **kwargs): if obj: self.form = UpdateForm else: self.form = CreateForm return super(InstrumentAdmin,self).get_form(request,obj,**kwargs) How can i pass a value (value = 10) to UpdateForm in this case? And how I can get the value from ModelForm? I have look for a lot of example but still can't figure it out how it works. Appriciate for any help. -
How can I convert from Datetime to Milliseconds in Django?
I want to convert date (ex: 2016-09-20 22:00:00+00:00) to milliseconds. I will apply this block: def get_calendar_events(request): user = request.user taken_course = Course.objects.get_enrollments(user=user) homework_list = [] for course in taken_course: homework_list = course.get_homeworks() data_l = [] for homework in homework_list: data_l.append({ "id": user.id, "title": homework.title, "class": "event-important", "start": homework.start_date, # Milliseconds "end": homework.end_date # Milliseconds }) data = { "success": 1, "result": [data_l] } return JsonResponse(data, safe=False) I need to edit "start" and "end" tags in data_l. Thank you. -
Django - Ajax POST form not working
I'm making a POST form to rent books. Whenever the form is submitted, the status of the chosen book needs to be changed but for some reason I cannot get a successful post when trying to use ajax. This is my code: Form: <form id="Boek_uitlenen"> {% csrf_token %} <div class="form-group"> {# Boek uitlenen - Leerling selecteren #} <label for="Choose_member">Boek Uitlenen</label> <select class="form-control" id="Choose_member"> {% for Member in members %} <option value="{{ Member.Leerlingnummer }}">{{ Member.Leerlingnummer }} {{ Member.Voornaam }} {{ Member.Achternaam }}</option> {% endfor %} </select></div> {# Boek uitlenen - Boek selecteren #} <div class="form-group"> <div for="Choose_book" class="input-group"><span class="input-group-addon">ISBN13</span> <select class="form-control" id="Choose_book"> {% for Book in books %} <option value="{{ Book.ISBN13 }}">{{ Book.ISBN13 }} - {{ Book.Titel }}</option> {% endfor %} </select></div> </div> <button type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-menu-up"></span> Uitlenen </button> </form> This is my Jquery, located at the bottom of the page: <script type="text/javascript"> $("#Boek_uitlenen").on('submit', function (e) { var csrftoken = $.cookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function (xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); e.preventDefault(); $.post('/boek/uitlenen/', { Member: $('#Choose_member').val(), Book: $('#Choose_book').val() }).done(function (data) { console.log(data); }); return false; }); </script> This … -
Django context variable names for the templates
I'm doing Django's getting started tutorial and I'm on the generic views part: https://docs.djangoproject.com/en/1.10/intro/tutorial04/ where at one point it explains: "In previous parts of the tutorial, the templates have been provided with a context that contains the question and latest_question_list context variables. For DetailView the question variable is provided automatically – since we’re using a Django model (Question), Django is able to determine an appropriate name for the context variable. However, for ListView, the automatically generated context variable is question_list." My problem is that I don't know how Django determines this "appropriate names". I want to know this for when I write my own template. I would want to know what context variable names to use in such template. From what I can understand, if my model is Question, the "question" context variable would store that question, and the "question_list" context variable would store every question. So my doubt is: What other context variables names can I use? and what would they store? I can't seem to find this on the documentation, please redirect me to it if you know where it is. -
how to recuperate the data from a QuerySet with django
I'm totally new with django and I'm trying to recuperate data from database and then send it to the template so that data will be displayed in a table. I made a querySet and I got this response : <QuerySet [<name: Gen>,<name: Alen>]> when I displayed in the template I had the same string in my table. I would like to display only the name ' Gen ' and Alen in the table this is the table : <td> <ul> <li>{{teachers.name_list}} </li> </ul></td> could you help me please ? -
Django: Test content of email sent
I'm sending out an email to users with a generated link, and I wanna write a test that verifies whether the link is correct, but I can't find a way to get the content of the email inside the test. Is there a way to do that? If it helps at all, this is how I'm sending the email: content = template.render(Context({'my_link': my_link})) subject = _('Email with link') msg = EmailMultiAlternatives(subject=subject, from_email='MyWebsite Team <mywebsite@mywebsite.com>', to=[user.email, ]) msg.attach_alternative(content, 'text/html') msg.send() -
django : add a class to a model
I would like to add a class to a model the class is : class Essai_Fluage(models.Model): name = models.ForeignKey(Material, verbose_name=_('name')) elongation= models.FloatField(_('allongement'),blank=True, null=False) time = models.IntegerField_('temps'),blank=True, null=False) valT= models.FloatField(_('temperature'),blank=True, null=False) effort = models.FloatField(_('contrainte'),blank=True, null=False) def __unicode__(self): return '%s' % (self.name) class Meta: verbose_name = _('creep test') verbose_name_plural = _('creep test') ordering = ['elongation', 'time',] then I save after changing the model can I write python manage.py schemamigration monprojet --auto and after, python manage.py migrate monprojet -
How to make the following query in Django?
I have a bunch of users in a group. I also have a OneToOne relation with each user to a Profile model. I am trying to get all the users who are teachers in a specific school. I have a Teacher group so I filtered the users with teachers = User.objects.filter(groups__name='Teacher') The following is the profile model. class Profile(TimeStamped): user = models.OneToOneField(User) school = models.ForeignKey(School, blank=True, null=True) Let's say the instance of the school that I am trying to filter on is assigned on a variable called school. How can I now put a second filter on the teachers variable to find the teachers of ONLY a specific school. -
Django user.is_authenticated reversed
In my template if user is anonymous,it would show Register button. So I use {% if user.is_authenticated %} Log out {% else %} Log in But when I test it. It reversed. -
Django rest framework one to one relation Update serializer
I ' m beginner on django rest Frame work .i have a problem s from a long period i try to find a solution through many forums but unfortunately i didn't succeed .hope you help me models.py from __future__ import unicode_literals from django.contrib.auth.models import User from django.db import models class Account(models.Model): my_user=models.OneToOneField(User,on_delete=models.CASCADE) statut=models.CharField(max_length=80) date=models.DateField(auto_now=True,auto_now_add=False) def __unicode__(self): return self.my_user.first_name Now i want to update Account serilizer . Serializers .py class AccountUpdateSerializer(serializers.ModelSerializer): username=serializers.CharField(source ='my_user.username') class Meta: model= Account fields=['id','username','statut','date'] def update(self, instance, validated_data): print(instance) instance.statut = validated_data.get('statut', instance.statut) instance.my_username=validated_data['username'] return instance the error : enter image description here -
How to load million of rows in django admin
I have 10 of millions of data in database when I try load in the django admin I received timeout error I don't have any foreign key in the data, simple character data -
Unable to play mp3 file on browser using ajax
I uploaded files on my server.Now I want to play them.So i pull a file from server storage and pass it to the browser and try to play and download it.The response is received on the browser but audio player does not show up. Views.py def play_file(request) : file=Files.objects.get(id=37) fsock = open(r'C:\Users\rdoshi\storage\%s' %file.file_name, 'rb') response = HttpResponse() response['Content-Type'] ='audio/mp3' response['Content-Length'] =os.path.getsize(r'C:\Users\rdoshi\storage\%s' %file.file_name) response.write(fsock.read()) return response Index.html $.ajax({ method: 'GET', url: '/polls/play_file', //data: {'id': 37}, success: function (recvd_file) { //this gets called when server returns an OK response console.log("success"); this.mAudioData = recvd_file this.mAudioSrc = "data:audio/mp3;base64," + this.mAudioData; document.write("<audio id='myaudio' src='this.mAudioSrc' preload='auto'></audio>"); var x = document.getElementById("myaudio"); //x.src = this.mAudioSrc; x.load(); x.play(); }, }); } The ajax is unable to play the audio file throwing the following error undefined:1 Uncaught (in promise) DOMException: Failed to load because no supported source was found What am i doing wrong here?And if i have to download..do i add a content-disposition header and it will suffice?