Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to hide button/form with django templates?
I want to hide form if user already pushed on the button. I tried to use a bit of JS code, it works well, but after refreshing page, button on form stay valid. It not a huge surprise for me)) I want hide form using Django templates, but it is not so easy as I thought. my html : <div class="who_come"> <p>Who come : </p> {% for u in who_come %} {%if u.visiter.username != request.user.username %} <form class="form-inline" role="form" method="post" id="joinToEventForm"> {% csrf_token %} <p align="left"><b ><button type="submit">I want join</button></b></p></b></p> </form> {% endif %} {% endfor %} <div id="who_come_links"> {% for u in who_come reversed %} <p><a href="profile/{{u.visiter.username}}" title="{{u.visiter.first_name}} {{u.visiter.last_name}}">{{u.visiter.username}}</a></p> {% endfor %} </div> <script> $('#joinToEventForm').submit(function() { $(this).find("button[type='submit']").prop('disabled',true); }); </script> <script> $('#joinToEventForm').on('submit', function(event){ event.preventDefault(); console.log("form submitted!") // sanity check $.ajax({ type:'POST', data:{ action: 'joinEvent', csrfmiddlewaretoken:'{{ csrf_token }}' }, success : function (data) { //console.log(data); var usernames = JSON.parse(data); var html_str = ''; for (var i=0; i < usernames.length; i++) { html_str += '<p><a href="profile/' + usernames[i] + '">' + usernames[i] + '</a></p>'; } $('#who_come_links').html(html_str); } }); }); </script> </div> my model : class WhoComeOnEvent(models.Model): visiter = models.ForeignKey(User, related_name='WhoComeOnEvent') which_event = models.ForeignKey(Topic, related_name='WhoComeOnEvent') in this place : <p>Who come : </p> … -
Django Binding POST request to class-based view
I am trying to build a class based view to handle a review/update form. The form is built with the following code for the form: class ProcesoCandidato(forms.Form): '''''' hrfrmreclutado_nombres = forms.CharField() hrfrmreclutado_se_presento = forms.ChoiceField( choices=()) hrfrmreclutado_cambio_de_cita = forms.DateField() hrfrmreclutado_entrevista = forms.ChoiceField() hrfrmreclutado_contratado = forms.ChoiceField() hrfrmreclutado_motivo_de_rechazo = forms.ChoiceField() hrfrmreclutado_notas = forms.CharField() def clean(self): '''''' cleaned_data = super(ProcesoCandidato, self).clean() clnfrmreclutado_nombres = \ clnfrmreclutado_se_presento = \ self.cleaned_data.get('hrfrmreclutado_se_presento', '') clnfrmreclutado_cambio_de_cita = \ self.cleaned_data.get('hrfrmreclutado_cambio_de_cita', '') clnfrmreclutado_entrevista = \ self.cleaned_data.get('hrfrmreclutado_entrevista', '') clnfrmreclutado_contratado = \ self.cleaned_data.get('hrfrmreclutado_contratado', '') clnfrmreclutado_motivo_de_rechazo = \ self.cleaned_data.get('hrfrmreclutado_motivo_de_rechazo', '') clnfrmreclutado_notas = \ self.cleaned_data.get('hrfrmreclutado_notas', '') def __init__(self, *args, **kwargs): '''''' super(ProcesoCandidato, self).__init__() self.fields['hrfrmreclutado_se_presento'].choices = [ ('', '------'), ('Si', 'Si'), ('No', 'No'), ] self.fields['hrfrmreclutado_entrevista'].choices = [ ('', '------'), ('Si', 'Si'), ('No', 'No'), ] self.fields['hrfrmreclutado_contratado'].choices = [ ('', '------'), ('Si', 'Si'), ('No', 'No'), ] self.fields['hrfrmreclutado_motivo_de_rechazo'].choices = \ [('', '------')] + [(c.pk, c.razonrechazo) for c in models.RazonRechazo.objects.all()] The views file contains a class based view to handle the GET and POST methods: class ProcesoRH(View): '''''' form_class = ProcesoCandidato initial = { 'procesorh_llego': 'No', 'procesorh_entrevista': 'No', 'procesorh_contratado': 'No', 'procesorh_rechazo': '', 'procesorh_notas': ''} template_name = 'sitio_rh/rhprocess.html' def get(self, request, *args, **kwargs): reclutadoid = request.GET['candidato'] procesodata = models.ProcesoRH.objects.filter( procesorh_reclutado_id=reclutadoid) if procesodata.exists() is False: objproceso = models.ProcesoRH() objproceso.procesorh_reclutado_id = reclutadoid objproceso.save() else: … -
Ajax not firing after I added a GeoJson 'data'
I have an HTML page where a button click will fire an ajax function showDetail(): <a href="#" class="list-group-item" onclick="showDetail({{ test.id }});"> <strong>{{ test.test_name }}</strong></a> The ajax function works well if it's like this on its own: function showDetail(id){ $.ajax({ url : "/test/" + id, type: 'GET', success: function(data){ map.removeLayer(tests); $('#pane-content-edit').html(data); $('.tests_display').animate({right:0}); } }); } I would like to modify it having the current HTML page containing a Geojson. And I'd like to pass it to my ajax to pass it to the url my ajax is pointing at. So I did this: function showDetail(id){ $.ajax({ url : "/test/" + id, type: 'GET', data: {'tests_geojson' : {{ tests_geojson | safe}}}, success: function(data){ map.removeLayer(tests); $('#pane-content-edit').html(data); $('.tests_display').animate({right:0}); } }); } After adding that, it would not fire. I tried opening up the web console, nothing is happening. Can someone help? or tell me how to debug this? Thank you! Edit: Additional info - Django Framework templating Contents of test_geojson showing on Leaflet map so it's most likely validated: Big geojson feature but would look generally like so: alert(JSON.stringify(geojsonFeature)); { "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": {"type": "Point", "coordinates": [102.0, 0.5]}, "properties": {"prop0": "value0"} }, { "type": "Feature", "geometry": { "type": "LineString", … -
Date range query in django
I have a calendar table in MySQL in the following format. I have only shown 3 rows but there are thousands of rows in the same format. Name Period Indicator Value ACV 2007-01-07 Actual 0.00 TV 2007-01-14 Actual 0.00 Print 2007-01-21 Actual 0.00 MySQL is linked to Django. I want to write a web service in Django such that data for the first 60 days is displayed. This web service will be linked to an HTML component. So each time I click Next I want the web service to display data for the next 60 days. If I click on previous I want it to display data for the previous 60 days. Can someone help me achieve this? -
django admin related Field got invalid lookup: icontains
I got these Models: @python_2_unicode_compatible class Media(models.Model): the_image = FilerImageField(null=True) title = models.CharField(verbose_name="Title", max_length=255, null=True, blank=True) alt_text = models.CharField(verbose_name="Alt Text", max_length=255, null=True, blank=True) created = models.DateTimeField(default=now) modified = models.DateTimeField(editable=True, auto_now=True) product_image_gallery = models.ForeignKey('Product', related_name="product_image_gallery", null=True, blank=True, verbose_name="Product's Image Gallery") def __str__(self): return self.the_image.__str__() @python_2_unicode_compatible class Product( models.Model ): name = models.CharField(verbose_name="Name", max_length=255) slug = models.SlugField(verbose_name="Slug", max_length=255, unique=True) price = models.PositiveIntegerField(verbose_name='Price', null=True, blank=True) sale_price = models.PositiveIntegerField(verbose_name="Sale Price", null=True, blank=True) sku = models.CharField(verbose_name="SKU", max_length=255) def __str__(self): return "%s" % (self.sku, ) I have these Admin Objects: class Media_Admin(admin.ModelAdmin): search_fields = ['id', 'the_image', 'title', 'product_image_gallery__sku'] list_display = ['the_image', 'image_tag', 'title', 'product_image_gallery', 'created'] readonly_fields = ('image_tag',) fieldsets = [ ( "Data", { 'classes': ('grp-collapse grp-open',), 'fields': ['the_image', 'title', 'alt_text']}), ] admin.site.register(Media, Media_Admin) The list_display works fine but the search always gives an error saying "Related Field got invalid lookup: icontains" I don't know what i did wrong, i use double underscore for the SKU "product_image_gallery__sku", but it still gives an error, i tried "product_image_gallery" it is also an error. -
Moving an current DJango app to a different sub-directory
I have an app that was created in an "old" directory using "django-admin startproject businesscontacts" old location: C:\Users..\backendworkproj\businesscontacts moved to new location: C:\Users..\backendworkproj\appmasterdata\businesscontacts Now, of course, the app that was working is now broken. My understanding is that "C:\Users..\backendworkproj\appmasterdata" needs to be put in the PYTHONPATH. I know that there are other explanations out there - but - I am trying to follow one of the responses listed here: Permanently add a directory to PYTHONPATH It says: Instead of manipulating PYTHONPATH you can also create a path configuration file. First find out in which directory Python searches for this information: To me, it is not clear exactly what is to go into the .pth file. I did not see anything stating whether or not a full-path is needed or a realtive-path or ... In my case, 1. run python -m site --user-site output => C:\Users\...\AppData\Roaming\Python\Python36\site-packages 2. Made sure that the directory existed 3. echo "$HOME/foo/bar" > "$SITEDIR/somelib.pth" Again, not sure what is supposed to be in the .pth file - or - what the name of the file should be (with Step #3) TIA -
The current path, didn't match any of these. error django
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/votes/ Using the URLconf defined in votes.urls, Django tried these URL patterns, in this order: ^$ [name='index'] The current path, votes/, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. this is my urls.py of my app. from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] this is my urls of my entire project from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^votes/', include('votes.urls')), url(r'^admin/', admin.site.urls), ] I tried to approach to admin site but i couldn't. how can I fix it? -
The compressed avatar image getting "rotate" in Python
I have added the image compression code for Avatar in my application. But sometimes it saving the uploaded image as "rotate". Please check the below code, import Image, ImageFile pic = "pic/goes/here.jpg" im = Image.open(pic) width, height = im.size if width > 1000 or height > 1000: width = width*.7 height = height*.7 im = im.resize((int(math.floor(width)), int(math.floor(height))), Image.ANTIALIAS) try: im.save(pic,optimize=True,quality=70) except IOError: ImageFile.MAXBLOCK = width * height im.save(pic,optimize=True,quality=70) Do i need to update something or Any other alternative method to resize the image upload for AVATAR ? -
Is it good approach not to use Database in Django
We are developing website with Django as front-end & Salesforce NPSP as the back-end. We are asked not to use any of the Database like SQLite or MYSQL & data management will be completely handled by Salesforce. a) Is it good idea to do the above? b) You want certain pages to be access only by logged-in users, I was planning to use decorators @login_required (which work only with DB at the back-end) How to achieve this functionality with Salesforce as back-end? c) I need to share user data between several pages, directly approach would have been to use the User object but with no DB i will be forced to use session variables. Is any other was possible to achieve this? Any other suggestions in the above area are welcomed. -
file uploading Django code not working from /var/www/
def upload(request): print(request.FILES) if request.POST and request.FILES: files = request.FILES print(files) for file in files: data = files[file] with open('/tmp/%s' % data.name, 'wb+') as dest: for chunk in data.chunks(): dest.write(chunk) return render(request, "create.html") return HttpResponse("Failed to Upload") Above code works from when Django project is in root folder. but when I push the code to /var/www/ folder the same code not working. for request.FILES I am not getting the files uploaded in the output. Not able to understand where code is missing. can anyone help me out finding out what is the issue -
deleting the parent (primary) values when deleting the inline value django admin?
when i am trying to delete the values in inlines using django admin , the primary key objects are deleting,please solve my problem.Thanks in advance. -
How to get just list of ids in ManytoMany Field
class Task(models.Model): title = models.CharField(max_length=80) asignee = models.ManytoManyField(User) Is there an efficient way of getting just the 'id's of the users assigned to a task? I dont want to use this - task.asignee.valueslist('id', flat=True) The asignees will be from a limited list and already available. So there is no need to get to the user level. But I need the ManytoMany relation for reverse lookups. TIA -
Using python 3.6 on azure app services - not working despite it is installed as extension
I've got a challenge with deploying Django app (wagtail to be precise) to Azure Web Services using external Git repo (Bitbucket). I want to use Python 3.6.1, therefore I followed instructions at Managing Python on Azure App Service manual I have python 3.6.1 extension installed and in place I created web.config file in root directory of my app (I checked and it is uploaded to the server) However, deploy fails with message Detecting Python runtime from runtime.txt Unsupported runtime: python-3.6.1 Supported runtime values are: python-2.7 python-3.4 An error has occurred during web site deployment. \r\nD:\Program Files (x86)\SiteExtensions\Kudu\66.61008.3066\bin\Scripts\starter.cmd "D:\home\site\deployments\tools\deploy.cmd" My web.config file <?xml version="1.0" encoding="utf-8"?> <configuration> <appSettings> <add key="PYTHONPATH" value="D:\home\site\wwwroot"/> <!-- Django apps only --> <add key="WSGI_HANDLER" value="django.core.wsgi.get_wsgi_application()"/> <add key="WSGI_LOG" value="D:\home\LogFiles\wfastcgi.log"/> </appSettings> <system.webServer> <handlers> <add name="PythonHandler" path="*" verb="*" modules="FastCgiModule" scriptProcessor="D:\home\python361x64\python.exe|D:\home\python361x64\wfastcgi.py" resourceType="Unspecified" requireAccess="Script"/> </handlers> </system.webServer> </configuration> Paths are ok, below is ls from Kudu console D:\home\python361x64>ls DLLs Lib Scripts __pycache__ python.exe python3.dll python36.dll pythonw.exe sitecustomize.py vcruntime140.dll wfastcgi.py It looks like the deployment process is not taking into account the web.config file that I have, or the python version that I've installed via extensions is not visible. Could you please tell me where the possible issue could be? Best regards, Konrad -
Can I run django server ingnore part of the project in Django?
Can I run django server ingnore part of the project in Django? I have a Django project with several apps, and one of the apps is need to import openstacksdk(because it relay on many linux libs, in Mac env is very troublesome ), so I must work in the Linux operate system. but now I have done that app which must import openstacksdk. Now I cloned the project from Linux to my mac, there will report error which related to openstacksdk. This is the directory of my project: So, is there a way only to debug the apps that do not contain the openstacksdk-related app? -
How to get values of choicefield using raw query from Django?
I am trying to get values of choicefield from table of database using raw query but it doesn't work with notification 'NameError was unhandled by by user code' What was wrong? Here is forms.py class SearchForm(forms.Form): validflg = forms.ChoiceField(label=("Names:"), choices = names(), widget = forms.Select({'class':'form-control'})) def get_names(): cursor = connection.cursor() get_query = str("SELECT distinct name from T_STUDENT") cursor.execute(get_query) results = cursor.fetchall() names = [] i=0 for row in results: names[i]=row[0] i+=1 return names def names(): data = get_names() i=0 names= [] for key,value in data: names.append(('i',value)) i+=1 return names -
httpd and mod_wsgi ran with wrong python version
I am deploying django project with httpd on RHEL7. And changed the system default python version to python3.4. But after I restarted the httpd, it still used python2.7. I searched a lot and it mostly because of mod_wsgi was built under wrong python version. However, I checked that mod_wsgi was installed under python 3.4. May I know how to make it run under the correct python version? Not too sure if httpd has default python version... Thanks very much for your help! enter image description here -
Forbidden (CSRF token missing or incorrect.) - even though it's included
I keep getting the above error even though I have included a csrf_token already. I've used the same csrfmiddlewaretoken for my other ajax calls and it works fine but here im getting the forbidden error. Any idea why? Here's my form: <form method="post" enctype="multipart/form-data" id="profileImageForm">{% csrf_token %} <label for="id_banner_image" class="change_profile_img">change <input id="id_banner_image" type="file" name="image" /> </label> <input type="submit"> </form> Here's my JS: $(document).on('submit', '#profileImageForm', function(e){ e.preventDefault(); var form_data = new FormData(); var image = document.getElementById('id_banner_image').files[0].name; form_data.append('file', image); $.ajax({ type:'POST', url: '/change_banner_image/', data : { form_data: form_data, csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val(), }, cache: false, contentType: false, processData: false, success: function(response){ console.log('Success'); }, }); }); -
get access to serializer validated data DRF
all the django rest framework docs assume your going to instantly save the data. But what if I want access to the serializer data? What if I want to do something with it. Or if the serializer contains info other than what I need to save in a model? is the validated_data attribute what we need? So validatedData = serializer.validated_data userid = validatedData.get('id') would work right? -
DJango CreateView not setting DB Key with Class-Based Views
I am using CreateView from DJango to save data to the DB. To do this, I am following the instructions here: Form handling with class-based views According to my understanding, after the data is saved to the DB, the control is to be passed to a type of "success screen" - in this case, for my scenario, control is to be passed to a "details page". The details page is represented by the following URL: url(r'^owner/(?P<pk>[0-9]+)/contact/details/$', views.MstrstoreheadcontactDetailsView.as_view(), name='owner-contact-details'), Below (in the class Mstrstoreheadcontact) the "details page" is being called by the get_absolute_url function (which is part of the Mstrstoreheadcontact model) from the models.py file class Mstrstoreheadcontact(models.Model): tenantid = models.ForeignKey('Mstrauthowner', models.DO_NOTHING, db_column='tenantid', blank=True, null=True) contactid = models.BigIntegerField(primary_key=True, default=0) genderid = models.BigIntegerField(blank=True, null=True, default=0) firstname = models.CharField(max_length=20, blank=True, null=True) lastname = models.CharField(max_length=20, blank=True, null=True) officephoneno = models.CharField(max_length=20, blank=True, null=True) cellphoneno = models.CharField(max_length=20, blank=True, null=True) class Meta: managed = False db_table = 'MstrStoreHeadContact' def get_absolute_url(self): return reverse('masterdata:owner-contact-details', kwargs={'pk': self.contactid}) For me the code: return reverse('masterdata:owner-contact-details', kwargs={'pk': self.contactid} is supposed to take the control to the "details page" that will display the new record that has been added to the DB. The problem When the code above is executed, the variable self.contactid is set … -
How develop django or python3 payment in china?(wechat pay and alipay)
I'm the new guy with the python django framework developer , I don't know how to connect or get the China payment in my django -
Django rendering a db field in the template
Could anyone correct my code? Background: The user, once on the 'start.html' template, will enter their name and press submit. Then on the next template, 'game.html', there should be a paragraph tab that contains that users name. Problem: I must be writting something incorrectly because the user's name does not render on the 'game.html' template. Or, I could also be storing it wrong. Any suggestions or corrections would be very appreciated! models.py - fp from django.db import models class User(models.Model): #first player name fp_name = models.CharField(max_length=30, default='') forms.py - I'm not sure if this is actually needed...? from django import forms class PlayerInfo(forms.Form): fp_name = forms.CharField(max_length=30, label='First player name') views.py - from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, render_to_response import os from .forms import PlayerInfo from .models import User def index(request): return render(request, 'index.html') def start(request): if request.method == 'Post': form = PlayerInfo(request.POST) if form.is_valid(): obj = User() obj.fp_name = form.cleaned_data['fp_name'] return HttpResponseRedirect('/') else: form = PlayerInfo() return render(request, 'start.html') def game(request): return render_to_response('game.html', {'obj': User.objects.all()}) start.html - Meant to submit player one's name {% extends 'base.html' %} {% block botRow %} <form method="post"> {% csrf_token %} <label for="fp_name">First Player Name</label> <input id="fp_name" type="text" name="fp_name" maxlength="30" required /> … -
Saving Blog in Django with figure, Space, paragraph, link
I am from embedded field but trying to learn web development and using Django for this purpose and using Postgresql as a back-end database. Questions can be silly but please understand that my level is beginner. I am making one website in which user can write new blog entries. For this purpose, I am using Textarea to let user write the blog entry. My questions are 1) Is there any good text editor which i can embed in my website and let user write their entries. Right now, i can only write text but can't choose the font, upload pic, or format the text. 2) I am thinking to store the link to figure in the database and uploading the pic to the google drive or dropbox. is this good practice? can you recommend some other method? 3) How can i let the text saved in the database to know when to start a new paragraph? HTML tag will be enough, or do i need to use some other method? -
Is it possible to trace back 403 error during ajax request in Django Rest Framework?
I'm trying to make an ajax call with DRF and each time receive: [20/Oct/2017 13:35:24] "OPTIONS /test/ HTTP/1.1" 403 82 I can't understand the reason of this error(I disable csrf by decorators and by middleware). Is it possible to raise exception instead of 403 response in Django to find out which middleware and and which code line return 403 error? -
Error trying to create Generic Relation
Hi I'm trying to create a GenericForeignKey Relation to link a reviews model to a set of location classes of different types of locations.. So I class museum, restaurant, park, industry, zoo, etc. which all inherit from an abstract class 'Location' and i want to be able to submit reviews for all the different locations saved for these types.. This is what I have so far in models.py: from django.db import models from django.contrib.auth.models import User from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericRelation class Location(models.Model): name = models.CharField(max_length=50) lat = models.FloatField() lng = models.FloatField() address = models.CharField(max_length=80, unique=True) city = models.ForeignKey(City, on_delete=models.CASCADE) email = models.EmailField(blank=True) # Below the mandatory fields for generic relation content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() class Meta: abstract = True class Reviews(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) review = models.CharField(max_length=200) reviews = GenericRelation(Location) def __str__(self): return self.name class College(Location): departments = models.CharField(max_length=200, blank=True) def __str__(self): return self.name class Industry(Location): type = models.CharField(max_length=50, blank=True) class Meta: verbose_name_plural = 'Industries' def __str__(self): return self.name class Hotel(Location): phone = models.CharField(max_length=15, blank=True) def __str__(self): return self.name I want to create a character text field in the reviews class (and use that for … -
How to save an array of object in DRF
I have this type of json: { "word" : "world", "days" : [1, 3, 7] } And DRF gives me this error: 'days': [{'non_field_errors': ['Invalid data. Expected a dictionary, but got int.']}, This is my days serializer: class DaysSerializer(serializers.ModelSerializer): class Meta: model = Days fields = ('day') And this my top level serializer: class WordsSerializer(serializers.ModelSerializer): days = DaysSerializer(many=True) class Meta: model = Words fields = ('word', 'days') I read that I need to use bulk serializers. Is that the route that is recommended today? Or there is a simpler way? If I need to use the bulk serializer library, I don't understand from their example how do I use that library for my purposes? Namely to (bulk) save the many to many entries (the Days) in one of the records (the Word).