Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Restarting a apache2 over perticular request in django
I am working a project, that creates an django app over a request. Since the webserver apache needs to be restarted to add new files created. I tried following: 1) Django request_complete Signals: This is not good way because I dont want my server to be restarting on every request complete 2) threading.Time:I tried to run a function with some delay so that it allows complete the current request. This is not working giving following error: RuntimeError at /apps/37f63340-2984-40b1-a728-1cf3d0820ae6/ threads can only be started once Please suggest me way to solve this problem. -
Django: Url don't works
I'm trying do the following: I have two url's working well, so I created a third for another template, but when I try to run the application his don't work and returns:Can not connect... I check the views and template (html file) and both seem ok, I think the error is in the app.url's file, but where? My codes: app.url's: #from .models import Candidato from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.canditato_list, name='canditato_list'), url(r'^candidato/(?P<pk>[0-9]+)/$', views.candidato_detalhe,name='candidato_detalhe'), url(r'^new/$', views.cadastrar, name='cadastrar') url(r'^avaliacao/$', views.avaliar, name='avaliar') ] views.py: from django.shortcuts import render, get_object_or_404 from .models import Candidato, Criterio from django import forms from .forms import CandForm def canditato_list(request): candidatos = Candidato.objects.all() return render(request, 'app/candidato_list.html', {'candidatos': candidatos}) def candidato_detalhe(request, pk): candidato = get_object_or_404(Candidato, pk=pk) return render(request, 'app/candidato_detalhe.html', {'candidato': candidato}) def avaliar(request): criterios = Criterio.objects.all() return render(request, 'app/avaliacao.html', {'criterios': criterios}) def cadastrar(request): form = CandForm() return render(request, 'app/cadastro.html', {'form': form}) forms.py: from .models import Candidato from django import forms class CandForm(forms.ModelForm): class Meta: model = Candidato fields = ('name', 'e_mail') PS: the problem is in the last url... when I comment this line all come back works well... -
Django admin group by FK
How do I go about grouping a set of fields within the Django Admin. By this I mean Table 1: User - User Key - User Name Table 2: Blog - Blog Key - User Key (FK) In the BlogAdmin I would like to display the User Name of the Author also perform an action on the blogs. This works but displays the user name for each blog created by the user. Is there a way I could just display the user name once but in the action update all blogs created by the user? -
django template call javascript function on loop
I am looping in a javascript template like: {% for movie in movies %} {{movie.name}} {% endfor %} Is there anyway like I can call a javascript function that returns required DOM element like: {% for movie in movies %} <script> function get_movie(name) { return "<div> class='movie-title'>name</div> } get_movie({{movie.name}}) </script> {% endfor %} I just want to call a js function and have some check and return an element according to.. -
how to convert a form to pdf in django?
I am using AngularJS and django but i am not able to convert my form into pdf. Can someone help me out what to write in .py file and .html file? This is my .py code but this is not executing when i click print pdf button def render_to_pdf(template_src, context_dict): context = Context(context_dict) template = get_template(template_src) html = template.render(context) result = StringIO.StringIO() pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(),content_type='application/pdf') return HttpResponse('We had some errors<pre>%s</pre>' % escape(html)) -
html - redirect to new url after form submission (django site)
I am trying to make a button redirect the user to a new url after they submit a form. This is how it is right now, and it works properly and all the data gets sent to the django database. <form method='POST' action='' class="col-md-6 col-md-offset-7" style="background-color: lightgreen; border-radius: 10px"> However, when I change the action to action="{% url 'ridesharing:request-success' %}", the redirect works, but the data does not go to my django database. What is going on here? -
Django model.Save Issue
I am trying to save a some data into one of my models defined as follows: class InvitationStatus(models.Model): Status = models.CharField(max_length=250, unique=True) class TeamInvite(models.Model): Inviter = models.IntegerField() Invitee = models.IntegerField() Team_ID = models.IntegerField() Status = models.ForeignKey(InvitationStatus, db_column='Status') Date = models.DateTimeField() In my views.py: def index(request, p_id): instance = TeamInvite(request.POST, request.FILES) instance.Inviter = request.user.id instance.Invitee = p_id instance.Team_ID = user_profile.team_id instance.Status = invitationstatus instance.save() But I get an error from the instance.save() function: TypeError: int() argument must be a string or a number, not 'QueryDict' Never got anything like this before...Any ideas? -
Something like django signals in Odoo
Am looking for some mechanism that allows me to hook a python function to the triggering of a database event (insert, update, delete) of ANY model in Odoo. I have worked with Django signals and am wondering if Odoo has something like that. Thanks in advance. -
XAMPP Apache not working after installing mod_wsgi
Good day. I am currently trying to host my Django website using XAMPP Apache. I have followed several tutorials but one of those works. I was wondering if you could tell me what are the steps I have missed or did wrong. Here is the specs of the installed packages on my Django dev site: Python = 2.7.12, 32-bit Apache = 2.4, 32-bit Visual C++ Version 9 OS: Windows 7 64-bit Here is the procedure I have followed: Download mod_wsgi from https://code.google.com/archive/p/modwsgi/downloads. I have tried [mod_wsgi-py26-vc9.so, mod_wsgi-py27-vc9.so, mod_wsgi-win32-ap22py27-3.3.so and mod] **but none seems to work. Rename the mod_wsgi file to mod_wsgi.so and save it to C:/xampp/apache/modules Run xampp and edit apache httpd.conf file by adding LoadModule wsgi_module modules/mod_wsgi.so I have also tried LoadModule mod_wsgi modules/mod_wsgi.so But still have same result. -
django adding admin category error
# settings.py MEDIA_URL = '/media/' MEDIA_ROOT =os.path.join(BASE_DIR,'media/') #urls.py outer from django.conf.urls import url, include from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'', include('webapp.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) #admin.py of webapp from django.contrib import admin from .models import Profile class ProfileAdmin(admin.ModelAdmin): list_display = ['user', 'birthday', 'photo'] admin.site.register(Profile, ProfileAdmin) #models.py of webapp class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) birthday = models.DateField() photo=models.ImageField(upload_to='users/%Y/%m/%d',blank=True) def __str__(self): return 'Profile for user {}'.format(self.user.username) full error traceback Traceback (most recent call last): File "./manage.py", line 8, in from django.core.management import execute_from_command_line File "/home/peterkim/PycharmProjects/bravepeach_web/.venv/lib/python3.5/site-packages/django/core/management/init.py", line 13, in from django.core.management.base import ( File "/home/peterkim/PycharmProjects/bravepeach_web/.venv/lib/python3.5/site-packages/django/core/management/base.py", line 13, in from django.core import checks File "/home/peterkim/PycharmProjects/bravepeach_web/.venv/lib/python3.5/site-packages/django/core/checks/init.py", line 11, in import django.core.checks.caches # NOQA isort:skip File "/home/peterkim/PycharmProjects/bravepeach_web/.venv/lib/python3.5/site-packages/django/core/checks/caches.py", line 14, in @register(Tags.caches) TypeError: register() missing 1 required positional argument: 'kwargs' I can't figure out why this happens. please help. Thank you in advance! -
When should I use .set(..., clear=True) in Django?
Django's ManyToManyField managers have a .set(objs, bulk=True, clear=False) method. According to the (current) source: clear=True calls .clear on the relation before adding everything in objs. [clear=False] fetches the related items to compare with objs and .remove everything not in objs then add anything in objs not in the relation already. So in terms of database queries that gives us: clear=True sends 2 queries (one to delete everything, one to add all new items). [clear=False] sends up to m+n+1 queries (1 to get the existing relations, m to remove existing relations not in objs and n to add objs not in relations) as well as computing the difference between the sets. The default [clear=False] seems much more inefficient. Why would I not set clear=True wherever I can? In what situations is the default behaviour preferable? -
Deleting/Clearing django.contrib.messages
I want to conditionally clear django.contrib.messages. None of the solutions discussed in these two questions work: Delete all django.contrib.messages Django: Remove message before they are displayed Any suggestions on how I can clear the messages? I am using django 1.10 Code: messages = get_messages(request) for msg in messages: pass for msg in messages._loaded: del msg for msg in messages._queued_messages: del msg -
no such table: social_auth_usersocialauth
I'm trying to develop an Django Application which uses Google API for authentication. Everything seems to work fine, however after login I got this error: no such table: social_auth_usersocialauth and I have no idea how to solve it. enter image description here Is there anyone who already had this same problem that could help me? I appreciate any help, thanks. -
Django Loop inside Model.py to check if previous ID exist in DB or NOT
def getPreID(self): preid=self.id-1 preid1 = TourScene.objects.filter(id = preid) if not preid1: preid =preid-1 What I want here exactly is when I am getting self.id I need the previous Id so I did preid=self.id-1, Now I want to check if this preid exist or not if not I want to next previous ID. So how Can I run this in loop to check if id not exist check previous if previous not exist then check next previous ID.. so ... please help me out because I am new to python. -
Django signup/login not directing users to ?next=/my/url
Setup I use [django-allauth][1] for user accounts. # urls.py url(r'^login$', allauth.account.views.login, name="account_login"), url(r'^join$', allauth.account.views.signup, name="account_signup"), . # settings.py LOGIN_REDIRECT_URL = '/me' LOGIN_URL = '/join' # users sent here if they run into @login_required decorator # To collect additional info if user signs up by email: ACCOUNT_SIGNUP_FORM_CLASS = 'allauth.account.forms.WinnerSignupForm' . That custom signup form: # account/forms.py from .models import Winner, FriendCode class WinnerSignupForm(forms.ModelForm): """ This is the additional custom form to accompany the default fields email/password (and maybe username) """ class Meta: model = Winner fields = ('author_display_name','signupcode',) widgets = {'author_display_name':forms.TextInput(attrs={ 'placeholder': _('Display Name'), # 'Display Name', 'autofocus': 'autofocus', }) , 'signupcode': forms.TextInput(attrs={ 'placeholder': _('Invite code (optional)'), 'autofocus': 'autofocus' }) } def signup(self, request, user): # custom code that performs some account setup for the user # just runs a procedure; there's no "return" at end of this block I don't think my custom WinnerSignupForm is causing the issue, because the problem persists even if I disable it (i.e., I comment out this line from settings.py: ACCOUNT_SIGNUP_FORM_CLASS = 'allauth.account.forms.WinnerSignupForm') Behaviour 0. Without ?next=/some/url parameter: Thanks to LOGIN_REDIRECT_URL in settings.py, if I visit example.com/join or example.com/login, I'll wind up on example.com/me That is fine. 1. If I am already logged in, everything … -
Paypal Express Checkout - Show confirmation page
Finishing up paypal express checkout and would like to show confirmation page before the payment is executed and not sure how to go about it. Paypal documentation doesn't provide whole lot of detail. Currently I am able to create and execute a payment but missing the middle step. Here is JS code that is part of my cart template. <div class="pull-right" id="paypal-button"></div> <script src="https://www.paypalobjects.com/api/checkout.js"></script> <script> paypal.Button.render({ env: 'sandbox', // Optional: specify 'sandbox' environment style: { size: 'medium', shape: 'rect', color: 'gold' }, payment: function(resolve, reject) { var CREATE_PAYMENT_URL = 'http://127.0.0.1:8000/checkout/payment_create/'; paypal.request.post(CREATE_PAYMENT_URL) .then(function(data) {console.log('Payment ID: ', data.paymentID); resolve(data.paymentID); }) .catch(function(err) { reject(err); }); }, onAuthorize: function(data) { // Note: you can display a confirmation page before executing var EXECUTE_PAYMENT_URL = 'http://127.0.0.1:8000/checkout/payment_execute/'; paypal.request.post(EXECUTE_PAYMENT_URL, { paymentID: data.paymentID, payerID: data.payerID }) .then(function(data) { window.location.href = 'http://127.0.0.1:8000/checkout/payment_done/'; }) .catch(function(err) { window.location.href = 'http://127.0.0.1:8000/checkout/payment_error/'; }); } }, '#paypal-button'); payment_create and payment_execute views work as expected, let me know if they are needed I can add them here as well. -
post group name with the multiple device selected
I am trying to create an api for device group and device. A device group can have multiple devices and i want to have the post api for device group with multiple devices because group creation is shown only when device is selected and user might select multiple devices and then create a new group. That way when group is created, those selected devices should also be shown as device_list Here is my code, i am not sure on how to do post request class BaseDevice(PolymorphicModel): name = models.CharField(max_length=250, blank=False, null=False) group = models.ForeignKey('DeviceGroup', related_name="groups", null=True, blank=True) class Device(BaseDevice): description = models.TextField(blank=True, null=True) class DeviceGroup(models.Model): name = models.CharField(max_length=250, blank=False, null=False) class DeviceIdSerializer(serializers.ModelSerializer): id = serializers.UUIDField(source='token', format='hex', read_only=True) class Meta: model = Device # id is the token of the device and name is the name of the device fields = ('id', 'name') class DeviceGroupSerializer(serializers.ModelSerializer): name = serializers.StringRelatedField() device_list = DeviceIdSerializer(read_only=False, many=True, required=False, source="groups") class Meta: model = DeviceGroup # name is the name of group created and device_list is the list of devices with id(token) and device name fields = ('id', 'name', 'device_list') def validate(self, data): """ This method should validate all data """ errors = {} try: name = … -
Bootstrap fileupload button stacked beneath default html form button
As shown in the picture below I have bootstrap beneath the standard html form file upload button. How can I remove the standard button and the text. So that it's only the bootstrap button and my own text? The text is in danish, but it's the "no file has been chosen" I use ModelForm to display the form field. html: <label class="btn btn-primary btn-file"> {{ field }} </label> ModelForm: widgets = { 'image': forms.FileInput(attrs={'class' : 'add-image-upload-hidden'}), } -
Is there a way to run a Django app without mod_wsgi or mod_passenger?
I've been trying to set up a Django Application on a shared hosting and I'm not allowed to use mod_wsgi neither mod_passenger. I've searched the web and found something about FastCG, but I'm not sure about it. The issue is, I'm using a shared hosting and the support guy told me this: The mod_wsgi needs to modify Apache so that it can create its own mini server to handle .py files, but for obvious reasons we just are not able to do that for a shared server. If this is something you really need I would suggest looking at a VPS where you are able to make any modifications you desire. I'd like to know if there are any known alternatives for this situation, where one needs to run a Djando App on a shared hosting service and it's not allowed to use neither mod_wsgi nor mod_passenger. -
django social auth login
django python social auth with facebook auth User Model structure class User(AbstractBaseUser, PermissionsMixin): objects = UserManager() email = models.CharField(max_length = 40, unique=True) username = models.CharField(max_length=50) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=True) date_joined =models.BooleanField(default=True) avatar = models.ImageField(upload_to=get_upload_path) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] so pipeline def create_user(strategy, details, user=None, *args, **kwargs): if user: return {'is_new': False} fields = {'email': details.get('email'), 'username': details.get('username')} if not fields: return return { 'is_new': True, 'user': strategy.create_user(**fields) } def update_avatar(backend, response, uid, user, *args, **kwargs): data = backend.strategy.request_data() print(data.get("reception_email")) if backend.name == 'facebook': url = "http://graph.facebook.com/%s/picture?type=large" % response['id'] avatar = urlopen(url) user.avatar.save(slugify(user.email + "social") + '.jpg', ContentFile(avatar.read())) user.save() i need facebook login after login my site but pipeline's requets argement is not HttpRequest -
django-allauth socialaccount "full" logout?
I am working on what might become a sort-of kiosk app. I am new to python and django but it is rolling along. My allauth flow for signup uses either a social login (Google for the moment) or a "local" email address & password. If I login with a Google account then logout I am redirected to the sign-in page, cool. The thing is I have not really been logged out of the Google account. If I click the social login link then I am back in the user area with no password challenge. Does allauth have a way to logout and have the social auth token removed? Do I need to catch the logout signal and find/delete the token myself? -
Elastic search result filter by user
I'm using elasticsearch_dsl which works great. However, I would like the results to filter according the the user token that gets sent. I tried using rest_frameworks' filters, but had no success with it. What is the right way to achieve this? Models.py class Task(models.Model): title = models.CharField("Title", max_length=10000, blank=True) owner = models.ForeignKey('auth.User', blank=True, null=True) Search.py from rest_framework import filters connections.create_connection() class TaskIndex(DocType): title = String() class Meta: index = 'task-index' def filter_queryset(self, request, queryset, view): return queryset.filter(owner=request.user) def bulk_indexing(): TaskIndex.init() es = Elasticsearch() bulk(client=es, actions=(b.indexing() for b in models.Task.objects.all().iterator())) def _search(title): s = Search().filter('term', title=title.text) response = s.execute() return response -
Ordering Users in a Django ManyToManyField
I have a model that has a ManyToManyField of Users: models.py class Excuse(models.Model): students = models.ManyToManyField(User) reason = models.CharField(max_length=50) views.py def excuse_list(request, block_id=None): queryset = Excuse.objects.all().prefetch_related('students') context = { "object_list": queryset, } return r ender(request, "excuses/excuse_list.html", context) template.html {% for excuse in object_list %} <tr> <td>{{ excuse.reason }}</td> <td> {% for student in excuse.students.all %} {{student.get_full_name}}; {% endfor %} </td> </tr> {% endfor %} How can I sort the User set (excuse.students.all) alphabetically by a User field, for example: user.last_name? -
Uploading Wagtail images from outside of wagtail
In a Django model that cannot subclass Page, I want to convert an existing ImageField to use Wagtail images. I have redefined the field as: avatar = models.ForeignKey( 'wagtailimages.Image', null=True, on_delete=models.SET_NULL, related_name='+' ) The user needs to be able to upload an image to their profile view. In forms.py for the Django view, I have: avatar = forms.ImageField( label='Your Photo', required=False, error_messages={'invalid': "Image files only"}, widget=forms.FileInput()) When I upload an image to the view, it crashes on: Cannot assign "<InMemoryUploadedFile: filename.jpg (image/jpeg)>": "UserProfile.avatar" must be a "Image" instance. I'm pretty sure the problem is the field definition in the form, but I can't figure out what the right definition should be. I know that I'll need to manually attach the image to the UserProfile and the Collection, but need to get past this error first. Or is it a bad idea to try and use individual WT fields in a non-WT model? Thanks. -
How does django implement double underscore in filter?
I noticed that Django use double under score to define a lookup in Model.objects.filter instance. For example: Room.objects.filter(width__lte = 10) How does it work? How can I create my own function like Django and know that width__lte is actually separated for width and lower then or equal to 10 Thank you