Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django DateField form generates None in cleaned_data
After selecting dates from DateField's form in django and hitting submit button, is_valid() succeeds, but cleaned_data shows None. Does anyone know what is the issue? Thanks forms.py class DateForm(forms.Form): day_from = forms.DateField(label=u'Začiatok obdobia', input_formats=['%d/%m/%Y'], required=False, widget=forms.DateInput(format='%d/%m/%Y')) day_to = forms.DateField(label=u'Koniec obdobia', input_formats=['%d/%m/%Y'], required=False, widget=forms.DateInput(format='%d/%m/%Y')) views.py def dp_list(request): if request.method == "POST": form_date = DateForm(request.POST) if form_date.is_valid(): date_from = form_date.cleaned_data['day_from'] date_to = form_date.cleaned_data['day_to'] print(date_from, date_to, type(date_from), type(date_to)) print(form_date.cleaned_data) datelist.html <form action="" method="post"> {% csrf_token %} {{ form | materializecss:"s4"}} <span class="align-bottom"> <input class="btn primary-btn pink" type="submit" value="Zobraz"> </span> </form> Output of prints in console: None None class 'NoneType' class 'NoneType' {'day_from': None, 'day_to': None} -
How to make a modal pop up which work for web as well as mobile
Hi I am making a modal pop up for my website. I want is behave dual for website(desktop version) as well as mobile(small scren version). So how can i make it?? Thanks in advance -
Django middleware vs mixin
I am using oauth2_provider library. However they have not given an end point to check if a access token is valid. Token Introspection rfc says this is one non-normative way of doing so POST /introspect HTTP/1.1 Host: server.example.com Accept: application/json Content-Type: application/x-www-form-urlencoded Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW token=mF_9.B5f-4.1JqM&token_type_hint=access_token However oauth2_provider lib doesn't provide any way to check if a client has correct credentials or not. To check that should I add a middleware to my request and decorate the view like is done by CSRFExepmtMixin or should I write a mixin like ProtectedResourceMixin ? -
Django - changing validator name causes traceback in migration
i use Django 1.9.2 with python 3.4.2. In the first half of the development lifecycle i had this code: class ModificationOrder(ERN): ... san_amount = models.IntegerField(default=0, \ validators=[validate_modificationorder_san_amount]) , and i created an initial migration which resulted this line in the 0001_initial.py file: migrations.CreateModel( ... fields = [ ... ('san_amount', models.IntegerField(default=0, validators=[shop.validators.validate_modificationorder_san_amount])), ]) . Later i had a few migrations and i deleted the san_amount field from the model, but probably that is not related to my problem. Now i tried to change the name of the validator to validate_resource_san_amount, but after changing it runserver results this error: python manage.py runserver Performing system checks... System check identified no issues (0 silenced). Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f8ec1a5a510> Traceback (most recent call last): File "/home/csa.virtualenvs/sccdb34/lib/python3.4/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/home/csa/.virtualenvs/sccdb34/lib/python3.4/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check_migrations() File "/home/csa/.virtualenvs/sccdb34/lib/python3.4/site-packages/django/core/management/commands/runserver.py", line 163, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/home/csa/.virtualenvs/sccdb34/lib/python3.4/site-packages/django/db/migrations/executor.py", line 20, in __init__ self.loader = MigrationLoader(self.connection) File "/home/csa/.virtualenvs/sccdb34/lib/python3.4/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/home/csa/.virtualenvs/sccdb34/lib/python3.4/site-packages/django/db/migrations/loader.py", line 170, in build_graph self.load_disk() File "/home/csa/.virtualenvs/sccdb34/lib/python3.4/site-packages/django/db/migrations/loader.py", line 105, in load_disk migration_module = import_module("%s.%s" % (module_name, migration_name)) File "/home/csa/.virtualenvs/sccdb34/lib/python3.4/importlib/__init__.py", line 109, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 2254, in … -
Error 405 in class based views
I keep on getting a 405 error in my webpage for django. views.py from django.shortcuts import render from rest_framework.views import APIView from rest_framework.parsers import FileUploadParser # Create your views here. class FileUploadView(APIView): #parser_classes = (FileUploadParser,) template_name = "list.html" # def put(self, request, filename, format=None): # file_obj = request.data['file'] # # ... # # do some stuff with uploaded file # # ... # return Response(status=204) urls.py from django.conf.urls import url from rest_framework import renderers from views import FileUploadView urlpatterns = [ url(r'', FileUploadView.as_view()), ] list.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Minimal Django File Upload Example</title> </head> <body> <!-- List of uploaded documents --> {% if documents %} <ul> {% for document in documents %} <li><a href="{{ document.docfile.url }}">{{ document.docfile.name }}</a></li> {% endfor %} </ul> {% else %} <p>No documents.</p> {% endif %} <!-- Upload form. Note enctype attribute! --> <form action="{% url "list" %}" method="post" enctype="multipart/form-data"> {% csrf_token %} <p>{{ form.non_field_errors }}</p> <p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p> <p> {{ form.docfile.errors }} {{ form.docfile }} </p> <p><input type="submit" value="Upload"/></p> </form> </body> </html> Not sure if i need to post more of my code. But i keep on getting a 405 error on a get request. May i know what … -
Should I use any Learning Management System for my Django powered site?
Mine is a Django site that must provide prospective students with courses. Do I really need an LMS for this. If an LMS is the better way to go which one might you suggest for me. I might like something that goes well with the Django. What are your thoughts on Openedx Apologies, if the question is not relevant here. I am just starting out and couldn't find something that might help me make a decision. -
ImportError: cannot import name caches
I am using Django 1.6. I want to start working site. When you use python manage.py shell get an error: (test) D:\test>python manage.py shell Traceback (most recent call last): File "manage.py", line 11, in <module> execute_from_command_line(sys.argv) File "D:\testvenv\lib\site-packages\django\core\management\__init__.py", line 399, in execute_from_command_line utility.execute() File "D:\testvenv\lib\site-packages\django\core\management\__init__.py", line 392, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\testvenv\lib\site-packages\django\core\management\base.py", line 242, in run_from_argv self.execute(*args, **options.__dict__) File "D:\testvenv\lib\site-packages\django\core\management\base.py", line 280, in execute translation.activate('en-us') File "D:\testvenv\lib\site-packages\django\utils\translation\__init__.py", line 130, in activate return _trans.activate(language) File "D:\testvenv\lib\site-packages\django\utils\translation\trans_real.py", line 188, in activate _active.value = translation(language) File "D:\testvenv\lib\site-packages\django\utils\translation\trans_real.py", line 177, in translation default_translation = _fetch(settings.LANGUAGE_CODE) File "D:\testvenv\lib\site-packages\django\utils\translation\trans_real.py", line 159, in _fetch app = import_module(appname) File "D:\testvenv\lib\site-packages\django\utils\importlib.py", line 40, in import_module __import__(name) File "D:\testvenv\lib\site-packages\constance\backends\database\__init__.py", line 1, in <module> from django.core.cache import caches ImportError: cannot import name caches Tell me what I have a problem. And if it can depend on your database (not sure that Django is connected to the DB - I do not know how to check)? -
How to upload file with non-ascii file name using django rest framework
I'm using Django Rest Framework 3.4.4 and Django 1.10. This is post request in the client side: $http.post(fileUrl, fd, { withCredentials: true, transformRequest: angular.identity, headers: { 'Content-Type': undefined } }).success(function(data) { .... In the server side I have the following: def post(self, request, format=None): file_ids = [] file_list = request.FILES.getlist('file_path') for file in file_list: serializer = FileSerializer(data={'file_path': file}) if serializer.is_valid(): serializer.save() .... With filname such as foo.pdf the file is uploaded properly. But when filename contains, as example, Armenian letter: ա.pdf, I'm getting the UnicodeEncodeError error: UnicodeEncodeError, Traceback. -
Resolve for me this issue?
query (note: Q object ) = (AND: (u'c_s_p_field__icontains', u'q'), (NOT (AND: (u'meeting__client__icontains', u'ipsos'), ('meetingcandidat__canceled', 0)))) result = Candidat.objects.filter(email__isnull=False,c_s_p_field__isnull=False).exclude(stop=True).exclude(c_s_p_field="").annotate(age_annotated=date.today().year-F("naissance")).filter(query).distinct() this is query sql after django compile : SELECT DISTINCT ... puzz_candidat.owned_contact, puzz_candidat.source, (2016 - puzz_candidat.naissance) AS age_annotated FROM puzz_candidat WHERE ( puzz_candidat.c_s_p_ IS NOT NULL AND puzz_candidat.e_mail IS NOT NULL AND NOT (puzz_candidat.stop = True) AND NOT (puzz_candidat.c_s_p_ = '' AND puzz_candidat.c_s_p_ IS NOT NULL) AND puzz_candidat.c_s_p_ LIKE %q% AND NOT ( puzz_candidat.id IN ( SELECT U1.candidat_id AS Col1 FROM puzz_meeting_candidats U1 INNER JOIN puzz_meeting U2 ON ( U1.meeting_id = U2.id ) WHERE U2.Client LIKE %ipsos% ) AND puzz_candidat.id IN (SELECT U1.candidat_id AS Col1 FROM puzz_meeting_candidats U1 WHERE U1.canceled = False))) ORDER BY puzz_candidat.nom ASC, puzz_candidat.prenom ASC so my question is: i want to move the : puzz_candidat.id IN ( SELECT U1.candidat_id AS Col1 FROM puzz_meeting_candidats U1 INNER JOIN puzz_meeting U2 ON ( U1.meeting_id = U2.id ) WHERE U2.Client LIKE %ipsos% ) AND puzz_candidat.id IN (SELECT U1.candidat_id AS Col1 FROM puzz_meeting_candidats U1 WHERE U1.canceled = False))) into puzz_candidat.id IN ( SELECT U1.candidat_id AS Col1 FROM puzz_meeting_candidats U1 INNER JOIN puzz_meeting U2 ON ( U1.meeting_id = U2.id ) WHERE U2.Client LIKE %ipsos% AND U1.canceled = False) -
DJango Model form that display's user.profile.name info instead user.username
I have a ModelForm in Django that is used to take attendance at an event. It displays the user as plain text instead of a field: class PlainTextWidget(forms.Widget): def render(self, name, value, attrs=None): return mark_safe(value) if value is not None else '-' class AttendanceForm(forms.ModelForm): class Meta: model = Registration fields = ( "absent", "late", "excused", "user", # User foreign key ) widgets = { 'student': PlainTextWidget,} However, instead of having the form display a user's username, which is the default, I would like to display the user's profile string: user.profile.__str__ It seems like I could look it up in PlainTextWidget.render() using value as a filter on a Profiles queryset, but is there a more direct way to access user.profile in the form or the widget? How can I do this? -
Django Haystack - Combine two different SearchQuerySets using pipe operator
I am trying to run autocomplete on two different models, and then trying to combine the searchquerysets to obtain one final searchqueryset but I am not able to combine them using | (pipe operator). What am I doing wrong ? def autocomplete(request): sqs1 = SearchQuerySet().models(Doctor).load_all().autocomplete(content_auto_doc=request.GET.get('q', '')) sqs2 = SearchQuerySet().models(Clinic).load_all().autocomplete(content_auto_clin=request.GET.get('q', '')) sqs = sqs1|sqs2 suggestions = [result.object for result in sqs] the_data = json.dumps({ 'results': suggestions, }) return HttpResponse(the_data, content_type='application/json') -
Django Need assistance to achieve the below result - custom view on admin site
Need assistance on achieving this I would like to have a custom view on a model admin. Current behavior: When i click on Model object(1) it takes me to "site/app_label/1/change" This leads to edit of the object with its inlines. What I want to achieve: when i click on a object should redirect to "site/app_label/1" it should show a list view of its inlines (Not a editable list) i will put a separate button which will lead to "site/app_label/1/change" I want this list view to be similar to Django default style listing. My two models are: class RunConfig(models.Model): config_name = models.CharField(max_length=100,blank=False,null=False, unique=True ) class Jobs(models.Model): config_name = models.ForeignKey('RunConfig',on_delete=models.CASCADE,) job_name = models.TextField(blank=True,null=True, ) parameters = models.TextField(blank=True,null=True, ) exec_order = models.IntegerField(help_text="Execution Order") admin.py class JobsInline(SortableInlineAdminMixin, admin.TabularInline): model = Jobs extra = 1 class RunConfigAdmin(admin.ModelAdmin): list_display = ('config_name',) What I have tried till now: my plan was to override the changelist template but that did not work as it started to complain about no reverse match found for app_list in admin.py added custom url def get_urls(self): urls = super(RunConfigAdmin, self).get_urls() my_urls = [ url(r'^(?P<pk>[0-9]+)/$', self.admin_site.admin_view(RunConfigDetailView.as_view(), cacheable=True), name='rc-detail'), ] return my_urls + urls created a detailed view on views.py i was expecting it wil … -
invalid syntax (views.py, line 34)
I'm new to django, I'm getting an invalid syntax error in views.py file. Is there a way i can debug syntax errors in django? When running the development server with python manage.py runserver I'm getting the below error =============== SyntaxError at / invalid syntax (views.py, line 34) Request Method: GET Request URL: http://localhost:8000/ Django Version: 1.8.5 Exception Type: SyntaxError Exception Value: invalid syntax (views.py, line 34) Exception Location: /home/arajguru/training/mycode/myshop/orders/urls.py in <module>, line 2 Python Executable: /home/arajguru/training/mycode/env/myshop/bin/python ....... =============== Below is my views.py file: from django.shortcuts import render from .models import OrderItem from .forms import OrderCreateForm from cart.cart import Cart #from .tasks import order_created from django.shortcuts import render, redirect from django.core.urlresolvers import reverse def order_create(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save() for item in cart: OrderItem.objects.create(order=order, product=item['product'], price=item['price'], quantity=item['quantity']) # clear the cart cart.clear() # launch asynchronous task # order_created.delay(order.id) # set the order in the session request.session['order_id'] = order.id # redirect to the payment return redirect(reverse('payment:process')) else: form = OrderCreateForm() return render(request,`enter code here` 'orders/order/create.html', {'cart': cart, 'form': form} -
Extending admin user profile in Django
I want to store database users in admin page with admin authentications. For this aim, I need to modify UserAdmin fields for storing more columns. But I am receiving below error: DatabaseError at /admin/auth/user/1/change/ ORA-00904: "PROFILE"."USER_ID": invalid identifier app name profiles, class name is profile. here is the code: models.py class profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE,null=True,blank=False) id = models.FloatField(primary_key=True) ip = models.CharField(max_length=20, blank=True, null=True) ad = models.CharField(max_length=20, blank=True, null=True) soyad = models.CharField(max_length=20, blank=True, null=True) username = models.CharField(max_length=200, blank=True, null=True) password = models.CharField(max_length=200, blank=True, null=True) role = models.FloatField(blank=True, null=True) email = models.CharField(max_length=2000, blank=True, null=True) parent_username = models.CharField(max_length=2000, blank=True, null=True) notif_ask = models.CharField(max_length=3, blank=True, null=True) notif_answer = models.CharField(max_length=3, blank=True, null=True) department = models.CharField(max_length=100, blank=True, null=True) position = models.CharField(max_length=50, blank=True, null=True) internal_tel_num = models.CharField(max_length=30, blank=True, null=True) mob_tel_num = models.CharField(max_length=50, blank=True, null=True) image = models.CharField(max_length=300, blank=True, null=True) ata_adi = models.CharField(max_length=20, blank=True, null=True) class Meta: managed = True db_table = 'profile' def __str__(self): return self.user.username def __unicode__(self): return self.user.username @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: profile.objects.create(user=instance) instance.profile.save() admin.py class ProfileInline(admin.StackedInline): model = profile can_delete = False verbose_name_plural = 'profile' fk_name = 'user' class CustomUserAdmin(UserAdmin): inlines = (ProfileInline, ) def get_inline_instances(self, request, obj=None): if not obj: return list() return super(CustomUserAdmin, self).get_inline_instances(request, obj) admin.site.unregister(User) admin.site.register(User, … -
allauth social account sign up send signup information
I have two different signup pages for two different groups of users. These group of users do not relate to each other in any way, so they are stored and managed seperately. However, during social account signup, I need information of what groups do they belong and that can only be found out by the signup page from which they register using a link. Heres the button for facebook signup. <a class="btn btn-primary p-sm" href="{% provider_login_url "facebook" process="" method="oauth2" %}"><b>Sign up with facebook</b></a> Now, the question is how do i get the page source on the allauth signals so i can update my users instance later. -
Django--Is there a way to reference/get the current page URL from within a template?
What I had in mind was something along the lines of {% if <"the current page url = '/'"> %} {% include '...' %} How can I make this work using template tags? -
Django all-auth redirect to url with post post after login
I am using django-allauth for my project. Flow: User fills a form.(anonymous user, not logged in) If user is not logged in, redirect to login page. After successful login, form data filled in step 1 should be saved in db. html <form action="{% url 'account_login' %}?next={% url 'issue' %}" method="POST"> {% csrf_token %} <button type="submit" id="btn" class="btn btn-default btn-danger" style="background:#dd4252; height:43px; font-size:14px;">Enter Bug</button> <label style="color:#dd4252; margin-left: 20px"> Win +3 points!</label> </form> Here, I am able to redirect to 'issue' (using url resolver) page but with get request and not "post" method. My question is how do i post to 'issue' page after login page has redirected there. -
Having trouble with passing over image files to celery worker
I'm making a Django api server for an app. Concept of the app is a photo diary and an user can upload diary(a post) with many photos.(ForeignKey related) The api server handles image files, so I use VersatileImageField, django third-party module, for the imagefield. The client can request with many image files, so I want to use Celery for the image handlings. To Celery worker, I pass over django.core.files.uploadedfile.InMemoryUploadedFile(File)s and an ID of an instance of a model. But when I pass File, there is an error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte So my new strategy is 1. Use python base64 module and encode the image file and overwrap the File 2. Send over image File to the celery worker 3. The task decode the File and make a Image instance with it. Here is the serializer create method for passing over File to the task. def create(self, validated_data): photos_data = list(validated_data.pop('photo_set')) for photo in photos_data: # photos_data is the list of `InMemoryUploadedFile` # Encoding image file encoded_photo = base64.b64encode(photo.read()) photo.seek(0) photo.truncate() photo.write(encoded_photo) photo.seek(0) post = Post.objects.create( **validated_data, ) # celery task task_upload_photos.delay(photos_data=photos_data, post_id=post.id) return post And the task is like this … -
Setting up a Django server
so I want to set up a Django server on my Digital Ocean droplet. I have found this tutorial. I got to the point where I am configuring my gunicorn.conf file and I got stuck: I dont seem to have a .socket file, nor can I find how to write one. I am not using an env, as an FYI. -
I accidentally deleted django_admin_log and now i can not use the django admin
I get this error "ProgrammingError at /admin/ relation "django_admin_log" does not exist LINE 1: ..."."app_label", "django_content_type"."model" FROM "django_ad..." django_admin_log table does not exist in the database. Anyone know how I can create it? Am not worried about deleting the data for my app. -
Dynamic fields querying in django
I have a model containing 50 plus fields, while I would like to fetch the specific fields say some 3 or 4 fields only from database. In case of static query, the above could be solved as follows field_value = model.objects.values_list(field1, field3, field9) while how the same could be replicated when the above fields are dynamically chosen. Is there any way if we could store the fields for retrieval as a list and use the list as input parameter for values_list. -
What do "{%" do in HTML?
I've added Django messages to my app using the official documentation. In it it says to add something like this to my template: {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} I have no idea what the percentage signs do, they're not actual HTML right? -
Dynamically Change Authentication Classes Django Rest Framework
I understand that we can set up authentication classes in class based viewsets like this: class ExampleViewSet(ModelViewSet): authentication_classes = (SessionAuthentication, BasicAuthentication) However, is there a way to dynamically change the authentication class based on the request method? I tried overriding this function in my ExampleViewSet: def get_authenticators(self): # Found in if self.request.method == "POST": authentication_classes.append(authentication.MyCustomAuthentication) return authentication_classes However, django rest does not have the request object setup at this point: 'ExampleViewSet' object has no attribute 'request' Note: not real variable names - just for example purpose. -
What are the difference between Serializer's create() and ModelViewset's create() perform_create()
I want to clarify the given documentation of django-rest-framework regarding the creating of a model object. So far i found that there are 3 approach on how to handle such events. The Serializer's create() method. Here is the documentation class CommentSerializer(serializers.Serializer): def create(self, validated_data): return Comment.objects.create(**validated_data) The ModelViewset create() method. Documentation class AccountViewSet(viewsets.ModelViewSet): queryset = Account.objects.all() serializer_class = AccountSerializer permission_classes = [IsAccountAdminOrReadOnly] The ModelViewset perform_create() method. Documentation class SnippetViewSet(viewsets.ModelViewSet): def perform_create(self, serializer): serializer.save(owner=self.request.user) This three approach is important depending to your application environment. But WHEN do we need to use each create() / perform_create() function??. In the other hand i found some account that two create methods were called for a single post request the modelviewset's create() and serializer's create(). Hopefully anyone would share some of their knowledge to explain and this will surely be very helpful in my development process. -
Django: customer user model superuser
I've created an app with customer user model which inherits from AbstractBaseUser and created a UserManager. Everything works just fine, except when I try to create a second super user, it replaces the first one. Also, when I log into admin page, it doesn't allow me to edit the user with superuser status. I'm not sure what's causing it, but here are the codes that I'm using... models.py class User(AbstractBaseUser, PermissionsMixin): id = models.CharField(_('customer id'), primary_key=True, max_length=255) email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'), max_length=30) last_name = models.CharField(_('last name'), max_length=30) is_staff = models.BooleanField(_('staff status'), default=False, help_text=_('Designates whether the user can log into this admin site.')) is_active = models.BooleanField(_('active'), default=True, help_text=_('Designates whether this user should be treated as active. Unselect this instead of deleting accounts.')) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) phoneNumber = PhoneNumberField(unique=True) #restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE,null=True, blank=True) orderStatus = models.BooleanField('Order Placed', default=False) numOffense = models.PositiveIntegerField('# Offense', default=0) company = models.CharField(_('company'), null=True, blank=True, max_length=50) handle = models.SlugField(unique=True, max_length=30) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name','last_name','phoneNumber'] class Meta: verbose_name = _('user') verbose_name_plural = _('users') def get_full_name(self): ''' Returns the first_name plus the last_name, with a space in between. ''' full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() …