Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - How to only save form to database if a specific field is NOT filled out (honeypot trap for signup spam)
I have recently been having some trouble with fake signups on my website signup form. I've decided the best way to deal with this is to create an 'invisible' honeypot form field. I have created this new 'fake' form field in my models.py and forms.py, I have rendered the field in my template, and I have hidden the field from real users using 'display: none' in my CSS. What I want to be able to do now is only save the form to the database if the 'fake' field is NOT filled out. For example, I want to do something like this: if form.is_valid() and fakeformfield.is_null(): instance = form.save(commit=False) instance.save() return redirect('thankyou') If you need to see my code just say and I will update the question. Any help would be much appreciated! -
Django-storages S3Boto3Storage makes HEAD and GET requests on read
I am using the S3Boto3Storage storage backend from the django-storages package in my Django application. I use the backend to handle large amounts of files in S3. When reading a file from the storage, the backend makes separate HEAD and GET requests. I am doing this operation many times, so I would prefer to skip the HEAD requests if possible. My read operation looks similar to this: class MyModel(models.Model): img = FileField() instance = MyModel.objects.filter().first() instance.img.read() I am using the default preload_metadata flag, which is False. Is there another setting that controls this behavior of the read method? My guess is that the HEAD request checks if the file exists before getting the file content. So maybe the HEAD call could be replaced with a try/except statement. But I could not figure out how to do that. -
How to save the attachment from an incoming email in Django's FileField?
I'm trying to save any attachments of incoming emails to a FileField in Django. The model looks like this: class Email(models.Model): ... attachment = models.FileField(upload_to='files/%Y/%m/%d', null=True, blank=True) ... def __unicode__(self): return self.contents[:20] I wrote this function to return the attachments. def get_attachments(email_object): attachments = [] for part in email_object.walk(): # content_type = part.get_content_type() content_disposition = part.get("Content-Disposition") if content_disposition and content_disposition.lower().startswith("attachment"): attachments.append(part) return attachments Now I have a list of instances of the email object, and I'm not sure how to save them as a file in the FileField. attachment.get_content_type() returns image/jpeg. But how do I go from here to making it somehting that can be saved in the file field? Thanks for all help. -
Duplicate regex syntax in urls Django
I have three buttons in a template. When clicked, each will perform a specific function from the views.py. With each, I send a PK in the url. My question is, they now all kind of have the same url and for that all the buttons access one method only. How do I fix this? Here is my code: In the template: <form method="GET" action="{% url 'register' activity.pk %}"> {% csrf_token %} <button onClick="return showLogoutMessage()" type="submit" class="btn btn-primary" id="Register">Register </button> </form> <form method="GET" action="{% url 'volunteer' activity.pk %}"> {% csrf_token %} <button onClick="return showLogoutMessage()" type="submit" class="btn btn-warning" id="Register">Volunteer </button> </form> <form method="GET" action="{% url 'cancel' activity.pk %}"> {% csrf_token %} <button onClick="return showLogoutMessage()" type="submit" class="btn btn-danger" id="Register">Cancel </button> </form> In views.py: def registerAttendee(request,pk): act = Activity.objects.get(pk=pk) act.save() attendee, _ = Attendee.objects.get_or_create(student=request.user) act.attendee.add(attendee) return redirect('home/#work') def registerVolunteer(request,pk): act = Activity.objects.get(pk=pk) act.save() volunteer, _ = Volunteer.objects.get_or_create(student=request.user) act.volunteer.add(volunteer) return redirect('home/#work') def cancel(request,pk): act = Activity.objects.get(pk=pk) act.save() attendee, _ = Attendee.objects.get_or_create(student=request.user) act.attendee.remove(attendee) return redirect('home/#work') In urls.py: url(r'^(?P<pk>\d+)', authentication_views.registerAttendee, name='register'), url(r'^(?P<pk>\d+)', authentication_views.cancel, name='cancel'), url(r'^(?P<pk>\d+)', authentication_views.registerVolunteer, name='volunteer'), Like I mentioned, the problem is when clicking any button, it performs the registerAttendee method only for all of them. -
py.test: Show local variables in Jenkins
Up to now we call py.test via Jenkins. If a test fails, we see the usual stacktrace like this Traceback (most recent call last): File "/home/u/src/foo/bar/tests/test_x.py", line 36, in test_schema_migrations errors, out)) AssertionError: Unknown output: ["Migrations for 'blue':", ...] It would be really great, if I could see local variables like in the django debug page (See https://djangobook.com/wp-content/uploads/figure2_3a.png). Is there a way to enable this? -
ElasticBeans/EB django, Can't access my server..
I deploy my server through http://docs.aws.amazon.com/ko_kr/elasticbeanstalk/latest/dg/create-deploy-python-django.html I created virtual environment. run my server "python manage.py runserver". initialized eb. "eb init -p python2.7 django-tutorial" created eb. "eb create django-env" oepn eb. "eb open" access through public dns But I can't access my server through the public DNS. This is my terminal and AWS instances AWS instances EB terminal Thank you! -
How to send javascript value to views.py django
I am trying to send a value from javascript to views.py function in Django. The code as following: <form name="myform" action="" method="get"> <button id="button" name="button" onclick="click()">send</button> <input type="hidden" id="data" name="data" value=""> <script> function click() { var d = 100 document.getElementById("data").value = d; document.myform.submit(); } </script> </form> In views.py, def views(request): #assume function name is views result = request.GET.get("data") , but this method is failed, please guide me. -
How to retrieve exact label values from a checkbox using django html tables
Here is my code for the checkbox. At the moment I retrieve all labels in each of the rows. <table id="mytable"> <tr> <p><label for="id_q">Enter Gene:</label> <input textarea name="Text1" cols="40" rows="5" name="q" type="search" value="CYP17A1" /></p> <p><label for="id_models_0">Disease:</label> <ul id="id_models[]"><td><li><label for="id_models_0"><input checked="checked" id="id_models_0" name="models" input type="checkbox" value="predictgene.amyotrophic_lateral_sclerosis_motor_neuron_disease" /> ALT</label></li></td> <td><li><label for="id_models_1"><input id="id_models_1" name="models[]" input type="checkbox" value="predictgene.arthrogryposis" /> AR</label></li></td> <td><li><label for="id_models_2"><input id="id_models_2" name="models[]" input type="checkbox" value="predictgene.congenital_myaesthenia" /> CM</label></li></td> <td><li><label for="id_models_3"><input id="id_models_3" name="models[]" input type="checkbox" value="predictgene.early_onset_dystonia" /> ED</label></li></ul></p></td> <br/><br> </tr> <button id="save">Click</button> </table> -
Stripe: Error "This application is not authorized to edit this account" while updating the account in stripe
I am very new the stripe & stripe API, right now am integrating the stripe into the django python server. I am able to create the customers & accounts. While updating the account with the bank token, I got an error "This application is not authorized to edit this account". I am able to see the connected accounts on the connected accounts page in stripe dashboard. Here is my code where I got the issue when account.save() try: account = stripe.Account.retrieve(user_account_id) account.external_accounts = bank_account_token account.save() except Exception as e: retrun e.message return account -
Download (PDF format) using Django
I am Trying to add download option(pdf format) it works fine but when I open downloaded the file it looks like a page only 1 line is visible, but when I copy that content and paste somewhere else there total content is visible. can anyone help me to overcome this issue HTML: <div class="dropdown-menu dropdown-primary pull-right" id="dashboard_download_button" aria-labelledby="dropdownMenu"> <a class="dropdown-item waves-effect waves-light download-file" id="csv" href="#"><i class="fa fa-file-excel-o download-icons"></i>&nbsp;&nbsp;CSV</a> <a class="dropdown-item waves-effect waves-light download-file" id="json"href="#"><b class="download-icons">&#123;&nbsp;&#125;</b>&nbsp;&nbsp;JSON</a> <a class="dropdown-item waves-effect waves-light download-file" id="pdf" href="#"><i class="fa fa-file-pdf-o download-icons">&nbsp;&nbsp;PDF</i></a> </div> JavaScript: var download_url = '/download/' + '?term=' + search_term + '&' + 'server=' + encodeURIComponent(server) + '&' + 'results=' + encodeURIComponent(results) + '&occurrence=' + occurrence; //download link for pdf format var pdf_href = $('#pdf').attr('href',''); var pdf_format_link = download_url + '&' + 'type=' + 'pdf'; $('#pdf').attr('href', pdf_format_link); Views.py (Items a list - the content which I want to download): response = HttpResponse(content_type = 'application/pdf') response['Content-Disposition'] = 'attachment; filename=%s'% smart_str(fname) p = canvas.Canvas(response) p.drawString(100,100,"\n".join(str(x) for x in items)) p.showPage() p.save() return response -
Celery worker doesn't see tasks from a specific Django app
Can't understand why celery worker suddenly stopped discovering tasks from a specific app, i.e. it can find all tasks except the ones from the app (though it worked fine some time ago, no changes were made to the settings). Has anyone ever encountered this problem before? -
Django: How to show all images in images model
I am trying to show all images associated with the currently selected user This is built off of this solved question: django upload to image model with foreign key to user Model.py class Images(models.Model): image = models.ImageField(upload_to='profile_image', null=True, default='profile_image/none/no-img.png') user = models.ForeignKey(User, on_delete=models.CASCADE) Views.py @login_required def index_account(request): args = {'user': request.user } return render(request, 've/cp/index_account.html', args) Template > index_account.html <p><a href="{% url 've:edit_images' %}">Edit your images</a></p> # test to see if it worked w/o if {{ user.images.image}} # ideal solution {% if user.images.images %} {% for img in user.images %} <img src="{{ user.images.image.url }}"><br> {% endfor %} {% else %} <p>No images</p> {% endif %} <br> <hr> -
How to run the same Django test for different datasets?
I want to run the same exact test in a django.test.TestCase for different datasets: class MyTestCase(django.test.TestCase): fixtures = ['datasets.json'] @classmethod def setUpTestData(cls): super(MyTestCase, cls).setUpTestData() self.datasets = [] # get from fixtures def test(self): for dataset in self.datasets: self._test_dataset(dataset) def _test_dataset(self, dataset): # peforms the actual test for the given dataset self.assertEquals(...) How can I do that in a more elegant way? Does Django test framework provide a tool to do this? The main issue is determining what dataset has failed, if the test fails. Since my example uses a for loop that would not be easy unless we used additional statements. Let me mentioned that I found out that this can apparently be done with pytest, but I am using django.test here. -
Django create a register page which contains extra field
I am trying to create a register page which located www.mysite.com/register and contains "username,email,password" as usually and extra (gender,dateofbirth,workposition). Firstly i tried to make this by using this code but i failed. How can i create a Profile and RegisterPage which is using same User? in my accounts/forms.py class RegisterForm(forms.ModelForm): username = forms.CharField(max_length=100, label='Kullanıcı Adı') password1 = forms.CharField(max_length=100, label='Parola', widget=forms.PasswordInput) password2 = forms.CharField(max_length=100, label='Parola Doğrulama', widget=forms.PasswordInput) GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES) class Meta: model = User fields = [ 'username', 'password1', 'password2', 'gender', ] in my accounts/views.py def register_view(request): form = RegisterForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) password = form.cleaned_data.get('password1') user.set_password(password) # user.is_staff = user.is_superuser = True user.save() new_user = authenticate(username=user.username, password=password) login(request, new_user) return redirect('home') return render(request, "accounts/form.html", {"form": form, 'title': 'Üye Ol'}) -
WebGUI Deployment with Python and Bash
I would like to build a simple webGUI interface for Python/Bash execution scripts running on a Linux VM. My ultimate idea is to create a Docker container out of it for easy deployment. So in principle, the website will have some input fields and depending on the input it should show the output fields, allow the ability to export the data in different formats and plot some graphs. It would be great if the webGUI has also responsive design, but it is not a must. The website should also support setting some parameters on remote machines using HTTP PUT/POST REST API and display the output of REST API GET requests. I have so far created command line bash script doing just this, but it requires access to the command line and it is not very user friendly, that's why I am looking for a way to put all this functionality on a webGUI. Do I need to re-write my script in Python, or I can still use Bash? I am a beginner, but I feel comfortable with Linux command line, Python and bash scripting. I just don't know what to use for the underlying web platforms. I was thinking that … -
Django optimistic concurrency on save - is it possible?
I don't currently have optimistic concurrency implemented in my application. Only the version field that gets updated on each save. However, all my form edits are implemented with save and not update. Is it possible to implement optimistic concurrency with save or I have to rewrite every edit method to update? (See this article https://invalidpatent.wordpress.com/2016/08/03/two-approaches-to-concurrent-write-safety-in-django/ it claims only update can be used) -
Django OAuth2 authorization server setup
I found django-oauth-toolkit, which I think will serve my purpose.As I'm new to Django, Oauth documentation seems confusing to me. DhaWhat I am trying to achieve is to link Alexa smart home skill with Django user accounts.Thus registered users will be able to use my smart home skill after completing account linking from Alexa app. From my research, I found that I need to create an authorization server for Alexa smart home skill and grant Alexa to access to User's data. So how can I create a such an Authorization server.? -
Run DJango server from outside of virtual environment by using script
I have created DJango Project inside virtual environment. Let's say virtual environment DJangoProject project name is Mysite I am tired of running ./manage.py runserver everytime so that I wanted to automate running server when I was logged into ubuntu.I tried many ways but was always failing to access the path of virtual environment. So help me to run manage.py runserver from outside of virtual environment using bash or shell scripting. any help can be appreciate! -
How to create queryset expression containing different types
I have two models like: class Category(models.Model): title = models.CharField(max_length=100) expires_in_days = models.PositiveIntegerField(default=20) class Item(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100) description = models.TextField() category = models.ForeignKey(Category) And I need to determine which items I should set expired: items_to_cancel = Item.objects.annotate(expires_date=F('created') + F('category__expires_in_days'))\ .filter(expires_date__lte=timezone.now().date()) Running this query raises an exception: FieldError: Expression contains mixed types. You must set output_field. Adding days to date is valid operation in Postgres, and since I have a simple arithmetic operation here, I don't understand where I should add this output_field parameter. And if I won't be able to get expiration date this way after all, how can I do it with raw SQL? -
Is there a way to constraint the together value in Serializer?
I have a EmailCreateSerializer, I can let creator pass receive_group id or receive_user id for send to them: class EmailCreateSerializer(Serializer): receive_group = serializers.IntegerField(allow_null=True) receive_user = serializers.IntegerField(allow_null=True) Either pass the receive_group (send to a group), or receive_user (send to single user). But I want to one of them (receive_group, receive_user) must be not null. Is there a way to realize it in Serializer? -
Django multiple template rendering
At the moment I'm working on a pretty complex page with multiple areas that need to be updated upon user input. My thought is to render multiple extend/include templates that are each responsible for their own part of the webpage.However, I face a few problems: I need multiple view functions to process data for all templates. I need to pass the request to multiple view functions so that they return the template with the correct data One of the functions not only takes the request but also the slug of a model object to update data on the page. Questions: How do I send responses/data from different view functions to each other? How do I pass the request to multiple functions? Does the rendering of the extends also make sure that the base.html is rendered? Are extends the right thing to use or should I use includes? So far I have thought of this system: base.html <body> {% block extend1 %} {% endblock %} {% block extend2 %} {% endblock %} {% block extend3 %} {% endblock %} </body> extend1.html (example for the 3 extends) {% extends base.html %} {% block extend1 %} #html code {% endblock views.py def extend1(request): … -
error while filtering data as per columns in django template
I am using Django template to display a table and I wish to filter data based on columns In order to do so, I have taken two var q and r in my javascript function go(){ // alert("hellonikhar"); var q = document.getElementById("search").value; var r=document.getElementById("columnName").value; window.open("/?q="+q+r,"_self"); (i guess some error is here only) } In my home.html I have made a text-field and a dropdown menu <input type="text" class="text_field" id="search" placeholder="Search for..." required> <select name="columns" id="columnName"> { <option value="{{column.name}}"> Customer Name</option> <option value="{{column.name}}"> Status</option> <option value="{{column.name}}"> Product</option> <option value="{{column.name}}"> OS Type</option> <option value="{{column.name}}"> Server Type</option> <option value="{{column.name}}"> L3</option> <option value="{{column.name}}"> Version</option> <option value="{{column.name}}"> PM</option> <option value="{{column.name}}"> CDM</option> } </select> <input type="button" class="button" onclick="go()" value="go" id="submit"> <input type="button" class="button" onclick="exp()" value="export" id="exp"> I have defined a function in my views.py to check the value of r from the dropdown and q when the go button is clicked but the data is not filtered based on those columns def user_profile(request): q = request.GET.get('q','') custom = Customer.objects.all() r= request.GET.get('r','') if (q and r=="Status"): custom1=custom.filter(name__contains=q) currently i am just testing when the value in the dropdown is status -
Save user language in a model through default() with Django
I would like to save the language of the user each time a new model instance is created: models.py: def getlanguage(request): lang = request.LANGUAGE_CODE return lang class Comment(models.Model): language = models.CharField(max_length=100, blank=True, default=getlanguage) Django generates the following error: TypeError: getlanguage() takes exactly 1 argument (0 given) How to pass the request to the function? Thank you! -
Django redirect from inside a view
I'm using django 1.11.8. I need to perform some check on the requested view and inside it redirect the user to another Http page, but this code fail, as the redirect is ignored. What am I missing? class ThisCreateView(CreateView): def get_form_kwargs(self): if self.kwargs['x'] == 1: return redirect(reverse('this_app:this_list')) return kwargs -
django rest framework installation fails
How do I install the REST framework in django? The following command throws an error on Mac OSx: pip install djangorestframework-jsonapi Could not find a version that satisfies the requirementdjangorestframework-jsonapi (from versions: ) No matching distribution found for djangorestframework-jsonapi