Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django: raw_id_field in a custom view
I have a model I'll call Item and a form I'll call ItemAdminForm I have in my model a field name 'city' that is a ForeignKey. I need to show this as a raw_id_field in my custom view/template: [views.py content] def item_add(request): #raw_id_fields = ('city',) form = ItemFormAdmin(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.save() return HttpResponseRedirect(instance.get_absolute_url()) context = { "form": form, } return render(request, 'item_add.html', context) What is the correct way to do that? -
Django get the max PK
I am trying to recieve the max PK using django ORM. By max I mean I want to do this query: SELECT MAX(pk_column) FROM some_table; the thing is that I want something like some_table_model.max(pk) , it is important for me that the Django will translate it to the query above so it will use indexs. So: Is there something like that build in? Is there a way to write a generic function without doing it for a specific model? Thank you in advance. -
How to retrieve photos from requested album in django?
class Album(models.Model): title = models.CharField(max_length=250) date = models.DateTimeField(default=datetime.now) image = models.ImageField(upload_to='photos') class Photo(models.Model): title = models.CharField(max_length=250, help_text='Maximum 250 characters.', blank=True) slug = models.SlugField(unique = True, help_text='Suggested value automatically generated from title. Must be unique.', null=True) caption = models.TextField(blank=True, max_length=250, help_text='An optional summary.') date = models.DateTimeField(default=datetime.now) image = models.ImageField(upload_to='photos', help_text='Maximum resolution 800x600. Larger images will be resized.') album = models.ForeignKey(Album) class Meta: ordering = ['-date'] def __unicode__(self): return self.title I have something like this in models.py and i want to write a function in views which select all the photos related to the requested album and return it in the corresponding html page def album_list(request): album_choice = Album.objects.all() return render(request, "talks/gallery.html", {'album_choice':album_choice}) def photo_list(request): queryset = Photo.objects.filter context = { "photos" : queryset, } return render(request, "talks/", context) Also I have just this in views.py so suppose a user clicks on particular category and then it opens up to show the images related to it. how do I retrieve this information ? -
Django specific permissions for users
for example i have a model with booleanfield class Item(BaseModel): name = models.CharField(max_length=255) pending = models.BooleanField(default=False) if user creates new item from admin panel pending field is false and this item won't display on website until other user set this field into True, but this user mustn't be allowed to make change on pending field on his items but he can do this activity on other users items. any solutions? -
Cannot make my Django project use Django-cities "unexpected metadata layout"
I want my project to serve all world cities by using Django-cities. First and after facing many problems, I made my SQLite accept spacial queries by using advice in this tutorial and this question. So far I can run "makemigrations" but when I run "migrate" I receive: unexpected metadata layout. I think the answer to my problem is included in this question but I'm not sure how to apply it in a Django project. This is full text of the error when I run "migrate": Applying cities.0001_initial...AddGeometryColumn() error: unexpected metadata layout CreateSpatialIndex() error: "no such table: geometry_columns" AddGeometryColumn() error: unexpected metadata layout CreateSpatialIndex() error: "no such table: geometry_columns" AddGeometryColumn() error: unexpected metadata layout CreateSpatialIndex() error: "no such table: geometry_columns" AddGeometryColumn() error: unexpected metadata layout CreateSpatialIndex() error: "no such table: geometry_columns" Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Python27\Lib\site-packages\django\core\management\__init__.py", line 385, in execute_from_command_line utility.execute() File "C:\Python27\Lib\site-packages\django\core\management\__init__.py", line 377, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python27\Lib\site-packages\django\core\management\base.py", line 288, in run_from_argv self.execute(*args, **options.__dict__) File "C:\Python27\Lib\site-packages\django\core\management\base.py", line 338, in execute output = self.handle(*args, **options) File "C:\Python27\Lib\site-packages\django\core\management\commands\migrate.py", line 160, in handle executor.migrate(targets, plan, fake=options.get("fake", False)) File "C:\Python27\Lib\site-packages\django\db\migrations\executor.py", line 63, in migrate self.apply_migration(migration, fake=fake) File "C:\Python27\Lib\site-packages\django\db\migrations\executor.py", line 97, in apply_migration migration.apply(project_state, schema_editor) … -
Deploying Django project on Linux
Comming from PHP(without frameworks), I don't quite understand how deploying works in Python. I have completed my simple Django version: (1, 10, 1, 'final', 1) blog project and all I have to do is put it online. I am using linux openSUSE distro and virtualenv I have access to a mysql database with phpmyadmin and I have some space, accessed with filezilla. hosting site: https://host.bg/ But then I started researching of how to deploy my project and I stumbled upon stuf like apache, Nginx, wsgi and other stuff I haven't used in the project and not quite familiar how they work. So my question is: Can I make my project into a folder with some files in it, copy->paste them in filezilla and have a working site and if not, how does django deployment really work and what should I do from here ?! -
How to remove the 'row' css class of bootstrap4 form-group in djang-crispy-forms?
I have a model form: ``` class PostCreationForm(UserKwargModelFormMixin, forms.ModelForm): class Meta: model = Post fields = ['title', 'body', 'category', 'tags'] def __init__(self, *args, **kwargs): super(PostCreationForm, self).__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_method = 'post' self.helper.form_action = 'forum:create_post' self.helper.layout.append( StrictButton(_('Post post'), css_class='btn-outline-info pull-xs-right', type='submit') ) def save(self, commit=True): self.instance.author = self.user return super(PostCreationForm, self).save(commit) ``` Crispy form create a Div wrapper each field with css class class='from-group row' (bootstrap4) but I want to romove the row class name, only let from-group remained. How to modify it? By the way, how to get a certain field via 'self.help'. In a normal form, I user it like a dict such as self.help['body'], but in model form I can't access it method. If I do so, I will get an error: 'LayoutSlice' object has no attribute 'update_attributs'. And, how to change the hepl_text wrapped tag? The default tag is . I want to wrap the help_text with -
Django JOIN table
I have the next query in Postgres: SELECT a.key, a.name, a.code, (SELECT coalesce((SELECT MAX(value) FROM financials WHERE client_key=a.key AND year=2016), 0) AS ca_vlr_n) FROM clients a I want to translate it into Django, but I do not know how to deal with that Coalesce. I done this: queryset = Client.objects.values('name', 'code').annotate(ca_vlr_n=Coalesce(Max('financial__value'), V(0))) but I do not know how to put the condition for year. Thank you! -
Django internal server error on change of one line
I'm trying to set up a Django server on my Rpi, and got to the point where I could get to the admin page through nginx, based on these two tutorials; https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 and https://docs.djangoproject.com/en/1.10/intro/tutorial01/ My directory structure looks like this; pi@raspberrypi:~/myproject $ ls manage.py myproject myprojectenv myproject.sock polls static pi@raspberrypi:~/myproject $ ls polls admin.py apps.py __init__.py migrations models.py tests.py urls.py views.py views.py.save pi@raspberrypi:~/myproject $ ls myproject __init__.py __pycache__ settings.py urls.py wsgi.py Created an app called Polls from within the above directory. ./manage.py startapp polls I've set the following in ~/myproject/myproject/settings.py # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['localhost','127.0.0.1','192.168.1.213','*'] I've restarted nginx and gunicorn after each change. I've tried moving ~/myproject/polls to ~/myproject/myproject/polls The line that causes the internal server error is this in ~/myproject/myproject/urls.py; from django.conf.urls import url from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls')),#This one causes the internal server error. url(r'^admin/', admin.site.urls), ] I'm not really sure where to go from here, but suspect I'm close, any advice, suggestions or things I should be reading appreciated. -
Django Spirit 1.9
Is there any way I can install a package(Spirit) that isn't compatible with 1.9 on Django 1.9? It is only compatible with 1.8 LTS. Also, if that is not possible, am I able to make a separate project and connect the two to the same database? -
How to customize the payload section of the JWT response
What do I need to do to customize the url(r'^auth/login/', obtain_jwt_token) view to allow me to add data to the JWT token I have a django-rest-framework API that is used by independent web applications. What I want is to return to the web app the logged in user's role and permissions together with what djangorestframework-jwt already returns. I already have the roles in a python dictionary but I can't figure out what is required to override the default payload. user_payload = {'user': user, 'roles': roles} I thought it was as simple as replacing the 'user' in payload = jwt_payload_handler(user) with my user_payload but then am getting serializer errors. Is there a cleaner/easier way to do it? djangorestframework==3.4.7, djangorestframework-jwt==1.8.0 -
Django Spirit integrate with existing project
So I am kind of a newbie in Django and I am trying to setup a forum on my website. I managed to setup the example project correctly, and it works but I can't seem to find anything on how to integrate Spirit with an existing project which uses Userena for authentication. -
How to save Foreign Key text input in Django model form
My view passes an id to my form. This id is a foreign key from another table. I am not able to save the id in the database table. (id : voucher_id, table in which i am saving the form : TmpPlInvoicedet) What i want to do Send voucher_id from (View) to ---> TmpFormDetForm (Form) ---> TmpPlInvoicedet (DB) Trying to get instance from the table 'TmpPlInvoice' (which has voucher_id as PK) and save it in the form gives me DoesNotExist at /new/ TmpPlInvoice matching query does not exist What am i doing wrong? Views.py def new_invoic(request): # Create a voucher id according to my criteria temp_vid = TmpPlInvoice.objects.order_by().values_list("voucher_id", flat=True).distinct() if not temp_vid: voucher_id = str(1).zfill(4) else: voucher_id = str(int(max(temp_vid)) + 1).zfill(4) # POST METHOD TRying to show the voucher_id in the form in readonly format if request.method == 'POST': form = TmpFormDetForm(request.POST or None, voucher=voucher_id, initial={'voucher': voucher_id}) if form.is_valid(): form.save() return HttpResponseRedirect('/new/') else: return render_to_response('test.html',{'form': form},context_instance=RequestContext(request)) else: form = TmpFormDetForm(voucher=voucher_id, initial={'voucher': voucher_id}) return render_to_response('test.html',{'form': form},context_instance=RequestContext(request)) Forms.py class TmpFormDetForm(forms.ModelForm): def __init__(self, *args, **kwargs): voucher = kwargs.pop('voucher', None) super(TmpFormDetForm, self).__init__(*args, **kwargs) self.fields['voucher'].initial = TmpPlInvoice.objects.get(voucher_id=voucher) voucher = forms.CharField(widget=forms.TextInput(attrs={'size':'40'})) class Meta: model = TmpPlInvoicedet exclude = ['emp_id','particulars','qty', 'rate' , 'itemtot', 'stock_code' ] widgets = … -
Generate PDF with WeasyPrint having common header/footer and pagination
I am using WeasyPrint to generate PDF in Django. I can generate pdf from a static html file like below - from django.template import Context, Template import weasyprint with open('static_file.html', 'r') as myfile: html_str = myfile.read() template = Template(html_message) context = Context({'some_key': 'some_value'}) rendered_str = template.render(context) weasyprint.HTML(string=rendered_str).write_pdf('generated.pdf') But I want to generate a PDF in which, I can include a common header/footer in each page and add pagination. Also it will be very helpful if anyone can tell how to include a custom font to generate the PDF. I have installed the font in the OS (Ubuntu 14.04) but it is not working. I have searched a lot on the web about these. But could not find a proper solution. -
Django + ReactJS and 3rd party app frontend
So far I have read some documentation on ReactJS and how to integrate with Django. It's a lot of work to do, there is no easy way to just try it out. I have a django app that works with django-templates as frontend and I am trying to get a picture of the work need for a transition to reactJS frontend. I understand that all my frontend logic needs to be redone. Maybe a stupid question but does that include all of the django 3rd party apps as well? For example allauth that I use for authentification. Do I need to customize all of the allauth views to become an API for react? Allauth is huge and I am using a lot more 3rd party apps from django. Would I need to customize views in each of them to work with react and also all the frontend they have prebuild? Or am I missing something? Any django-react developers around: how are you coping with the fact that most django 3rd party apps return template responses? -
Django - Geographical hit counter
Currently I serve out videos and keep a table in the database as class Statistic(models.Model): views = ... unique_views = ... clicks = ... unique_clicks = ... However I want to add functionality to be able to see geographical location also. Is there an "industry standard" way to record some aspect of geographical location also? # What I have so far class GeographicStat(models.Model): clicks_from_us = ... unique_clicks_from_us = ... clicks_from_cad = ... unique_clicks_from_cad = ... ... # but this doesnt seem exactly "efficient" or a correct way to implement this # obviously I could make the fields bigger (e.g. clicks_from_north_america) but I was # wondering if it is possible to get more fine grained information I want to be display something akin to the following to my users Any opinion/suggestions are highly appreciated! -
Django and requirements
Im a bit stuck. I can't get this configuration to work and I don't know why. The code I site below is from https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-14-04. The reason I get stuck on it is because he named his project directory and his project the same thing. If I am right, then where he is locating files like the settings.py and wsgi.py should be /home/user/myproject/myproject/myproject but I'm not sure anymore because I can't even get it right myself. Earlier in the document he cd's into the directory he created, which would put him in /home/user/myproject. He then proceeds to create a virtual environment, enter it, and run django-admin startproject myproject. So, if all this holds true, at least what I see on my own server tells me that when you start a django project it actually creates two folders with the same name, nested. Am I wrong? Can someone help me straighten the below code out to make more sense? . . . Alias /static /home/user/myproject/static <Directory /home/user/myproject/static> Require all granted </Directory> <Directory /home/user/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/home/user/myproject:/home/user/myproject/myprojectenv/lib/python2.7/site-packages WSGIProcessGroup myproject WSGIScriptAlias / /home/user/myproject/myproject/wsgi.py </VirtualHost> -
Deploying django and django cms under one domain?
I am a beginner i need to host multiple Django and django cms under one domain i am using mod_wsgi handler for hosting. I used to follow the following configuration. ServerName example.tk WSGIDaemonProcess blog python-home=/home/nidhinjames/djangosite/virtualenv3.5 python-path=/home/nidhinjames/djangosite/mysite WSGIScriptAlias /djangosite /home/nidhinjames/djangosite/mysite/mysite/wsgi.py process-group=blog application-group=%{GLOBAL} WSGIDaemonProcess rnd python-home=/home/nidhinjames/djangocms/virtualenv3.5 python-path=/home/nidhinjames/djangocms/september WSGIScriptAlias / /home/nidhinjames/djangocms/september/september/wsgi.py process-group=rnd application-group=%{GLOBAL} when i calling example.tk it will render my djangocms site properly but example.tk/djanosite showing 404 not found. Any solutions can be appreciated. -
Passing a string with html over via http get as parameter only shows part of string
I am attempting to pass a html content string through http. The string looks like this std::string mystring = <p style="-qt-block-indent: 0; text-indent: 0px; margin: 18px 0px 12px 0px;"><span style="font-siz"... .... http://127.0.0.1:8000/someUrl?someString=mystring However it seems like only the following part of the string appears <p style="-qt-block-indent: I believe the string is being cut of by other characters in the string when it is retrieved. My question is if there is a way for me to resolve this issue ? Is it possible to send html via GET as parameters ? -
How to load django query faster?
I have a database with around 7000 entries. When I load the page displaying all 7000 entries, the template takes around 7 seconds to load. How can I lower the load time? What are my options? other than caching? See below the screenshot from network tab in Google Chrome. -
stuck in implementing search in django
I want to implement search in django .I dont use any search technique like solar etc. i am using simple filter query of django. Now the problem is this i have a model Product with five field name,cost,brand,expiry_date,weight I want to implement a advanced search feature with all fields. by name = request.GET.get('name') i get a value on which basis i search all product. I want is name = None. it search for all names. so problem is this if values is not coming by user side how can i search for all names -
csrf token missing or incorrect though token is passed
I have passed csrf token to reactjs app and i can see the token is passed but still shows an error of missing or incorrect while posting to an api. CSRF token is passed using window.CSRF_TOKEN = "{{ csrf_token }}". Am i missing something or i have done it in incorrect way? Here is my code actions let nextTab = 1; export function addTab(name, icon) { console.log('name', name); console.log('icon', icon); // console.log('token is', CSRF_TOKEN); return (dispatch) => { dispatch({ type: 'POST_TAB_START' }); axios.post('http://192.168.1.103:8000/rest-api/ui/tabs/', { header: { 'X-CSRFToken': CSRF_TOKEN, 'Access-Control-Allow-Origin': '*', } }) .then((response) => { console.log('response', response); dispatch({ type: 'POST_TAB', payload: { id: nextTab++, name, icon } }); }) .catch((err) => { dispatch({ type: 'POST_TAB_FAILURE', payload: err }); }); }; } tab-dialog.js onSubmit = (e) => { e.preventDefault(); console.log(e.target.value); console.log(e.text); this.props.addTab(this.state.name, this.state.icon); // addTab is an action creator which returns action } renderAddTab() { console.log('this.props.fetchIcon', this.props.fetchIcon.icons); const listOfIcon = _.map(this.props.fetchIcon.icons, (icon) => { return { text: icon.name, value: <MenuItem primaryText={icon.name} /> }; }); console.log('listOfIcon', listOfIcon); return ( <div className="device-action"> <Dialog title="Add a Tab" modal={false} bodyStyle={{ background: '#fff' }} contentStyle={customContentStyle} actionsContainerStyle={{ background: '#fff' }} titleStyle={{ background: '#fff', color: '#1ab394' }} open={this.props.createTab.open} onRequestClose={this.props.closeTabIcon} > <form onSubmit={this.onSubmit}> <div className="tab-name"> <TextField floatingLabelText="Name" ref="name" floatingLabelStyle={{ … -
Django Form request.POST.get() always returns empty
Sorry if this is a noob question. I'm creating a login form for a Django app, but I'm having trouble getting it to work. request.POST.get() doesn't return anything, so the authentication always fails. Am I missing something obvious? login.html: {% extends "base.html" %} {% block content%} <h2>Welcome! Please login to continue.</h2> <br> <form action="{% url 'account:authenticate' %}" method="post"> {% csrf_token %} <div > <label for='username'> Username: </label> <input type='text' name='Username' id='username'> <br><br> <label for='password'>Password: </label> <input type='password' name='Password' id='password'><br><br> <input type='submit' value='Login'> </div> </form> relevant part of views.py: from django.shortcuts import render, get_object_or_404 from datetime import datetime from django.http import HttpResponse, Http404, HttpResponseRedirect from django.template import loader from random import randrange from django.contrib.auth import authenticate def login(request): return render (request, 'login.html') def authenticate(request): usern = request.POST.get('username', '') passw = request.POST.get('password', '') user = authenticate(username = usern, password = passw) if user is not None: authenticate.login(request, user) return HttpResponseRedirect('/voters/instructions') else: return HttpResponseRedirect('/account/loginfail') def loginfail(request): return render (request, 'loginfail.html') I'm using Django 1.10. Thanks! -
haystack-int() argument must be a string or a number, not 'list'
I am using django-haystack to do search with Apache Solr. But i meet a problem when doing the demo project. The error information is:int() argument must be a string or a number, not 'list'. More error (in line 985) information is below: 981. def get_prep_value(self, value): 982. value = super(AutoField, self).get_prep_value(value) 983. if value is None: 984. return None 985. return int(value) and the var "value" is: self <django.db.models.fields.AutoField: id> value [1] I suspect that it is because of the version of django. The version of django and haystack is 1.8.15 and 2.5, python is 2.7. If you have successfully implemented haystack, could you please tell me what is your version? Thanks. -
Extending django User django-rest_framework gives me KeyError
I'm new to django rest_framework and have and issue, i've extended the auth_user as per the django docs, but is giving me a hard time... models.py class UserProfile(models.Model): user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) national_id = models.CharField(max_length=10, blank=True, null=True) mobile = models.CharField(max_length=10) pin = models.IntegerField() pattern = models.IntegerField(blank=True, null=True) fingerprint = models.CharField(max_length=45, blank=True, null=True) class Meta: managed = False db_table = 'user_profile' serializers.py class UserSerializer(serializers.ModelSerializer): national_id = serializers.CharField(source='userprofile.national_id', allow_null=True, required=False) mobile = serializers.CharField(source='userprofile.mobile') pin = serializers.IntegerField(source='userprofile.pin', write_only=True) pattern = serializers.IntegerField(source='userprofile.pattern', write_only=True) fingerprint = serializers.CharField(source='userprofile.fingerprint', write_only=True, allow_null=True, required=False) class Meta: model = User fields = ('id', 'username', 'password', 'first_name', 'last_name', 'email', 'national_id', 'mobile', 'pin', 'pattern', 'fingerprint') write_only_fields = ('password',) read_only_fields = ('last_login', 'is_superuser', 'is_staff', 'is_active', 'date_joined') def create(self, validated_data): user = User( username=validated_data['username'], first_name=validated_data['first_name'], last_name=validated_data['last_name'], email=validated_data['email'], ) user.set_password(validated_data['password']) user.save() userprofile = UserProfile( user=user, national_id=validated_data['national_id'], mobile=validated_data['mobile'], pin=validated_data['pin'], pattern=validated_data['pattern'], fingerprint=validated_data['fingerprint'], ) userprofile.save() return user views.py class UserView(viewsets.ModelViewSet): serializer_class = UserSerializer queryset = get_user_model().objects urls.py from django.conf.urls import include, url from django.contrib import admin from rest_framework.routers import DefaultRouter from restful.views import * router = DefaultRouter() router.register(r'availability-notification', AvailabiltyNotificationView) router.register(r'bank', BankView) router.register(r'recipient', RecipientView) router.register(r'user', UserView) urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^admin/', admin.site.urls), but keeps giving me: Environment: Request Method: POST Request URL: http://localhost:8000/user/ Django …