Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - dropdown form with multiple select
I need guidance building a django dropdown forms.Form field in which I can select multiple choices. I need to select multiple locations on the office field of the form. When submitted, the form needs to return a list of the chosen offices (e.g. ["New York", "Los Angeles"] or ["Austin"]). Returning a tuple is also acceptable. The best I can do right now is build a multipleChoiceField for office with the following: from django import forms class my_Form(forms.Form): OPTIONS = [ ("0", "*ALL"), ("1", "New York"), ("2", "Los Angeles"), ] office = forms.MultipleChoiceField( choices=OPTIONS, initial='0', widget=forms.SelectMultiple(), required=True, label='Office', ) resulting in this form field layout: However, I would like this field to be a dropdown, to take up less space on the page. I found this djangosnippet but (1) a few people have mentioned it appears out of date (I can't confirm), and (2) I first want to check if a built-in django form/widget setup can fulfill this task before using custom code. -
Subprocess calling application with window
At a moment I need to run external application (Excel), for what I've tried subprocess and multiprocessing modules with os.system called either from the main process or from subprocess. The problem is: open Excel window from my script close script, window still open re-run script script doesn't respond to incoming HTTP requests (it's django server actually) close Excel - script begins responding -
How do I get the filepath of an uploaded file?
I'm having difficulty passing the path of a file to a library called Textract. def file_to_string(filepath): text = textract.process(filepath) print text return text Here is my upload form in views.py if request.method == 'POST': upload_form = UploadFileForm(request.POST, request.FILES) if upload_form.is_valid(): file = request.FILES['file'] filetosave = File(file=file, filename=file.name) filetosave.save() if validate_file_extension(file): request.session['text'] = file_to_string(file) # something in here else: upload_form=UploadFileForm() Now Textract expects a path to go into file_to_string(filepath). If I try to pass in the file object it gives me an error: "coercing to Unicode: need string or buffer, InMemoryUploadedFile found". But if it is an InMemoryUploadedFile type, how do I get the path? I understand this is stored in memory and doesn't have a path. How should I handle this -- should I save the file object first and then try to access it? If I save the file and then try request.session['text'] = file_to_string(file.name) it gives a MissingFileError, though the docs say that this should give the name of the file including the relative path from MEDIA_ROOT. Thanks a lot in advance. -
Django validate what user sends from admin panel
I am kind of new to Django, and i am trying to make sort of a news website where users can submit articles(with an account) but the admin needs to check them before they can be posted. Is that possible? -
Django group sublist permission
I need to restrict user permission to a sublist of groups. For example, I have a user USER1 who belongs to groups GROUP1, GROUP2 and ADMIN. At connection the user can choose to connect with ADMIN permissions or GROUP1 permissions or GROUP2 permissions or GROUP1 + GROUP2 permissions Is it possible to do this in Django ? Regards, -
Extended User model and Serialize
Serializer: class ExtUserSerializer(serializers.ModelSerializer): class Meta: model = ExtUser fields = ('id','nickname') def create(self, validated_data): return ExtUser.objects.create(**validated_data) When I try to registrate new User I got error: AttributeError: 'ExtUserSerializer' object has no attribute 'init_data' -
How to excute postgre query asynchronously in django
In current scenario result2 not get executed until result1 one finished its execution. I want to execute select * from Test1 and select * from Test2 asynchronously.result2 should not wait utile result1 complete its execution.And finally send both the result set to client at a time. def fetchQueryData(request): cur=connection.cursor() cur.execute("select * from Test1") result1=cur.fetchall() json1=result1[0][0] cur.execute("select * from Test2") result2=cur.fetchall() json2=result2[0][0] cur.close() return JsonResponse([json1,json2]) -
How can I use two keys with defaultdict?
I am trying to create a defaultdict with nested keys. Here is the view that I wrote, but apparently multiple keys don't work in defaultdict. def routine_view(request, klass_id): days = Routine.DAYS periods = Routine.PERIODS class_details = defaultdict(list) classes = Routine.objects.filter(klass_id=klass_id) for cls in classes: class_details[cls.day][cls.period].append(cls) context = { "days": days, "periods": periods, "class_details": class_details } return render(request, "routine/routine_view.html", context) When I run this view I get the following error: IndexError at /routine/1/ list index out of range -
Django forms: Error message display all the time, not only after errors
I'm building my own site with Django's Framework. I made a form for creating a new account. It works well but I have a problem with my errors messages. All my errors are already display when I first arrive on the page. After submit, if a field is wrong, the page newly updated display only the wanted messages. Here is a view of my page at my first arrival So, my question is: How can I do for display the message only if a field is wrong ? I already succeed to personalize each messages. I paste you my different django files: views.py @csrf_exempt def create_new_user(request): form = UserCreateForm(request.POST) if request.method=="POST": if form.is_valid(): user = form.save() messages.info(request, "Merci pour votre enregistrement, vous etes maintenant connecte") new_user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1'] ) login(request, new_user) return HttpResponseRedirect('/') return render_to_response('lejeudesbars/register.html', RequestContext(request, {'form': form})) else: return render(request, 'lejeudesbars/register.html', {'form': form}) forms.py class UserCreateForm(UserCreationForm): captcha = ReCaptchaField(error_messages={'required': 'Captcha: Validation obligatoire'}) email = forms.EmailField(required=True) username = forms.CharField(error_messages={'required': 'Pseudo: Champ obligatoire'}) email = forms.EmailField(error_messages={'required': 'Email: Champ obligatoire'}) password1 = forms.CharField(widget=forms.PasswordInput(), error_messages={'required': 'Mot de passe: Champ obligatoire'}) password2 = forms.CharField(widget=forms.PasswordInput(), error_messages={'required': 'Mot de passe: Confirmation obligatoire'}) class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, … -
Api design for payment gateway
please note : at this point this is just for practice to get familiar with the process and it's problems , it's not for any known bank or credit /payment company ... btw im going to write it with php/laravel or python/django that's why i've taged both lets say i'm writing api for my online payment gateway which serve various websites who wants to have online transaction for their shoppers so they register in my gateway and i give them an id code lets call it client_website_code so i have 2 key tables in api database payment_requests = refrence_id , amount , client_website_id , order_id payments_successful = id , trace_code , amount , client_website_id , order_id when someone shop something in the client website , it will send these parameters to my api step 1 client_website_code order_id amount i'll check for the api_code in database and read the owner of that account /client website if everything is ok i'll return back these parameters step 1.1 succ = 10 refrence_id = 123 // id for current request in api payment_requests table then client website would create blow link using refrence_id and redirect shopper to this address http://api.com/pay/refrence_id which is basically api … -
How to render output of cartridge API's on custom HTML page?
I am working on a cartridge project. I have created custom html templates for better visual and now I want to render all data which is coming through cartridge's built in APIs on my custom html pages. For.ex. I have a product.html, on which I want to show all products stored in db (category wise). Actually, I tried to explore url, url("^shop/", include("cartridge.shop.urls")), I am not getting that on which API or Function, this url is hitting. -
Custom user model permissions
So everything works fine, but I can't add permissions to my users through admin. When I change an user the box with User permissions appears in place but all the permissions I add have no effect. When I log in as that user I don't have permission to do anything. This is what I have in "accounts.models": from django.utils import timezone from django.db import models from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.models import AbstractBaseUser, BaseUserManager from django.core.mail import send_mail from django.utils.translation import ugettext_lazy as _ from django.utils.http import urlquote class CustomUserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): now = timezone.now() if not email: raise ValueError('The given email must be set') email= self.normalize_email(email) user = self.model( email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) def create_superuser(self, email, password, **extra_fields): return self._create_user(email, password, True, True, **extra_fields) class CustomUser(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=30) email = models.EmailField(unique=True) date_joined = models.DateTimeField(_('date joined')) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = CustomUserManager() class Meta: verbose_name=_('user') verbose_name_plural = ('users') def get_absolute_url(self): return "/users/%s/" % urlquote(self.email) def get_full_name(self): return self.username def get_short_name(self): return self.username … -
'filters' is not a registered tag library
I have an issue regarding template filter. I have used django allauth for user registration. I have edited its signup.html and used loop to iterate over the fields to show them dynamically. I could show the fields but could not define the type field. What i did is account/signup.html {% load filters %} <form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}"> {% csrf_token %} {% for field in forms.visible_fields %} <input type="{{ field.field.widget|input_type}}" name="{{ field.name }}" id="{{ field.id_for_label}}" class="form-control"> {% endfor %} </form> template filter inside main app(filters.py) from django import template register = template.Library() @register.filter('input_type') def input_type(ob): return ob.__class__.__name__ templates location 'DIRS': [os.path.join(BASE_DIR, 'templates') As i am using django allauth where should i place my template filter code? Sign up form to extend the allauth form using first name and last name is inside main app. -
Django: How to create object which has ManyToManyField in shell?
I think that showing code is much easier than explanation. models.py class Product(TimeStampedModel): name = models.CharField(max_length=120, unique=True) slug = models.SlugField(null=True, blank=True) description = models.TextField(max_length=400, blank=True) is_active = models.BooleanField(default=True) place_category = models.ForeignKey( "PlaceCategory", related_name="products_by_place", # category.products_by_place.all() ) subject_category_set = models.ManyToManyField( "SubjectCategory", related_name="products_by_subject", # category.products_by_subject.all() ) objects = ProductManager() class Meta: ordering = ('-created',) def __str__(self): return self.name def get_absolute_url(self): return reverse( "products:product_detail", kwargs={ "slug": self.slug, } ) class Category(TimeStampedModel): name = models.CharField(max_length=25, unique=True) is_active = models.BooleanField(default=True) class Meta: abstract = True def __str__(self): return self.name class PlaceCategory(Category): class Meta: verbose_name = "Place Category" verbose_name_plural = "Place Categories" class SubjectCategory(Category): class Meta: verbose_name = "Subject Category" verbose_name_plural = "Subject Categories" This is what I'm trying to do in shell. # place category self.place_category = PlaceCategory.objects.create(name="학교") # subject category self.subject_category1 = SubjectCategory.objects.create(name="사람") self.subject_category2 = SubjectCategory.objects.create(name="꽃병") # product self.product = Product.objects.create( name="product name1", place_category=self.place_category, subject_category_set=( self.subject_category1, self.subject_category2, ) ) But it doesn't work. Any idea? What I could think of is moving ManyToManyField from Product to SubjectCategory. But I want know as in my code. Thanks. -
API access authentication/application key (django/nginx/gunicorn)
I have a web app created in django, running in gunicorn app server behind nginx webserver/reverse-proxy. I need to have external application to access some processed data (csv/json), for which I need some sort of authentication. The basic django auth/login is not optimal as a simple script needs to pull the data with a simple request, no cookies etc (not created by me). For now, I have set up the service being available with https/tls only created an IP-filter in django to reduce the "attack surface" with: request.META['HTTP_X_REAL_IP'] and using nginx to forward the ip with: proxy_set_header X-Real-IP $remote_addr; Next I was thinking to include and application key (hash of a pw or something) which needs to be included in the request, and is checked against db for a list of valid keys. Is this a suitable api authentication or is there something else which can be used/recomennded? some sort of application key framework? -
exposing multiple databases in django admin
My use case requires me to expose multiple databases in the admin site of my django project. Did that following this link: https://docs.djangoproject.com/en/dev/topics/db/multi-db/#exposing-multiple-databases-in-django-s-admin-interface Here's the code used: class MultiDBModelAdmin(admin.ModelAdmin): # A handy constant for the name of the alternate database. using = 'other' def save_model(self, request, obj, form, change): # Tell Django to save objects to the 'other' database. obj.save(using=self.using) def delete_model(self, request, obj): # Tell Django to delete objects from the 'other' database obj.delete(using=self.using) def get_queryset(self, request): # Tell Django to look for objects on the 'other' database. return super(MultiDBModelAdmin, self).get_queryset(request).using(self.using) def formfield_for_foreignkey(self, db_field, request, **kwargs): # Tell Django to populate ForeignKey widgets using a query # on the 'other' database. return super(MultiDBModelAdmin, self).formfield_for_foreignkey(db_field, request, using=self.using, **kwargs) def formfield_for_manytomany(self, db_field, request, **kwargs): # Tell Django to populate ManyToMany widgets using a query # on the 'other' database. return super(MultiDBModelAdmin, self).formfield_for_manytomany(db_field, request, using=self.using, **kwargs) And then: admin.site.register(Author, MultiDBModelAdmin) admin.site.register(Publisher, PublisherAdmin) othersite = admin.AdminSite('othersite') othersite.register(Publisher, MultiDBModelAdmin) The example's documentation states: This example sets up two admin sites. On the first site, the Author and Publisher objects are exposed; Publisher objects have an tabular inline showing books published by that publisher. The second site exposes just publishers, without the inlines. What I … -
Log Django-Startup-Error with gunicorn
I've got a Django-App(1.10) and it is running with gunicorn(19.6). All I want is that ALL log-messages which are logged to stdout/stderr should be logged with the gunicorn-logger. Normal print and log-calls will be logged. The only thing which is not working is when Django throws errors. For example when Django can't connect to the database. I looked at the code and it seems that Django writes in that case with OutputWrapper to stdout/stderr. In this scenario Gunicorn isn't grabbing the message. I am starting gunicorn with ../env/bin/gunicorn <myapp>.wsgi:application --capture-output The App is starting and everything is fine. The only problem is that the error-message from Django (Can't connect to database...) isn't showing. Am I using gunicorn wrong? -
I want to show progress bar in django template, on the basis of django post process/progress(form is ajax submit). is it possible?
def post(self, request, *args, **kwargs): if attorney_data_list: for i in len(attorney_data_list): if(index%3 == 0): process_percent = int(100 * float(index) / float(len(case_data_list)+1)) else: pass i want this process_percent value in django template on every for loop.is it possible? -
Frontend and backend flows in case of facebook login
I am implementing Facebook login on Android App with my backend written in Django. I'm able to login in a user and access his FB Id and Access Token. Now, which is the best way to implement the next flow? Option 1: Make graph calls from Android App itself and get all the details of user and then send the data to the backend to register the user. Subsequent calls can be made to fetch the details from backend. Option 2: Pass the access token to backend and backend does the rest. It makes graph calls. Android app can simply fetch the details from backend. I couldn't find any official facebook SDK for Django/python. So, i'll have to probably leverage HTTP calls. Moreover, my backend does a lot of internal requests while creating a new user. So, what should be the ideal choice? -
Hi i am very new to django. i am trying to write a code to display items in a database in a webpage and edit selected items
I am getting the below error when I tried to run the edit part. Displaying the contents of database in webpage is working fine. I have put up code for just the edit part. Please help. error: TypeError at /edit/ init() takes exactly 1 argument (2 given) views.py class userUpdate(UpdateView): model = user fields = ['name','phone','dob','gender'] template_name_suffix = '_update_form' models.py from django.db import models from django.forms import ModelForm from django.core.urlresolvers import reverse class user(models.Model): name = models.CharField(max_length= 200 ) phone = models.BigIntegerField() dob = models.DateField() MALE = 'M' FEMALE = 'F' gender_choices = ( (MALE, 'M'), (FEMALE, 'F'), ) gender = models.CharField( max_length= 20, choices= gender_choices, ) def get_absolute_url(self): return reverse('user_update_form', kwargs={'pk': self.pk}) forms.py from django import forms from django.contrib.admin.widgets import AdminDateWidget from .models import user class DateInput(forms.DateInput): input_type = 'date' gender_choices = ( ('male', 'M'), ('female', 'F'), ) class NameForm(forms.Form): name = forms.CharField(max_length=200) phone = forms.IntegerField() dob = forms.DateField(widget= AdminDateWidget) gender = forms.ChoiceField( widget=forms.RadioSelect, choices = gender_choices, ) urls.py from django.conf.urls import include, url from newapp import views urlpatterns = [ url(r'^edit/',views.userUpdate, name = 'user_update_form'),] user_update_form.html <form action="" method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Update" /> </form> -
recognize sound in python
I am working with android and ios developer for an app. I am developing web services in python. There is a module in that app in which user has to save his voice and whenever that user says anything then app will match that user's voice with voice saved in database. If voice matches then mobile should start ringing. What is the best way to accomplish this task, or is it possible through python ? -
Django Model Fields Radio Button
how can i create a radio button using Django model fields #models.py GENDER_CHOICES = ( ('M', Male), ('F', 'Female') ) class Profile(models.Model): gender = models.CharField(choices=GENDER_CHOICES, max_length=128) the above field is rendering as a select field, But i want to make it as a radio button. If the question is not correct, somebody please correct the question -
atomic transaction is not working django rest
I am using DRF, API View Class based view, post method. Parameters are : file Logic : Do some validation on file and save file progressively (different type of objects) I am trying to rollback the transaction if exception happens while saving the rest of the file. I set 'ATOMIC_REQUESTS' : True class SaveXMlFile(APIView): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] parser_classes = [FormParser, MultiPartParser] def post(self, request): """ Save xml file --- # inputs parameters: - name: game_log_file description: Game log file type: file required: true paramType: post allowMultiple: false """ try: # import pdb; pdb.set_trace() game_log_file = request.data['game_log_file'] file_store = FileStore.objects.create(uploaded_file=game_log_file) xml_file_processing = ProcessXmlFile(file_store) already_saved = xml_file_processing.was_file_saved() player_exists = xml_file_processing.player_exists() if already_saved: file_store.delete() return Response({"info": "File was saved previously, no action taken place this time."}, status=200) if not player_exists: file_store.delete() return Response({"info": "No player exists in the database, ask your administrator to create some."}, status=200) xml_file_processing.save() file_store.delete() return Response({"success": "File has been saved."}, status=status.HTTP_201_CREATED) except Exception as err: error = "{0}".format(str(err)) return JsonResponse({'exception': error}, status=500) I am deliberately throwing exceptions when half of the file has been saved but committed transactions don't rollback even exception is raised in the process. Any thoughts would be appreciated. -
Correct way to extend AbstractUser in Django?
I'm trying to integrate two django apps where each had their individual auths working. To do that, I'm trying to subclass AbstractUser instead of User. I'm following the PyBB docs and Django#substituting_custom_model. I've removed all migration files in all my apps apart from their individual init.py (including the migrations from the PyBB library sitting in my site-packages). I've also changed the Mysql database to a blank one to start afresh and I'm trying to subclass AbstractUser as shown below. My Models.py: from django.contrib.auth.models import User from django.contrib.auth.models import AbstractUser from django.db import models class Student_User(models.Model): """ Table to store accounts """ su_student = models.OneToOneField(AbstractUser) USERNAME_FIELD = 'su_student' su_type = models.PositiveSmallIntegerField(db_column='su_type', default=0) su_access = models.TextField(db_column='su_access', default='') su_packs = models.TextField(db_column='su_packs', default='') REQUIRED_FIELDS = [] def __unicode__(self): return str(self.su_student) My settings.py: AUTH_USER_MODEL = "btcat.Student_User" PYBB_PROFILE_RELATED_NAME = 'pybb_profile' When running makemigrations for my primary app, I get this error: app.Student_User.su_student: (fields.E300) Field defines a relation with model 'AbstractUser', which is either not installed, or is abstract. How do I achieve what I am trying to do here? PS: The app was working fine with onetoone with User without username_field or required_field. -
Django ModelAdmin custom method obj parameter
In Django's document Django Document It has following code. from django.contrib import admin class AuthorAdmin(admin.ModelAdmin): fields = ('name', 'title', 'view_birth_date') def view_birth_date(self, obj ): return obj.birth_date view_birth_date.empty_value_display = '???' I don't understand in the custom method view_birth_date(self, obj ) where this obj parameter came from? Note in the last line, it called this function, view_birth_date.empty_value_display = '???' but did not pass any parameter for obj. I don't understand where how obj got a value. Thanks!