Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"One-shot" way to change Wagtail pages' owner
Is there a clean and fast way to change Wagtail pages' owner? In my project I have page objects which I'd want to keep for production but were created by a "non pk=1" user, so fixtures would have trouble when either the user's pk or natural foreign key would not exist in the Users database. -
How do I combine Djangos ‘LoginRequiredMixin’ and Form Tools ‘FormPreview’?
LoginRequiredMixin works great on other class based views. Also the Form Tools FormPreview works fine. But if I try to uses both together, then the LoginRequiredMixin gets ignored. This is even the case if I use the most basic example from form tools and the Django documentation. Two things I found strange (but this does not necessary be the reason): “This mixin should be at the leftmost position in the inheritance list.” This sounds like there is some internal hack that breaks if someone does something irregular. There is no explanation why. The Form Tools view should be called itself and not the method .as_view(), which is off standard again. Is this a bug? What can I do? -
django-wkhtmltopdf with AJAX requests will get 403 Forbidden
Description I want to generate a PDF file from Django view, so I'm using django-wkhtmltopdf app, the app is working but my template (that is used in the view) has many AJAX requests using jQuery. Views that requested by AJAX requests are protected by csrf token. Issue All AJAX requests are getting 403 Forbidden response because of CSRF verification failed. Trial I tried django-cors-headers and still getting the same responses. -
Vuejs and django?
I am currently using django and vuejs seperately. I send request to django api from the vuej client. What we need is we dont want the client side to see the request sent to the endpoints for security. So, the solution I found is use the django view to render the html where I can call the api and send back response as json. However I have no idea how to intergrate the vuejs code I wrote like using vue router, vuex and so on while rendering from django. I have a build js file which pretty much renders everything in a single view of django. But the requirement doest not allow to do that. Didnot find much tutorials about the django vue which I require. -
"This field is required" error in django
I was working on a form in django and my view is like this:Please click on this link to view image When no data was entered, I want it to show error "This field is required" like this:Please click on this link to view image I've tried to use null = False and blank = False in form, but it is showing this error: TypeError: __init__() got an unexpected keyword argument 'null' This is how I've defined my form: class NewTopicForm(forms.ModelForm): message_in_form = forms.CharField( widget=forms.Textarea(attrs={'rows': 5, 'placeholder': 'What is on your mind?'}), max_length=4000, help_text='The max length of the text is 4000.', required = True ) class Meta: model = Topic fields = ['subject', 'message_in_form'] -
Concatenating into a new field in a Django query
Consider a table called DataTable. It has two fields, A and B. I want to return all rows of this table plus annotate a field called C that is a concatenation of A and B. Here is what I have tried from django.db.models import CharField, Value from .models import DataTable def Test(request): query = DataTable.objects.all().annotate(C=Value('A' + '-' + 'B', output_field=CharField())) problem here is that C is literally just "A - B" for every returned row. I want to use the actual values of A and B. -
Integrate Twilio into Django App
I am getting an import error when trying to import twilio into a preexisting Django app. Here is what is happening/things I have tried: The twilio package downloads to (/home/ubuntu/.local/lib/python2.7/site-packages): This directory contains request package plus urllib3. Both of these seem to be dependencies for twilio. However, I have no idea if these were downloaded as dependencies or if they were already there from the original structure. If so, I don't know if other parts of the program require them. The working location is (/var/www/polar/venv/lib/python2.7/site-packages): I moved twilio to this location and that is when the import twilio error went away, but this is when I got an import error for the request package. So I copied the request package and put it here, then I got import urllib3 error, did the same thing and got another import error from a file from the other directory. So it seems that the first location has a lot of the dependencies for twilio and the other location does not. My sys.path is:['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/home/ubuntu/.local/lib/python2.7/site-packages', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages'] ImportError at / No module named twilio.rest Request Method: GET Request URL: http://35.171.142.166/ Django Version: 1.11.4 Exception Type: ImportError Exception Value: No … -
How to validate of dimensions in default ImageField?
Have a following rule in the project: the image field is optional and a default image is an uninformed case for the user. Images are sent by the user in django and must have a dimension (width> = 900, height> = 400). I am trying to validate the dimensions in admin.py, but it is giving problem when I try to register when it has default argument in imagefield. Gives an image error not found even though it is in the directory. Without the validation function in admin.py it works normally. models.py class Event(models.Model): banner = models.ImageField('banner', upload_to='events/banners', default='events/banners/banner_padrao_eventos.png', blank=True) admin.py class EventForm(forms.ModelForm): class Meta: model = Event fields = '__all__' def clean_banner(self): banner = self.cleaned_data.get('banner') if banner: img = Image.open(banner) width, height = img.size max_width = 900 max_height = 400 if width < max_width or height < max_height: raise forms.ValidationError( 'Image is incorrectly sized:% s x% s pixels. Please insert an image with% s x% s pixels.' % (width, height, max_width, max_height)) if len(banner) > (3 * 1024 * 1024): raise forms.ValidationError('Very large image file (maximum of 3MB).') name_img, ext = banner.name.split('.') if not (ext.lower() in ['png', 'jpg', 'jpeg']): raise forms.ValidationError('Please use the image in JPG, JPEG or PNG format.') … -
Cannot deploy Official Django tutorial on Apache (mod_wsgi)
I know this question seems to have been asked and answered many times, but I have now wasted over 48 hours now trying various methods provided by other answers and I cannot seem to deploy the official django tutorial to my local Apache webserver (Apache 2.4 on Ubuntu 18.04, Python 3.6.5). Here's what I did. I created a virtualenv virtualenv outlier cd outlier pip3 install django django-admin startproject mysite I created my app and installed the mod_wsgi version appropriate for my python version (I tried the apt install and the setup.py install methods). Then I configured /etc/apache2/sites-enabled/000-default.conf as follows: LoadModule wsgi_module /usr/lib/apache2/modules/mod_wsgi.so <VirtualHost *:80> LogLevel info DocumentRoot /srv/outlier ServerName outlier.tuhao WSGIDaemonProcess outlier user=www-data group=www-data python-path="/srv/outlier" python-home="/srv/outlier/lib/python3.6/site-packages" WSGIProcessGroup outlier WSGIScriptAlias / /srv/outlier/outlier/wsgi.py <Directory /srv/outlier> Require all granted </Directory> </VirtualHost> Just to be sure, I also did a sudo chown -R www-data:www-data /srv/ and a sudo chmod -R 777 /srv/ to avoid any permissions ding-dongs. and restarted apache with sudo service apache2 restart. Unfortunately, immediately after restarting, the apache logs start incessantly spamming the following: Current thread 0x00007faa78e0abc0 (most recent call first): [Mon Jun 04 15:34:55.664080 2018] [core:notice] [pid 1932] AH00051: child pid 5058 exit signal Aborted (6), possible coredump in /etc/apache2 … -
I need help in retrieving data from Django fields
I have a model models.py class EmployeeModel(models.Model): Employee_id = models.CharField(max_length=200) name = models.CharField(max_length=200) basic_salary = models.IntegerField(blank=True,default=0) HRA = models.IntegerField(blank=True,default=0) DA = models.IntegerField(blank=True,default=0) TA = models.IntegerField(blank=True,default=0) CCA = models.IntegerField(blank=True,default=0) Medical = models.IntegerField(blank=True,default=0) bonus = models.IntegerField(blank=True,default=0) advance_pay = models.IntegerField(blank=True,default=0) PF = models.IntegerField(blank=True,default=12) def __str__(self): return self.name All objects of my models.py >>> employeeModel.objects.all() <QuerySet [<employeeModel: Emp001>, <employeeModel: Emp003>, <employeeModel: Emp004>, <employeeModel: Emp006>, <employeeModel: Emp006>, <employeeModel: Emp0010>, <employeeModel: Emp0011>, <employeeModel: Emp0012>, <employeeModel: Emp0013>, <employeeModel: Emp0013>, <employeeModel: Emp0013>, <employeeModel: Emp0013>, <employeeModel: Emp0013>, <employeeModel: Emp0013>, <employeeModel: Emp0013>, <employeeModel: Emp0013>, <employeeModel: Emp0013>, <employeeModel: Emp004>, <employeeModel: Emp0014>, <employeeModel: Emp0015>, '...(remaining elements truncated)...']> For every instance of model 'EmployeeModel',I want to retrieve data from fields to calculate further in 'views.py' for Gross Salary!For example i want to get data of fields TA,DA,HRA individually so i can add them. But i dont know how to get data from django fields. Im new to django,please be helping me.. -
Django auto deployment using Fabric
I wanted to automatically deploy my django project by using Fabric3 Here is my fabfile.py `from fabric.api import env from fabric.api import run from fabric.operations import sudo GIT_REPO = "https://github.com/........" env.user = 'root' env.password = '...' domain name env.hosts = ['demo....com'] normally is port 22 env.port = '22' def deploy(): source_folder = '/home/.../sites/..../...' run('cd %s && git pull' % source_folder) run(""" cd {} && ../env/bin/pip install -r requirements.txt && ../env/bin/python3 manage.py collectstatic --noinput && ../env/bin/python3 manage.py migrate """.format(source_folder)) sudo('restart gunicorn-demo.charon.me') sudo('service nginx reload')` And here is how I run it: python fabfile.py fab deploy And finally here is the error: Traceback (most recent call last): File "/Users/charon/Documents/PycharmProjects/try_blog/fabfile.py", line 1, in <module> from fabric.api import env File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/fabric/api.py", line 10, in <module> from fabric.context_managers import (cd, hide, settings, show, path, prefix, File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/fabric/context_managers.py", line 27, in <module> from fabric.state import output, win32, connections, env File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/fabric/state.py", line 9, in <module> from fabric.network import HostConnectionCache, ssh File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/fabric/network.py", line 16, in <module> from fabric.exceptions import NetworkError ImportError: cannot import name 'NetworkError' Plz help me with this!!!! -
How to send info in URL
I am trying to create a product filter I am sending the user choice in URL if the user select size = L then using request.GET I am recieving {'size': ['L']} but I want to recieve {'size':{'op':'in','attri':'L'}} is this possible?? please help my size filter is : size = django_filters.ModelMultipleChoiceFilter(queryset=q2.values_list('name', flat=True).distinct(),widget=forms.CheckboxSelectMultiple) -
Django signals - does a model automatically send post_save?
I have a model, in which no signals are defined. Then, in another file, as part of a management command, I have the following: from django.db.models.signals import post_save from django.dispatch import receiver from home.models import Product @receiver(post_save, sender=Product) def test(sender, **kwargs): print("Recevied: {}".format(sender)) The 'test' function never actually seems to be called. Does this mean that post_save is not automatically called when the model saves (the docs imply that the default signals of which post_save is one, are called automatically, and don't need to be defined. The docs don't actually state this, though, hence the question). -
Django show model images on Admin page
How would I add the image belonging to this model on the detail page of that model in the Admin Page? The image can be on the right side of the data/text or below the data/text/ from django.db import models # Create your models here. class Gallery3(models.Model): class Meta: verbose_name = "Vintago Upload" CATEGORIES = ( ('Meubels', 'Meubels'), ('Vazen', 'Vazen'), ('Schilderijen', 'Schilderijen'), ) title = models.CharField(max_length=100) category = models.CharField(max_length=10, choices=CATEGORIES, default='Meubels') description = models.CharField(max_length=255, blank=True) document = models.ImageField(upload_to='images',null=True) price= models.DecimalField(max_digits=10, decimal_places=2) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.title #def get_absolute_url(self): # return reverse('gallery_detail', kwargs={'pk': self.pk}) -
Django render_to_string not working (Django 1.4)
I'm trying to return a result set from an ajax search using Django. I'd like this result set to be displayed in a template and then i'd like the template to returned back after a successful django response. context ={} if request.method == 'POST': search_text = request.POST.get('search') monitors = RaspPiMonitor.objects.filter( mac_address__icontains=search_text) context={ 'monitors':monitors, } html = render_to_string('realtime_reports/search_results.html', context) return HttpResponse(html) return render(request,'realtime_reports/monitors.html',context) -
Django queryset - query date and value of first day of every year
I have the following fee_table holding date and price on a daily basis. fee_talbe -- date and price on a daily basis What is the most efficient way to query only the first day of every second year with the equivalent price without using raw SQL queries ? -
How to join Rabbitmq, Celery and Django?
The main idea is to send to Rabbitmq server a message with json file and to consume this message by Celery worker and do some job with this json. The question is how to set up celery worker for consuming? I surf on the Internet 3 days but all I found is how to set them up to work with the Django trigger (i.e., the action from the application launches the task). Please share your experience or point out my mistake in understanding this problem. Is this generally feasible? Thank you! -
How to get Django Admin to cache select options on inlines?
Using Django 1.11, Python 3.6 I'm having no luck whatsoever with this. I'm trying to optimise a slow Django Admin page which is making a lot of duplicate SQL queries due to a lot of select dropdowns and multiple inlines. I've tried using the cacheops library and a Redis store, but nothing gets cached at all, even if I set everything to cache automatically with '*.*': {'ops': 'all', 'timeout': 60*60},. I'm assuming this may be because the Admin seems to bypass normal Django ORM objects. Speaking of which, I tried just implementing a bespoke objects manager that caches using the cachetools library's TTLCache class: from django.db import models from cachetools import TTLCache, cached cache = TTLCache(maxsize=100, ttl=3600) class CacheManager(models.Manager): @cached(cache) def get(self, *args, **kwargs): print("Caching get. args: %r. kwargs: %r" % (args, kwargs)) return super(CacheManager, self).get(*args, **kwargs) @cached(cache) def all(self, *args, **kwargs): print("Caching all. args: %r. kwargs: %r" % (args, kwargs)) return super(CacheManager, self).all(*args, **kwargs) @cached(cache) def filter(self, *args, **kwargs): print("Caching filter. args: %r. kwargs: %r" % (args, kwargs)) return super(CacheManager, self).filter(*args, **kwargs) @cached(cache) def order_by(self, *args, **kwargs): print("Caching order_by. args: %r. kwargs: %r" % (args, kwargs)) value = super(CacheManager, self).order_by(*args, **kwargs) print(value) return value @cached(cache) def first(self, *args, **kwargs): … -
Multiple response message in drf rest swagger
How to display multiple response messages in the drf swagger. I am using the below packages Django==1.11.13 django-rest-swagger==2.2.0 djangorestframework==3.8.2 django-filter==1.1.0 -
`login_required` decorator utilized multiple nested callbacks
I find it amazing when read into the login_required decorator of Django def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME): """ Decorator for views that checks that the user passes the given test, redirecting to the log-in page if necessary. The test should be a callable that takes the user object and returns True if the user passes. """ def decorator(view_func): @wraps(view_func, assigned=available_attrs(view_func)) def _wrapped_view(request, *args, **kwargs): if test_func(request.user): return view_func(request, *args, **kwargs) path = request.build_absolute_uri() resolved_login_url = resolve_url(login_url or settings.LOGIN_URL) # If the login url is the same scheme and net location then just # use the path as the "next" url. login_scheme, login_netloc = urlparse(resolved_login_url)[:2] current_scheme, current_netloc = urlparse(path)[:2] if ((not login_scheme or login_scheme == current_scheme) and (not login_netloc or login_netloc == current_netloc)): path = request.get_full_path() from django.contrib.auth.views import redirect_to_login return redirect_to_login( path, resolved_login_url, redirect_field_name) return _wrapped_view return decorator def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): """ Decorator for views that checks that the user is logged in, redirecting to the log-in page if necessary. """ actual_decorator = user_passes_test( lambda u: u.is_authenticated, login_url=login_url, redirect_field_name=redirect_field_name ) if function: return actual_decorator(function) return actual_decorator Nested callbacks are employed in user_passes_test. I am thirsty for this technique and apply it to my own codes, What's the name of this … -
TypeError 'Profile' object is not iterable
I keep getting this error, I can't seem to fix it. Each time a new user signs up, he/she can create a profile. I can create and edit a profile, but I can't view the profile. Maybe my code is wrong, but idk. I am fairly inexperienced. TypeError at /profile/1/ 'Profile' object is not iterable Url: url(r'^profile/(?P<pk>\d+)/$', views.profile, name='profile') View: @login_required def profile(request, pk): prof = get_object_or_404(Profile, pk=pk) return render(request, 'blog/profile_detail.html', {'prof': prof}) Model: class Profile(models.Model): user = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name='prof') bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(blank=True, null=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) HTML: {% for pro in prof %} <a href="{% url 'profile_edit' pk=prof.pk %}"><span class="glyphicon glyphicon-pencil"></span></a> <h2>{{ user.username }}</h2> <p>{{ user.profile.bio }}</p> <p>{{ user.profile.location }}</p> <p>{{ user.profile.birth_date }}</p> {% empty %} <a href="{% url 'profile_new' pk=prof.pk %}"><span class="gliphicon gliphicon-plus"></span></a> {% endfor %} If I am supplying too little information, please say so nicely, no nasty comments and down-votes please. Please help a noob. -
how to create Groups programatically in Django
I am setting up a member site using django, in which members belong to groups that they create and then invite other users to join. It seems that what I am looking for is to use the django groups functionality, but the documentation on how to go about this is minimal at best - at least I haven't found any. It basically talks about creating groups in the Admin console, which is not what I am trying to do. I would like to do it programatically/dynamically. Another way to go about this would be to at a foreignkey to the User model up to a group model, however I can't add a foreignkey to the generic User model. I have read lots of stuff that google threw up at me from my searches. none helpful. How would I go about this? Thanks -
Video Field in Django FrameWork
I have tried many ways to work with videos in the Django. Is there any deddicated field in the frame work that was designed for the Videos. In order to work with images we have ImageField similarly is there any Video Field. Please share any opensource video web app for better understanding of how to work with videos in the Django. Thank you -
Pytest and pytest-django: How can I run each test (complete with setup and teardown) multiple times with different contexts?
I am setting up the test platform for a multi-tenant system. For each written test, I want to create a test for each tenant and wrap the entire test run to change the database connexion and some thread local variable before the test without breaking the database teardown where it flushes. During my trial-and-error process, I've resorted to climbing higher and higher in the pytest hook chain: I started with pytest_generate_tests to create a test for each tenant with an associated fixture, but the teardown failed, I've ended up at the following idea: def pytest_runtestloop(session): for tenant in range(settings.TENANTS.keys()): with set_current_tenant(tenant): with environ({'DJANGO_CONFIGURATION': f'Test{tenant.capitalize()}Config'}): session.config.pluginmanager.getplugin("main").pytest_runtestloop(session) return True Although this does not work (since django-configurations loads the settings during the earlier pytest_load_initial_conftests phase), this example should give an idea of what I am trying to achieve. The big roadblock: The default database connection needs to point to the current tenant's database before any fixtures are loaded and after flush is ran. I could have a wrapper python script that calls pytest multiple times with the right config, but I would lose a lot of nice tooling. -
Set models fields programmatically
I'm making some scripts to migrate an old database to a new one in a Django app. In order to manage the data from some tables of the old_app It would be easier to store the id of these tables on a temporary column in the new database. Note: I have to make individual scripts for each table in the new_app For example, suppose I have 2 tables (A, B) in the old_app with a ManyToMany Relationship. First I made an script to store A data and then B. Later on I have to store the relantionship between them but I have lost the id of both tables as I don't need them in my new_app. The question is: Is it possible in django to create some kind of temporary column to store the old id and then delete that column when I have saved the old relationship? Something like A.objects.add_column('temporary_id', Models.CharField, ....) A.objects.delete_column('temporary_id') Or do I have to make a migration of the model before and after I migrate the data from the old_app?