Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why recursive Ajax call throws CSRF error?
I'm using an Ajax function to delete some model instances in the database. The user submits his criteria to get the object, if only one is found it's deleted, if not the view returns serialized form so that the user can choose the one he wants to delete. When these forms are submitted, the view code executes (so my model instance is deleted) but Django throws a CSRF token error. I'm using Django documentation way to get and send CSRF token and it's the first time I face this kind of behavior. Below is related simplified JS code. Thanks in advance for any help. function delete(params) { $.ajax({ url: '../delete_alloc/', type: 'POST', dataType: 'json', beforeSend: function (xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } }, data: { params:params }, complete: function (response) { if (response.responseJSON.length) { if () { delete(params); } else if () { delete(params); } } } } -
Error of Django's forms instance
my files in project is: djangoTry --views.py --forms.py --others not included in this question files When I click submit in my form I call this method from views.py: from .forms import NameForm def kontakt(request): if request.method == 'POST': form = NameForm(request.POST) form.test("test") if form.is_valid(): first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] phone_number = form.cleaned_data['phone_number'] email = form.cleaned_data['email'] details = form.cleaned_data['details'] return HttpResponseRedirect('/') else: form = NameForm() return render(request, 'index.html', {'form':form}) NameForm is class from forms.py file: from django import forms class NameForm(forms.Form): first_name = forms.CharField(label='first_name', max_length=100) last_name = forms.CharField(label='last_name', max_length=100) phone_number = forms.CharField(label='phone_number', max_length=100) email = forms.CharField(label='email', max_length=100) details = forms.CharField(label='details', max_length=100) def test(self, message): print("i'm in test and message is: %s " , (message)) print(self.first_name) def is_valid(self): print("jest valid") return True form.html <form class="col s12" action="{% url 'kontakt' %}" method="post"> {% csrf_token %} {{ form }} <div class="row"> <div class="input-field col s6"> <input id="first_name" type="text" value="hehe"> <!-- value="{{ form.first_name }}"> --> <label for="first_name">First name</label> </div> <div class="input-field col s6"> <input id="last_name" type="text" autocomplete="off" value="hehe"> <!-- value="{{ form.last_name }}" > --> <label for="last_name">Last name</label> </div> </div> <div class="row"> <div class="input-field col s12"> <input id="phone_number" type="number" autocomplete="off" value="123456789"> <label for="phone_number">Phone number</label> </div> </div> <div class="row"> <div class="input-field col s12"> <input id="email" type="email" … -
django dynamic javascript in custom widget
I wrote a custom widget: class CustomWidget(CustomWidgetBase): css = { 'all': ( config['custom_css'] + config['extra_css'] ) } js = ( config['custom_js'] + config['extra_js'] ) @property def media(self): media = super(CustomWidget, self).media media.add_css(CustomWidget.css) media.add_js(CustomWidget.js) return media def render(self, name, value, attrs=None): attrs_for_textarea = attrs.copy() attrs_for_textarea['hidden'] = 'true' attrs_for_textarea['id'] += '-textarea' html = super(CustomWidget, self).render(name, value, attrs_for_textarea) html += render_to_string( 'app/custom_widget.html', { 'id': attrs['id'].replace('-', '_'), 'id_src': attrs['id'], 'value': value if value else '', 'settings': json.dumps(self.template_contexts()), 'STATIC_URL': settings.STATIC_URL, 'CSRF_COOKIE_NAME': settings.CSRF_COOKIE_NAME, } ) CustomWidget.js += (os.path.join(settings.STATIC_URL, 'app/my.js'),) return mark_safe(html) 'app/custom_widget.html' has javascript code: {% load staticfiles %} <div id='{{ id_src }}'>{{ value|safe }}</div> <script> $(function() { var {{ id }}_textarea = window.document.getElementById('{{ id_src }}-textarea'); ... omitted ... I'd like to move javascript code in 'app/custom_widget.html' into 'app/my.js' because it makes widget code dependent on the order of javascript declarations. Thus, 'app/my.js' must be dynamically generated with the values passed by Django view. I want to place 'app/my.js' at the bottom of the page. Thank you. -
'DatabaseOperations' object has no attribute 'geo_db_type' , mysl-celery-postgres , no work
I have read some relationed question but i not find solution, i am try to connect three database mysql - celery- postgis. mysql and celery is working but when i add new model and new database postgis I have this error , please check my code , I believe that problem is in router.py models from __future__ import unicode_literals from django.contrib.gis.db import models class Ciudad(models.Model): nombre = models.CharField(max_length=50, blank=True, null=True, unique=True) departamento = models.CharField(max_length=80, blank=True, null=True, unique=True) punto = models.PointField(blank=True, null=True) polygon = models.PolygonField(blank=True, null=True) precio_base = models.TextField(blank=True, null=True) precio_yamimo = models.TextField(blank=True, null=True) class Zona(models.Model): nombre = models.CharField(max_length=50, blank=True, null=True, unique=True) polygon = models.PolygonField(blank=True, null=True) ciudad = models.ForeignKey(Ciudad, blank=True, null=True) recargo = models.IntegerField(default=0, blank=True, null=True) I believe that problem might be here Router class AutoRouter(object): "Route Celery models to separate DB." APPS_POSTGRES = ( 'ciudades', # Models from kombu.transport.django, if you're using Django as a message transport. ) APPS_CELERY = ( 'ciudades', # Models from kombu.transport.django, if you're using Django as a message transport. ) DB_ALIAS_POSTGRES = 'geozone' DB_ALIAS_CELERY = 'celery' def db_for_read(self, model, **hints): if model._meta.app_label in self.APPS_CELERY: return self.DB_ALIAS_CELERY elif model._meta.app_label in self.APPS_POSTGRES: return self.DB_ALIAS_POSTGRES return None def db_for_write(self, model, **hints): if model._meta.app_label in self.APPS_CELERY: return self.DB_ALIAS_CELERY elif … -
Issue extending django User model
I have a website where the user should be able to sign up as a "worker" or a "customer", an uber model type of site. I created the two models WorkerProfile and CustomerProfile and the two forms, but each time I submit either the customer or worker form, the new user gets put in both the Customer profile's and Worker profile's in the database at http://127.0.0.1:8000/admin/ , how do I prevent this from happening? models.py: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class WorkerProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) university = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) role = models.CharField(max_length = 10, default = 'USER') def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_worker_profile(sender, instance, created, **kwargs): if created: WorkerProfile.objects.create(user=instance) @receiver(post_save, sender=User) def save_worker_profile(sender, instance, **kwargs): instance.workerprofile.save() class CustomerProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) university = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) role = models.CharField(max_length = 10, default = 'CUSTOMER') needLaundryDone = models.BooleanField(default = False) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_customer_profile(sender, instance, created, **kwargs): if created: CustomerProfile.objects.create(user=instance) @receiver(post_save, sender=User) def save_customer_profile(sender, instance, **kwargs): instance.customerprofile.save() forms.py: from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class WorkerSignUpForm(UserCreationForm): #birth_date and university … -
Storing the blank file using Django and Python
I need some help. I need to save the .csv file into local folder using Python but its storing the blank file. I am explaining my code below. views.py: report = Reactor.objects.all() filename = str(uuid.uuid4()) + '.csv' response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename='+filename writer = csv.writer(response) writer.writerow(['Name', 'Status', 'Date']) for rec in report: if rec.status == 1: status = 'Start' if rec.status == 0: status = 'Stop' if rec.status == 2: status = 'Suspend' writer.writerow([rec.rname, status, rec.date]) open(settings.FILE_PATH+filename,'w') return response settings.py: FILE_PATH = os.getcwd()+'/upload/' Here I am also downloading the file and I need to save that file into folder but here some blank file is storing. Please help me. -
Selecting connection not working Django-Haystack
When using a different connection on SearchForm, SearcQueryset instance is always none, after creating class with using parameter and / or calling using method on search. As a result, I keep getting warnings Object could not be found in database. These indexes use the same Model, the difference is on the index_queryset method which index different items. When using for default connection, everythings works fine. example: HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'search.backends.CustomElasticSearchEngine', 'URL': 'http://127.0.0.1:9200/', 'INDEX_NAME': 'default', 'EXCLUDED_INDEXES': ['search.search_indexes.SomeDefaultIndex', ] }, 'extranet': { 'ENGINE': 'search.backends.CustomElasticSearchEngine', 'URL': 'http://127.0.0.1:9200/', 'INDEX_NAME': 'extranet', 'EXCLUDED_INDEXES': ['search.search_indexes.SomeOtherIndex', ] }, } SearchForm class ExtranetSearchForm(BaseForm, SearchForm): def search(self): if not self.is_valid(): return self.no_query_found() if not self.cleaned_data.get('q'): return self.no_query_found() sqs = SearchQuerySet(using="extranet").auto_query(self.cleaned_data.get('q')) #even without further logic, SearchQuerySet instance using property is None return sqs As you see the trace, SearchQuerySet using is None. Im following this page http://django-haystack.readthedocs.io/en/v2.6.0/multiple_index.html Am I missing something here? Configuration wagtail 1.9 django-haystack (2.6.0) -
How get Instance in Django ModelForm
I'm trying to update a model in Django using the class-based generic view UpdateView.But i have some instance problem.When i click submit button id is pass to update form , but instances isn't i am new in django ,so please be forgiving if I'm doing something stupid. urls.py app_name = 'inventory' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^inventory/(?P<pk>[0-9]+)/delete/$', views.HardwareDelete.as_view(), name='hardware-delete'), url(r'^inventory/update/(?P<pk>[0-9]+)/$', views.HardwareUpdate.as_view(), name='hardware-update'), # url(r'^/inventory/add$', views.InventoryAdd.as_view(), name='add-inventory'),] models.py class Hardwares(models.Model): hardware_unit=models.CharField(max_length=100) hardware_model=models.CharField(max_length=100) hardware_subsystem=models.CharField(max_length=100) hardware_serial_number=models.CharField(max_length=1000) hardware_manufacturer = models.CharField(max_length=1000) hardware_operating_system = models.CharField(max_length=1000) hardware_quantity = models.IntegerField(default=1, validators=[MinValueValidator(1)]) def get_absolute_url( self ): return reverse('inventory:index') def __str__(self): return self.hardware_serial_number+" "+self.hardware_model+" "+self.hardware_unit+" "+str(self.hardware_quantity) forms.py class HomeForm(forms.ModelForm): hardware_unit = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Hardware Unit Name..', })) hardware_model = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Model Name...', })) hardware_subsystem = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control', })) hardware_serial_number = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control', })) hardware_manufacturer = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Manufacturer Company Name', })) hardware_operating_system = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Operating System Name', })) hardware_quantity = forms.IntegerField(validators=[MinValueValidator(1)], widget=forms.NumberInput(attrs={'class': 'form-control', 'placeholder': 'Quantity of Harware', })) class Meta: model = Hardwares fields = {'hardware_unit', 'hardware_model', 'hardware_subsystem', 'hardware_serial_number', 'hardware_manufacturer', 'hardware_operating_system', 'hardware_quantity', } views.py class HardwareUpdate(UpdateView ): model = Hardwares form_class = HomeForm template_name = 'inventory/update_form.html' def post(self, request,pk): instance = Hardwares.objects.get(id=pk) form = HomeForm(request.POST, instance=instance) if … -
Django: Several models with list of images
I have several models (say, Car, User, Animal, etc). I need all of them have a list of images. In my previous projects I used something like Car and ImageCar, but now I have many models which requires a list of images and I don't like the idea of use Car, ImageCar, User, ImageUser, Animal, ImageAnimal, and so on. Which is the best approach in this case? -
Django: datetime filter by date ignoring time
I am trying to filter Matches scheduled in a certain day. I can't just do this: match_queryset.filter(start=date) because it also filters by time, but I can do this: match_queryset.filter(start__year=a_date.year, start__month=a_date.month, start__day=a_date.day) But this is too complex, I feel like there could be a simpler way. Then I can also use a range: t0 = datetime.datetime.combine(a_date, datetime.time(0, 0)) t1 = datetime.datetime.combine(a_date, datetime.time(23, 59, 59)) match_queryset.filter(start__gte=t0, start__lte=t1) But this just seems to be an overkill and it probably generates an inefficient query. Can't I just make a query to target the actual date? Something like: # this of course doesn't work match_queryset.filter(start__date=date) No need to say I have tried looking for solution and could not find any. -
apache2 redirecting port from 443 another port which is running on django server
SSLEngine On SSLCertificateFile /etc/apache2/ssl/apache1.crt SSLCertificateKeyFile /etc/apache2/ssl/apache1.key ProxyRequests Off ProxyPreserveHost On AllowEncodedSlashes NoDecode ServerName 16.79.34.166:9000 ProxyPass /singleenctworegion https://16.79.34.166:9000/singleenctworegion/ ProxyPassReverse /singleenctworegion https://16.79.34.166:9000/singleenctworegion/ RequestHeader set X-Forwarded-Proto "https" RequestHeader set X-Forwarded-Port "443" <Directory /var/www/html > AllowOverride All </Directory> AllowEncodedSlashes NoDecode ProxyRequests Off ProxyPreserveHost On <Proxy https://16.79.34.166:9000/*> Order deny,allow Allow from all </Proxy> -
Django 'Request' object has no attribute 'user_id'
In my urls.py I have: url(r'^dashboard/users/(?P<user_id>[0-9]+)/products/$', views.UserProductsList.as_view()) in views.py class UserProductsList(generics.ListCreateAPIView): def get_queryset(self): if self.request.user_id: return UserProducts.objects.filter(user_id=self.request.user_id).order_by('id') else: return UserProducts.objects.all().order_by('id') I want to be able to access my api as such: http://localhost:8000/dashboard/users/10/products should list all products of that user, and http://localhost:8000/dashboard/users/10/products/1 should return product_id 1 of user_id 10 How can I implement this flow. Note: I'm using Django rest framework in this setup -
access class variable from django model method
Hi I have the following djanog model.py, class members(models.Model): def calculate_age(dob): return int((datetime.date.today() - dob).days / 365.25 ) auto_id = models.AutoField(primary_key=True) member_name = models.CharField(max_length=25, blank=False, default='') member_dob = models.DateField(blank=True) member_age = property(calculate_age(member_dob)) Now from calculate_age if I pass the member_dob it is going as datefield type and not the actual value. But If I use the self then it works fine as below, class members(models.Model): def calculate_age(self): return int((datetime.date.today() - self.member_dob).days / 365.25 ) auto_id = models.AutoField(primary_key=True) member_name = models.CharField(max_length=25, blank=False, default='') member_dob = models.DateField(blank=True) member_age = property(calculate_age) Now the issue is, I need to call this calculate_age for multiple items so need to pass the value to the method -
define flag variable in django template
I'm new in Django and I am trying to search for something in a template if I find it a want to print something, if not I want to print something else. sth like this: {% for art in artifacts %} {% if art.product_component == 'A' %} <p> something.</p> {{ found = True }} {% endif %} {% endfor %} {% if not found %} <p>NA</p> {% endif %} I know this is not the right way to do it, but this is just to understand the idea. how can i do it? -
Reading speed comparison in Django from postgreSQL
I'm developing web page, that has to show something like book. I have models for book, section, page, paragraph. Every model is stored in two tables (translation - django-parler). And here my question: Is it faster to retrieve data from postgreSQL with (polymorphic) mptt? I don't have to search data, just retrieve and show it to user. -
Could not save the csv file into folder using Django and Python
I need some help. I am trying to save some .csv files into folder but its throwing the below error using Python and Django. I am explaining my error below. Error: Exception Type: NameError Exception Value: global name 'filename' is not defined I am explaining my code below. report = Reactor.objects.all() response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename='+str(uuid.uuid4())+'.csv' writer = csv.writer(response) writer.writerow(['Name', 'Status', 'Date']) for rec in report: if rec.status == 1: status = 'Start' if rec.status == 0: status = 'Stop' if rec.status == 2: status = 'Suspend' writer.writerow([rec.rname, status, rec.date]) open(settings.FILE_PATH+filename,'w') return response settings.py: FILE_PATH = os.path.join(BASE_DIR, '/upload/') Here I wring the DB value into .CSV file and downloading it. In the same time I need to save that downloaded file into upload folder but getting those error. Please help me to resolve this error. -
How to get one single django queryset by giving multiple tuples
I have a dataframe of related values that I need to query my object together. I can loop through this list of related values and give them to my object, and then append them to a list, but this gives me a list of separate querysets. Is there a way I can read in my tuples together without a loop and obtain a single queryset? The related values are hts_run and variant. In this case, the same variant value has multiple hts_run values. my dataframe has removed the unwanted hts_run values, so I have the correct variant corresponding to the correct hts_run value. here is my code at the moment: var_obj = [] for i, row in df.iterrows(): v_obj = row['variant'] var_obj.append(VariantSampleRun.objects.filter(sample=current_sample, hts_run=row['run']).select_related('variant').order_by('variant')) I need however a single var_obj queryset for another function. I have tried to use 'chain' to merge them, but I am thinking -
Get logger in django get_wsgi_application()
Is it possible to log debug messages while accessing database using django.core.wsgi and get_wsgi_application? -
How to pass Regex named group variable from URL to TemplateView as argument
Say I have this URL url(r'users/(?P<id>\d+)/edit$',TemplateView.as_view(template_name='edit.html')) Is there a way to send the to the template within that url pattern definition? -
Custom field saving
I have a problem with Django admin, basically i have a model like team -> motorcycle connection, and now i have a lot of motorcycles and instead of inline objects i just put custom template with checkbox and manually added objects to database. Now for "hack" i have following line in my custom template: <div id="divCheckbox" style="display: none;"> {{ inline_admin_formset.formset }} </div> and it works okay, but it takes a lot of time if there are many objects, if i remove the "hack" i get MultiValueDictKeyError. So for the saving in model i just overwrite save method, and save after the super. def save_model(self, request, obj, form, change): super(MotorcycleAdmin, self).save_model(request, obj, form, change) moto_instert = Motorcycle() moto_instert.benefit = obj moto_instert.store = Motorcycle.get_by_team_id(id) moto_instert.save() So is there any way i can ignore this fields which i am saving manually or which way should i solve the problem? -
manytomany field not working django-cms
I am using django-cms many to many field is working fine when i add plugins or update but after publish page i didn't get any data where i add many to many field. models are look like this @python_2_unicode_compatible class ClientLogo(CMSPlugin): client_logo = models.ManyToManyField(LogoPluginModel, blank=True) class LogoPluginModel(CMSPlugin): title = models.CharField(max_length=100) here field 'client_logo' will be disapper when i publish djagno-cms page -
Django handle optional url parameter
I want url to have optional url parameter. Primary url is: url(r'^(?P<letnik_id>[1-4])/(?P<classes_id>[A-G])/(?P<subject_id>[\w\-]+)$', views.subject, name="subject_id"), but after subject id i want to be able to add optional parameter that is always a number: url(r'^(?P<letnik_id>[1-4])/(?P<classes_id>[A-G])/(?P<subject_id>[\w\-]+)/(?P<digit>\d+)/$'', views.subject, name="subject_id_optional"), Im not even sure if did that correctly, as i dont know how to set number for parameter. So after the parameter is passed i want the (template?) or maybe view to read the number (which is model's ID number) and add css class ) .highlited-model {background-color: red;} to that model. How would i achieve this and how should i handle it in views or template, wherever it makes more sense? -
Wagtail getting/generating image urls from JSON api or directly
I've been using Wagtail as a headless CMS to use with a frontend application, However I noticed some limitations regarding images. Normally in your jinja template you would generate the correct image size you need and all is fine, However I don't have access to these helpers in my frontend code. I have been trying several things. for example, to solve this for simple page models and their fields I could render a custom api field like so: api_fields = [ # Adds information about the source image (eg, title) into the API APIField('feed_image'), # Adds a URL to a rendered thumbnail of the image to the API APIField('feed_image_thumbnail', serializer=ImageRenditionField('fill-100x100', source='feed_image')), ... ] However this will not work for streamfield since these will only return the image id. So I figured I would use the Wagtail image API, however this does not allow me to access the direct URL either. I find some google group answers refering to this documentation: http://docs.wagtail.io/en/v1.9/advanced_topics/images/image_serve_view.html However this page does not seem to exists in the latest version of the documentation and doesn't seem to allow me to generate images from a url on the frontend. Is there a way to perhaps create a url … -
I am not able to download text file in django
log_path = settings.BASE_DIR + '/uploaded_files/logs/' # log_file = user + '_' +datetime.datetime.now().__str__() log_file = str(random.randint(1, 100)) + '_' + datetime.datetime.now().__str__() log_file = log_path + '%s.txt' % log_file download_error(log_file) def download_error(log_file): file_path = log_file file_name = os.path.basename(file_path) if os.path.exists(file_path): print "DOWNLOAD ERROR FILE" with open(file_path,'rb') as fh: response = HttpResponse(content_type = "text/plain") response['Content-Disposition'] = 'attachment; filename = %s' % file_name return response raise Http404 I am not getting the file downloaded??? -
How to simplify Django filter in if condition
here is my query, get_emp = Employee.objects.get(id='emp_id').name if Employee.objects.filter(name='emp_id') else None this is my scenario... this working fine.. but my query is to simply this even more.. is it possible? because here i am doing the same query twice in condition check and to fetch value. is it possible to make it single? i know to define it separately and do as i want like, emp_id = Employee.objects.filter(id='emp_id') get_emp = emp_id[0].name if emp_id else None but i want to do it in first method... is it possible?