Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Could not parse the remainder error on django url parameters
I get the following error: Could not parse the remainder: '=' from '=' on the following line: <a href="{%url 'secrets:like_it' id = secret.id%}">Like</a> -
design a serializer for device and device group
I have a device and device group table. A group can have multiple devices but a device can be on only one group. For example there is a device named device1, device2, device3, device4 and a group named Personal, Home etc. device1, device2 can be on personal group but either device1 or device2 now cant be on Home group because same device cannot be in different group. I am having very difficulty to store multiple devices in a group. How should my model be designed and serializer? Right now my model and serializer looks like following. This way i have no idea how can i store multiple devices in a single group if user wanted to have multiple devices in a group class Device(models.Model): name = models.CharField(blank=True, null=True) device_group = models.ForeignKey('DeviceGroup', null=True, blank=True) class DeviceGroup(models.Model): name = models.CharField(max_length=250, blank=False, null=False) class DeviceGroupSerializer(serializers.ModelSerializer): name = serializers.StringRelatedField() class Meta: model = DeviceGroup fields = ('name',) class DeviceSerializer(serializers.ModelSerializer): device_group = DeviceGroupSerializer(required=False) class Meta: model = Device fields = ('id', 'name', 'description', 'device_group') -
Override label in Django Dorms
I have 3 sections with identical fields, except for label on "title" field. For all of them I'm using same Django Form. In views I have: def get(self): context = self.CONTEXT_CLASS(self.MODEL_CLASS) context.messages = self.get_messages() context.section1 = InvoiceContentForm() context.section2 = InvoiceContentForm() context.section3 = InvoiceContentForm() self.render_jinja('templates/invoice/add_edit.html', context.as_dict) My form: class InvoiceContentForm(forms.Form): """Form for content of given section in add/edit invoice page.""" DEFAULT_ATTRS = {'class': 'form-control'} title = forms.CharField( help_text='Title should be up to 24 characters long.', label=u'Title', required=True, widget=FormTextInput(), ) (...) Is there any way I can change title's label on InvoiceContentForm() while assigning it to context.section1 = InvoiceContentForm()? -
How to get value from form and redirect to /value in Django 1.10
I need to get value from tag and redirect to '/value/' by submit. Now I'm getting: 'ApartmentForm' object has no attribute 'cleaned_data' I'm totally missing something. forms.py class ApartmentForm(ModelForm): class Meta: model = Apartment fields = ['title'] views.py def index(request): context = {} context['apartments'] = get_list_or_404(Apartment) if request.method == 'POST': form = ApartmentForm(request.POST or None) context = {'form': form,} id = form.cleaned_data.get('id', None) return redirect(id) else: context['apartment_form'] = ApartmentForm return render(request, 'main/main.html', context) template <form action="/{{ apartment.id }}" method="post"> {% csrf_token %} <p><select size="10"> <option disabled>Chose apartment</option> {% for apartment in apartments %} <option value="{{ apartment.id }}">{{ apartment.title }}</option> {% endfor %} </select></p> <input type="submit" value="Chose"> </form> -
How to add CSS to text input in Django Python
I am very new to Django Python and was trying to figure out if there is a way to beautify my input text. Currently, I have both login and register functions done and I want both of these functions to be in one HTML page. Here is my code: views.py def login(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): auth = EmailAuthBackend() user = auth.authenticate(email=request.POST['email'], password=request.POST['password']) if user is not None: django_login(request, user) return HttpResponse("Success Login") else: form = AuthenticationForm() return render(request, 'App/index.html', {'form': form, }) def register(request): if request.method == 'POST': form = RegistrationForm(data=request.POST) if form.is_valid(): user = form.save() return redirect('/') else: form = RegistrationForm() return render(request, 'App/index.html', {'form': form, }) I understand that I can use "{{ form.as_p }}" to display the input texts but is there a way to do it by using HTML tags to display the input texts instead? Current input text in html that is not linked to views.py (index.html): <form class="form" method="post"> {% csrf_token %} <input type="text" name="email" placeholder="Email"> <input type="password" name="password" placeholder="Password"> <button class="btn-lg btn-cv" type="submit">Log in</button> </form> <form class="form"> {% csrf_token %} <input type="text" id="signup_email" placeholder="Email"> <input type="password" id="signup_password1" placeholder="Password" class="showpassword"> <input type="password" id="signup_password2" placeholder="Password" class="showpassword"> <button id="signup" class="btn-lg … -
apache authentication against django application
I have the following problem: I wrote an application in Django, basically it’s some kind of management platform for my choir. Now we have some files that we want to provide to our members, but only to them (i.e. registered users). Additionally, there are some files that should only be accessible to the management. Ideally, I want to be able to define in the database who can access which files. Here is some information about the environment: Server OS Debian 8.7 Python version 2.7 Django version 1.10 Mod_wsgi version 4.3 What have I tried so far? Django documentation provides a very, very small example of how to authenticate against the database. The part where I only validate whether the user is a valid user works. Although it kind of sucks, since the users have to login again every time they access a file. The part where I validate whether the user is a group doesn't work at all. Apache says: Unknown Authz provider: group Then I started to look up this problem, which led me here. When I use the option wsgi-group the apache configuration doesn't cause any problems, but it apparently doesn't validate whether the user is in the … -
Get user input and pass to views for processing and pass the output to templates for display
I'm using Django for my website project. I need to read and view html file from a directory in my desktop. views.py from django.shortcuts import render def Test(request): import os summary = "1A" input1 = "7533C383" input2= "5263" result = input1 + "_" + input2 + "_" + summary path = "C:/Users/MFBW/Desktop/" shp_list = [] for dirpath, dirnames, x in os.walk(path): for f in x: if f.startswith(result) and f.endswith(".html"): fullpath = os.path.join(dirpath, f) shp_list.append(fullpath) with open(fullpath, 'r')as f: f_contens = f.read() print(f_contens) kau = f_contens context = { "kau" : f_contens } return render(request, 'Output.html', context) Output.html {% extends 'SBLReport/base.html' %} {% block body %} ** Lot Operation ** Search {% endblock %} in views file input1 and input2 was declare by me. How the variables inside views.py to receive input from the search box in template ? input1 = #userInput1 / from templates input2 = #UserInput2 / from templates For better explanation. from templates Output.html : I need user UserInput1 and UserInput2 pass to views views.py receive UserInput1 and UserInput2 and store in input1 &input2 for searching and using context to pass the output to the Output.html for display. Sorry this my first time to ask a question :D … -
File uploading from Poco client to Django server
I am trying to upload a file to django web server with the POCO::HTMLForm class. Here is my C++ code: HTTPClientSession *httpSession = new HTTPClientSession( "127.0.0.1", 8000 ); httpSession->setTimeout( Poco::Timespan( 20, 0 ) ); HTTPRequest request( HTTPRequest::HTTP_POST, "/", HTTPMessage::HTTP_1_1 ); HTMLForm form; form.setEncoding( HTMLForm::ENCODING_MULTIPART ); form.set( "mytext", "9876543210" ); form.addPart( "myfile", new FilePartSource( "d:\\test.jpg" ) ); form.prepareSubmit( request ); try { form.write( httpSession->sendRequest( request ) ); Poco::Net::HTTPResponse res; istream &is = httpSession->receiveResponse( res ); Poco::StreamCopier::copyStream( is, std::cout ); } ... and the python code: def start_pg(request): if request.method == 'POST': myform = MyTxtForm(request.POST, request.FILES) print(request.POST) print(request.FILES) if myform.is_valid(): txt_model = MyTxtModel() txt_model.mytxt = myform.cleaned_data['mytext'] txt_model.myfile = myform.cleaned_data['myfile'] txt_model.save() print('form OK!') return HttpResponse('Ok!') else: print('form is NOT valid.') return HttpResponse('Bad.') else: myform = MyTxtForm() return render(request, 'form_pg.html', {'myform': myform}) From the browser this code works very well. But the poco client sends an empty fields. print(request.POST) and print(request.FILES) gives me empty dicts: <QueryDict: {}> <MultiValueDict: {}> If I comment line form.setEncoding( HTMLForm::ENCODING_MULTIPART ); poco sends me only the <QueryDict: {'mytext': ['9876543210']}> field. Can anyone guide me on what is the issue. Thanks in advance. -
Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed. (Django 1.10.5 and OS Windows 10
Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed. (Django 1.10.5 and OS Windows 10) I'm trying to internationalize a Django app by following the wonderful Django documentation. The problem is when I try to run command to create language files: python manage.py makemessages --all It outputs an error : Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed. -
Why can't my Django connect to the Database?
My Django settings.py file contains this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'my_db', 'USER': 'my_db_user', 'PASSWORD' : 'my_password', 'PORT' : '3306', 'HOST' : 'mydbinstance.c13xxxxxxxxx.us-east-1.rds.amazonaws.com', } } My Django project has an app called myapp which contains a model called MyModel When I run python manage.py shell, I can manually connect to the database successfully with the parameters above and query that table: $ python manage.py shell >>> import MySQLdb >>> db = MySQLdb.connect(host="mydbinstance.c13xxxxxxxxx.us-east-1.rds.amazonaws.com", user="my_db_user", passwd="my_password", db="my_db") >>> cursor = db.cursor() >>> cursor.execute("select * from myapp_mymodel") 7L But from the same shell, when I try to use Django to access the same models from the same database, it fails as shown below. >>> from myapp.models import MyModel >>> MyModel.objects.all() Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 138, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 162, in __iter__ self._fetch_all() File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 965, in _fetch_all self._result_cache = list(self.iterator()) File "/srv/src/django-cache-machine/caching/base.py", line 118, in __iter__ obj = iterator.next() File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 238, in iterator results = compiler.execute_sql() File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 838, in execute_sql cursor = self.connection.cursor() File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/base.py", line 162, in cursor cursor = self.make_debug_cursor(self._cursor()) File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/base.py", line 135, in _cursor … -
build an includable template as string [django]
I want to build a list of clickable links for my nav, and because these are links to my site, I want to use the url-tag. I get a list of dictonaries which knows all names for the links and create a template string with them with this function: def get_includable_template(links): output = '<ul>' for link in links: output = output + '<li><a href="{% url' + get_as_link(link) + '%}>" + link['shown'] + '</a></li>' output = output + '</ul> links look like this: links = [ {'app': 'app1', 'view': 'index', 'shown': 'click here to move to the index'}, {'app': 'app2', 'view': 'someview', 'shown': 'Click!'} ] get_as_link(link) looks like this: def get_as_link(link): return "'" + link['app'] + ':' + link['view'] + "'" So the first method will return a template, which looks like this (but it's all in the same code line): <ul> <li><a href="{% url 'app1:index' %}">click here to move to the index</a></li>' <li><a href="{% url 'app2:someview' %}">Click!</a></li> </ul> So I want this to be interpreted as template and included to another template. But how to include this? Let's say, my other template looks like this: {% extends 'base.html' %} {% block title %}App 1 | Home{% endblock %} {% block … -
django url no reserve match
I am trying to pass two parameters through the url in django (email,name) it works fine when I am just passing the email through but when I pass the name through as well I get an error (no reserve match) url pattern `url(r'^details/(?P<email>[\w.%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4})/(?P<name>(\W+))/$', details, name="details"`), passing variable through to the url {%url 'details' email name %} -
Is there a workarround for using Wagtail Image tags in views.py
I've the following problem: In my models.py I'm using a Wagtail Image like this: class ArtWork(models.Model): image = models.ForeignKey( 'wagtailimages.Image', on_delete=models.CASCADE, related_name='+' ) ... ... ... I know i can use the Image in my templates now like this: {% image artwork.image height-100 %} But for my current project I need to use the Image tag in my views.py because I'd like to generate a Pdf with it. by simple using artwork.image just the Title of the Image returns but I'd need something like: <img alt="SomeName" src="/media/images/SomeName_155x200.max-1200x1200_22b3pND.height-100.jpg" width="77" height="100"> Also artwork.image.url gives no result. How can I use Wagtail Images outside my templates? best regards -
Django allauth error using stack exchange: Exception Value: 'items'
When I try to login using stack overflow using stackexchange, link generated {% provider_login_url "stackexchange" process="connect" %} and I've added it to INSTALLED_APPS 'allauth.socialaccount.providers.stackexchange',. When I click the link it redirects to stackexchange and I login it then redirect back to the site which brings an error Environment: Request Method: GET Request URL: http://kazichimp.com/accounts/stackexchange/login/callback/?code=CBy0SGksBsBjYZojGIsTwg))&state=jEssFyErtLnt Django Version: 1.8.7 Python Version: 2.7.12 Installed Applications: ('django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'sorl.thumbnail', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.linkedin_oauth2', 'allauth.socialaccount.providers.twitter', 'allauth.socialaccount.providers.stackexchange', 'django.contrib.admin', 'django_countries', 'accounts', 'common') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware') Traceback: File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python2.7/dist-packages/allauth/socialaccount/providers/oauth2/views.py" in view 69. return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/allauth/socialaccount/providers/oauth2/views.py" in dispatch 130. response=access_token) File "/usr/local/lib/python2.7/dist-packages/allauth/socialaccount/providers/stackexchange/views.py" in complete_login 23. extra_data = resp.json()['items'][0] Exception Type: KeyError at /accounts/stackexchange/login/callback/ Exception Value: 'items' -
compare timestamp from auto_now format of django in java
I am working on a django and java project in which I need to compare the time in django to the time in current time in java. I am storing the enbled_time in models as : enabled_time = models.DateTimeField(auto_now = True, default=timezone.now()) The time gets populated in the db in the form : 2017-02-26 14:54:02 Now in my java project a cron is running which checks whether enabled_time plus an expiry time is greater than the current time something as: Long EditedTime = db.getEnabledTime() + (expiryTime*60*1000); //expiryTime is in mins if (System.currentTimeMillis() - EditedTime > 0) { //do something } But db.getEnabledTime() gives a result '2017'. What am I doing wrong? PS: I am storing time as Long which seems unsuitable to me. Can someone suggest which datatype should I choose or does it work fine? -
django: relationship between BoundField and Form Field?
As per official documentation: BoundField: A Field plus data (source) (documentation) Form Field: Manages Form data (source) (documentation) If I look at the source code, they both seem independent classes, each inheriting from the base object. However, they both seem related in some way, it's just that I am not able to figure out how. Can you help me figure out if there is any relation between BoundField and Form Field? And in case if it is, how exactly are they different? -
Django. Several images for product
I want to add several images for my product and already have models.py: class Product(models.Model): category = models.ForeignKey(Category, related_name='products') name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True) short_description = models.CharField(max_length=200, blank=True) description = models.TextField(blank=True) product_information = models.TextField(blank=True) price = models.DecimalField(max_digits=10, decimal_places=0) stock = models.PositiveIntegerField() available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('name',) index_together = (('id', 'slug'),) def __str__(self): return self.name def get_absolute_url(self): return reverse('shop:product_detail', args=[self.category.slug, self.slug]) class Images (models.Model): product = models.ForeignKey(Product, default=None, related_name='images') image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) but I can't upload image via admin page. admin.py class ProductAdmin(admin.ModelAdmin): list_display = ['name', 'slug', 'category', 'price', 'stock', 'available', 'created', 'updated'] list_filter = ['available', 'created', 'updated', 'category'] list_editable = ['price', 'stock', 'available'] prepopulated_fields = {'slug': ('name',)} admin.site.register(Product, ProductAdmin) How should i change my code to be able add several images for my product using admin page? And how should I than call images in page code? Right now i call image using {{ product.image}} I spent already a lot of time to find answer. Please help. =) -
How to create dependent select in django?
How to create dependent select in django? Eg- selecting particular interval month/hour/minute/seconds its respective range can be updated in another select to choose from. -
Django serializing / deserializing two values to one model field
I have this code: models.py from django.contrib.gis.db import models class Driver(models.Model): location = models.PointField(null=True, blank=True) accuracy = models.DecimalField(max_digits=10, decimal_places=3) serializers.py from rest_framework import serializers from .models import Driver class DriverSerializer(serializers.ModelSerializer): class Meta: model = Driver fields = '__all__' The PointField is serialized into {"location":"SRID=4326;POINT (106.84341430665 -6.1832427978516)"} but I would like to get {"latitude": 106.84341430665, "longitude": -6.1832427978516} when serializing and also use this format for deserializing. Is it possible to do this inside the serializer? -
Use inlineformset in createform
I am writing the view for following forms: class QuestionForm(forms.ModelForm): class Meta: model = Question fields = ('question_text',) def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.fields['question_text'].label = 'Question' class ChoiceForm(forms.ModelForm): class Meta: model = Choice fields = ('choice_text',) def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.fields['choice_text'].label = 'Choice' ChoicesFormset = inlineformset_factory(Question, Choice, form=ChoiceForm, extra=6, validate_min=1, can_delete=False) class CreateQuestionView(generic.CreateView): template_name = 'polls/create.html' model = Question form_class = QuestionForm def get_success_url(self): return reverse('polls:vote', args=(self.object.id,)) def get_form(self, form_class=None): form = super().get_form(form_class) form.auto_id = False form.use_required_attribute = False return form def get(self, request, *args, **kwargs): self.object = None form = self.get_form() choices_form = ChoicesFormset() return self.render_to_response( self.get_context_data(form=form, choices_form=choices_form)) def post(self, request, *args, **kwargs): self.object = None form = self.get_form() choices_form = ChoicesFormset(request.POST) if form.is_valid() and choices_form.is_valid(): return self.form_valid(form, choices_form) else: return self.form_invalid(form, choices_form) def form_valid(self, form, choices_form): redirect = super().form_valid(form) choices_form.instance = self.object choices_form.save() return redirect def form_invalid(self, form, choices_form): return self.render_to_response( self.get_context_data(form=form, choices_form=choices_form)) The field required error message is also shown the first time the view is displayed The form requires the fill out all choices but it should only be one: validate_min=1 auto_id and the 'use_required_attribute' should also be disabled for the formset like in get_form -
Django server details
I have been working with django since 2 years, still confuse with some of the server related concepts of django as follows:- What web server does django use when I run python manage.py runserver? What is wsgi(I know it is web server gateway interface(sets of rules can say protocols) act as an middle-ware for the communication of web server and web application) then wsgi is the server django runs on? -
Jquery :not selector doesn't work with style on class
I am trying to make product pages for my website, unfortunately i am failing in Javascript to hide any other displays except specific page. First of all, i wrapped up every 24 div's in single div: var lis = $(".products li"); for(var i = 0; i < lis.length; i+=24) { lis.slice(i, i+24) .wrapAll("<div class='products'></div>"); } Then i gave each object of class, it's id: $('.products').each(function(i, obj) { if (i > 0) { obj.id = "p" + i } }); I have tested if it could work, and it did. After that, i made GET request so user would choose the page. {{ currentpagen }} was the value of GET request, for example, in this case, 1. Then i have added the code, so all other divs would be hidden, except current page one: $(".products:not(#p + {{ currentpagen }})").css("display", "none"); $('#p' + {{ currentpagen }}).css("display", "flex"); and it would not work, All elements would be hidden, including one's that shouldn't be hidden by idea, for example, all element's should've been hidden in this case, except #p1. So what could the problem be? Is there any better way to do this? Id's obviously work since i have tried changing their style, but … -
ODjango - Given the display of a model choice, how to retrieve the value?
If I have the model field with the following choice set: TYPES = ( ('1', 'Option1'), ('2', 'Option2'), ('3', 'Option3'), and I have the string 'Option3', how can I obtain the value 3? -
Privileges to database tables created by Django
I am creating a web application using python-Django and mysql. While migrating database framework created following 10 tables.so, is there need to give privileges to those tables? if yes, which are those ? auth_group auth_group_permissions auth_permission auth_user auth_user_groups auth_user_user_permissions django_admin_log django_content_type django_migrations django_session -
Assigning a field to a model only when it is part of another model
I am learning Django, and I've found myself in the following scenario: I have a project model with various fields. One of which is key_personnel. The other is key_person_roles, which defines the roles played by each key personnel on the project. A project can have various key personnel, and each key personnel can have various roles. Key personnel do not have default roles, they can play any roles on different projects. How can I best model this scenario in Django? I can't seem to find examples on how to model such a scenario. Here's my models.py: from django.db import models from phonenumber_field.modelfield import PhoneNumberField class Key_Person(models.Model): name = models.CharField(max_length=200) designation = models.CharField(max_length=100) email = models.EmailField() contact = PhoneNumberField() class Meta: ordering = ['name'] verbose_name_plural = "Key Persons" def __unicode__(self): return self.name class Key_Person_Role(models.Model): role = models.CharField(max_length=100) class Meta: verbose_name_plural = 'Key Person Roles' def __unicode__(self): return self.role class Project(models.Model): title = models.CharField(max=150) description = models.TextField() # more fields here ... key_persons = models.ManyToManyField(Key_Person) # What I want is to assign a role to each key person above. key_person_roles = models.ManyToManyField(Key_Person_Role) def __unicode__(self): return self.title I appreciate your help.