Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Save and add another behaviour modification
In my django admin console i would that after user press "Save and add another" button the fields value of the form remain populate with last values inserted but i don't know if and how this could be possible. Someone could help me? Thanks in advance -
Django - Meta.base_manager_name - make related argument in the custom queryset and manager
I have a custom model manager and a custom queryset defined specifically for related obj which means I have defined Meta.base_manager_name in the model. I would like to use a all() manager method which fetches related obj on a OneToOneFeild. Now I know this does not make sense since OneToOneFeild will always return one obj there is no need for a all() method. I am working on django-oscar project and am extending its "Partner" model. It originally has a field "users" with ManyToManyField and now changed to a OneToOneFeild. The users field is called in code several times using relation user.partners.all(). I don't want to extend/modify all these places (am I being lazy here?) since I want to keep the code as upgrade friendly as possible and so instead I wanted to have all() model manager defined which will work. Not sure if it is a good idea? the all() method takes user arg to return queryset of the user instance class PartnerQuerySet(models.QuerySet): def all(self, user): return self.filter(user=user) class PartnerManager(models.Manager): def get_queryset(self): return PartnerQuerySet(self.model, using=self._db) def all(self, user): return self.get_queryset().all(users) class Partner(models.Model): objects = PartnerManager() class Meta: base_manager_name = 'objects' The problem is when it is used with related obj … -
Django Error: HttpResponse Invalid Syntax
This is my views.py from django.shortcuts import render from django.http import HttpResponse def index(request): reutrn HttpResponse("<h1>This is a test</h1>") No matter what I do this syntax error always shows up! File "C:\Users\#24\Python Projects\Test\Packages\views.py", line 6 reutrn HttpResponse("<h1>This is a test</h1>") ^ SyntaxError: invalid syntax I've looked pretty hard to see if anyone else has had this problem but no dice. This is my first time trying out django -
Bokeh Dynamic Axis Scaling
My question is similar to this question but I have code examples. I have created a bokeh chart in a Django app that plots times swam in competitive swimming events over time, and uses one plot plot = figure( title='Event Progress', x_axis_label='Date', y_axis_label='Time', x_axis_type='datetime', plot_width=400, plot_height=200, tools=tools, responsive=True, ) the Select widget, and a CustomJS function to only display one line at a time. The problem is, if one event has a time of 10 minutes and another has a time of 25 seconds, the y-axis (time) scales so that both will be seen when they are made visible. I declare each line like plot_lines[event] = plot.line('x_'+event, 'y_'+event, line_width=4, source=source) and the Select widget like multi_select = Select(title="Select Event:", value=events[0], options=events, callback=callback) if that's helpful. I'm also custom formatting the y-axis as plot.yaxis.formatter = FuncTickFormatter(code= """ return Math.floor(tick/60) + ":" + tick.toFixed(2) """ ) so that it displays the time correctly. Everything else is just formatting the data, setting the lines to visible or not and the callback function. Is there a way to dynamically scale a single axis for each line? I suppose ideally I could set the y-max and y-min for each line to keep it within the … -
Using Django forms with arbitrary elements based on user input
I'm working on a Django (1.11.1) app which allows users to request reimbursement for certain purchases. Part of the request form (using django.forms) is an itemized list of purchases. I could, of course, hard code some number of rows into the form and make users submit a separate form if they need more rows. But that seems rather inelegant. My preferred solution would be to allow users to add rows as necessary via JavaScript, then handle that dynamically in forms. However, everything I've found on the subject relates to situations where the number of elements required can be determined at the time the form is rendered to HTML. It isn't clear to me how to apply such an approach to my situation. As dynamically adding form elements is extremely common, I'm a bit surprised that such functionality isn't baked into Django already. By the way, as this is intended to be an incredibly simple app, I don't want a solution that will require a lot of work. If there's no easy solution, it'd be better to just hard-code the form HTML directly into the template. -
How to give permission as per table value using Django and Python
I need some help. I need to give the permission as per the table value to some functions. I am explaining my model below first. class Permission(models.Model): """docstring for Permission""" user = models.ForeignKey(User) control_reactor = models.IntegerField(default=0) find_reactor = models.IntegerField(default=0) view_reactor = models.IntegerField(default=0) I am expected table is given below. id control_reactor view_reactor find_reactor user_id 1 1 1 1 2 2 0 1 0 1 Here suppose whose user_id = 2 has logged in the site. and need to set the permission for the below views.py functions. views.py: def home(request): """ This function for home screen . """ return render(request, 'plant/home.html', {'count': 1}) def view_reactor(request): """ This function for to get serch screen. """ return render(request, 'plant/view_reactor.html', {'count': 1}) Here I need to use like decorator function i.e-@permission_required and @login_required. Suppose user_id=2 has logged in then then it will check the all permission in DB like control_reactor=1,view_reactor=1,find_reactor=1 and all will check for home function and for view_reactor function it will check view_reactor=1 or not . and same process for user_id=1 also. Please help me. -
Internal Server Error when using django.contrib.gis.db.backends.postgis in settings.py
I always got Internal Server Error when I use postgis in settings.py: DATABASES = { 'default': { #'ENGINE': 'django.contrib.gis.db.backends.postgis', 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'geodb', 'USER': 'postgres', } } But it works if I use the sqlite3: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } I am using python3.6, django 1.11.4, postgis postgresql-9.2-postgis-2.3 on Centos 7. Spent the whole day to search for a solution but not able to find any. Appreciate it for any help. -
NoReverseMatch at /app02/user_delete-5/
In my /templates/app02/urls.py: urlpatterns = [ ... url(r'^userinfo/', views.userinfo), url(r'^user_delete-(?P<nid>\d+)/', views.user_delete), ] In the /app02/views.py: def userinfo(request): if request.method == 'GET': # QuerySet user_list = models.UserInfo.objects.all() return render(request, 'app02/userinfo.html', {'user_list':user_list}) elif request.method == 'POST': u = request.POST.get('username') p = request.POST.get('password') models.UserInfo.objects.create( username=u, password=p ) print ('before redirect') return redirect('/app02/userinfo/') def user_delete(request, nid): models.UserInfo.objects.filter(id=nid).delete() return redirect(request, '/app02/userinfo/') This is the code in the template: <ul> {% for row in user_list %} <li> <a href="/app02/user_detail-{{row.id}}/">{{ row.username }} </a> | <a href="/app02/user_delete-{{row.id}}/">delete</a> </li> {% endfor %} </ul> But after I delete the item in browser, I get the below error in browser: NoReverseMatch at /app02/user_delete-5/ Please attention the data is delete success, but the browser gets the error, but did not redirect to the /app02/userinfo/.(See my user_delete method in the /app02/views.py) And in the browser address bar url is:http://localhost:8000/app02/user_delete-4/ . -
How to map an audio file with Django?
This is my models page, Help me to add a mp3 File format in models and how can i play that mp3 on web page. class Album(models.Model): artist = models.CharField(max_length=200) album_title = models.CharField(max_length=300) genre = models.CharField(max_length=100) album_logo = models.CharField(max_length=1000) def __str__(self): return self.album_title + '-' + self.artist class Song(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) file_type = models.CharField(max_length=10) song_title = models.CharField(max_length=250) is_favorite = models.BooleanField(default=False) def __str__(self): return self.song_title -
How create slider by model in django?
In my Django project I have Slider model. Can someone help me to create slider by this model. I am little bit comfused and need some ideas. I would be grateful for any help. models.py: class Slider(models.Model): head = models.CharField( max_length=250, help_text='Header', blank=False ) body = models.TextField( help_text='Description', blank=False ) idx = models.IntegerField( help_text='Field to sort', default=0, blank=True ) class Meta: ordering = ['idx', 'pk'] -
Django: Wildcards in a concat() function when filtering
I have searched whether this is possible, and it appears it may not be, but I will ask in any case. I have built a queryset which gives my users all manner of search flexibility. One of the __icontains references a concatenated field (lastname, firstname). However the (migrated) data contains some last names that include suffexes (e.g. JR., III., etc.). When searching on the concatenated column, it of course filters literally. Thus if I want to search for everyone named John Smith, I would type in 'Smith, John'. But John Smith Jr. would not be returned. I have also set up lastname with an __icontains which will return all the Smiths, but there are a lot of them. Is there a way I can do a wildcard search with the concatenated field or something that would behave the same way? The view code is below. Thanks in advance. def CmsDecedents_list(request): decedent_list = CmsDecedents.objects.annotate(LastFirst=Concat('declastname', Value(', '),'decfirstname')) query = request.GET.get("q") if query: decedent_list = decedent_list.filter( Q(permitnum__icontains=query)| Q(declastname__icontains=query)| Q(servicedate__icontains=query) | Q(LastFirst__icontains=query) | Q(declastname__icontains=query) ).distinct() page = request.GET.get('page', 1) paginator = Paginator(decedent_list, 250) try: decedents = paginator.page(page) except PageNotAnInteger: decedents = paginator.page(1) except EmptyPage: decedents = paginator.page(paginator.num_pages) return render(request, 'templates/decedent_list.html', {'decedents': decedents}) -
Are there any Django packages to create signed urls for Google Cloud Storage resources?
I'm writing a fairly simply photo app using django-rest-framework for the API and django-storages for the storage engine. The front end is being written in Vue.js. I have the uploading part working, and now I'm trying to serve up the photos. As now seems obvious when the browser tries to load the images from GCS, I just get a bunch of 403 Forbidden errors. I did some reading up on this and it seems that the best practice in my case would be to generate signed urls that expire in some amount of time. I haven't been able to find a package for this, which is what I was hoping for. Short of that, it's not clear to me precisely how to do this in Django. -
The a tag href is not my expectant url
I have a project(pyProject), and in it have a APP(app02). And in the pyProject/urls.py, I routed the app02: from app02 import views as app02_v urlpatterns = [ url(r'^admin/', admin.site.urls), ... url(r'^app02/', include("app02.urls")), ] In the app02/urls.py: import views urlpatterns = [ url(r'^index/$', views.Index.as_view()), ... url(r'^userinfo/', views.userinfo), ] the app02/views.py: def userinfo(request): # QuerySet user_list = models.UserInfo.objects.all() print (user_list.query) return render(request, 'app02/userinfo.html', {'user_list':user_list}) And in the templates: templates/index.html: <div style="position:absolute; top:48px; bottom:0; left:0; width:200px;background-color:#333"> <a class="menu" href="app02/userinfo/">用户管理</a> <a class="menu" href="app02/ugroup/">用户组管理</a> </div> But when I click the <a class="menu" href="app02/userinfo/">用户管理</a> tag, print the error: Not Found: /index/app02/userinfo/ Why it is not the /app02/userinfo/? why there is /index more ? My expert is request the /app02/userinfo/. -
Using django channels allowed_hosts_only with class based consumers
From the docs, allowed_hosts_only is a decorator to make sure the connection origin is in settings.ALLOWED_HOSTS. However I'm having difficulty applying it to a class based consumer. The applying decorators sections explains how to add decorators to the class: from channels.generic.websockets import JsonWebsocketConsumer from channels.security.websockets import allowed_hosts_only class MyConsumer(JsonWebsocketConsumer): ... def get_handler(self, *args, **kwargs): handler = super(MyConsumer, self).get_handler(*args, **kwargs) return allowed_hosts_only(handler) # just 'return handler' works This is the error I get: [2017/08/14 02:32:05] WebSocket HANDSHAKING / [123.123.123.123:12345] [2017/08/14 02:32:05] WebSocket DISCONNECT / [123.123.123.123:12345] Exception in thread Thread-4: Traceback (most recent call last): File "/usr/lib64/python2.7/threading.py", line 804, in __bootstrap_inner self.run() File "/home/user/env/lib/python2.7/site-packages/channels/management/commands/runserver.py", line 175, in run worker.run() File "/home/user/env/lib/python2.7/site-packages/channels/worker.py", line 123, in run raise ValueError("You cannot DenyConnection from a non-websocket.connect handler.") ValueError: You cannot DenyConnection from a non-websocket.connect handler. How should I be validating the connection origin with a class based consumer? I thought AllowedHostsOnlyOriginValidator might be a mixin, but the source simply has allowed_hosts_only = AllowedHostsOnlyOriginValidator. -
Deny access to unauthenticated users with django channels
I'm basically after a login_required/LoginRequiredMixin equivalent for django channels. The docs have an authentication section, which describes how to get a user, but it seems to miss the bit where you actually deny access to users who are not authenticated. from channels.generic.websockets import JsonWebsocketConsumer class MyConsumer(JsonWebsocketConsumer): channel_session_user = True def connection_groups(self, **kwargs): return ["test"] def connect(self, message, **kwargs): print message.user # AnonymousUser self.send({"accept": True}) # False here still accepts and sends a message How should I be denying/dropping the connection if message.user.is_anonymous is true? -
Django - How to handle a normal form to filter and create formsets
I'm new in Django and I'm facing a situation that I cannot solve. Probably it is some easy, but I'm failing in my approaches. Basically, I need to have 3 (modelchoices) from which I will list a table of objects to be filled by the user. The are chained, each values are filtered depending on the value selected on previous . Each value selected, I submit the form to filter the values of the next . When the last one is selected, I need to render another form, like a detail table form in which each row correspond to an object. So, they are Areas, which have Praticas, which have Projetos which have some Indicadors associated. For each Indicador I want to user inform Notas. I'm using one view and one template. I tried these approaches: 1) Normal form for selecting, then, another form with dynamic fields; but could not deal with the request.POST coming with to form 2) Normal form for selecting, then, formset; but I stuck in the same situation 1) 3) Inlineforms,based on models, but tried to make the base form have the selects, but I couldn't. I'm stuck and my code is a mess right now, … -
Set database engine to sqlcipher.backend in Django
I am trying to use sqlcipher with my Django application. My current database is sqlite. I am following this official github instruction to integrate sqlcipher successfully : https://github.com/codasus/django-sqlcipher In, settings.py I have already added sqlcipher in INSTALLED_APPS . I am having problem to set database engine to sqlcipher.backend . Previously it was, 'ENGINE': 'django.db.backends.sqlite3', I changed it to, 'ENGINE': 'sqlcipher.backend' Error is showing, Error was: No module named backend.base Probably, I am missing something. -
How to filter ManyToManyField with distinct?
I am using Django+postgres and have this model: class Room(models.Model): users = models.ManyToManyField(settings.AUTH_USER_MODEL) type = models.IntegerField(default=1) room table data example: ____________________ | id | type | |-------------------- | 1 | 1 | | 2 | 1 | | 3 | 2 | ... room_users table data example: ____________________ | room_id | user_id | |-------------------- | 1 | 100 | | 1 | 101 | | 2 | 100 | | 2 | 102 | | 3 | 103 | ... Q: How to get room_id where only 2 users are participated and room has type=1? As you know, ManyToManyField automatically creates room_users table. Here is example code if I access directly to room_users, but I don't know how (room_users does not presented in django as model because of ManyToManyField): user_id_1 = 100 user_id_2 = 101 rooms = Room.objects.filter(users__in=[user_id_1, user_id_2], type=1).distinct("users__room_id").values_list("users__room_id", flat=True) # result must me rooms[0].id = 1, len(rooms) = 1 For this case error is: django.core.exceptions.FieldError: Cannot resolve keyword 'room_id' into field. Choices are: date_joined, email, first_name, groups, id, is_active, is_staff, is_superuser, last_login, last_name, logentry, password, user_permissions, username -
django- trouble with mixins
so i was attempting to follow the django docs- https://docs.djangoproject.com/en/1.11/topics/class-based-views/mixins/#using-formmixin-with-detailview essentially I'm making a stackoverflow clone using django. people can ask questions, which can be responded to with answers now i can make it work if i provide a link that brings them to a seperate page to submit their answer. but that sucks. i want the answer form to be on the question page based on the docs i came to this code urls.py- url(r'^view/(?P<pk>\d+)/$',views.QuestionDetail.as_view(),name='detail'), views.py- class QuestionDetail(View): def get(self, request, *args, **kwargs): view = QuestionDisplay.as_view() return view(request, *args, **kwargs) def post(self, request, *args, **kwargs): view = Answer.as_view() return view(request, *args, **kwargs) which (i believe) should render one view for a post request and a different one for a get request class QuestionDisplay(generic.DetailView): model = Question template_name = 'questions/question_detail.html' def get_context_data(self, **kwargs): context = super(QuestionDisplay, self).get_context_data(**kwargs) context['form'] = AnswerForm() return context ^ this part works fine class Answer(SingleObjectMixin, FormView): template_name = 'questions/question_detail.html' form_class = AnswerForm model = Answer def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseForbidden() self.object = self.get_object() return super(Answer, self).post(request, *args, **kwargs) def get_success_url(self): return reverse('questions:detail', kwargs={'pk': self.object.pk}) ^ the problem (i think) when i attempt to submit an answer in the form provided on … -
How to use CSRF Tokens within Chrome Plugins/From other origins
My basic goal is to send some data from a chrome plugin to a Django server. My basic attempt thus far has looked like this: Use javascript to capture data within plugin code. loginData = { 'username': document.getElementById("login-email").value, 'password': document.getElementById("login-password").value }; Send this to Django using the REST Framework. csrfToken = getCookie('csrftoken'); $.ajax(login_url, { type: 'post', data: JSON.stringify(loginData), contentType: 'application/JSON', dataType: 'json', headers: { 'HTTP_X_CSRFTOKEN': csrfToken }, success: function (data, status, XhrObj) { // Do some stuff }, error: function (XhrObj, status, error) { // Do some other stuff } }); Where I'm getting stuck is I keep getting the error response {"detail":"CSRF Failed: CSRF token missing or incorrect."} I have attempted to follow the instructions listed in Django's documentation for adding the CSRF header into requests, however the getCookie function they declare there always returns null because the page I'm doing this from is not from that domain (remember it's inside the Chrome plugin "domain") and therefore doesn't have access to my cookies (rightfully so). Further in that documentation they mention that "If you activate CSRF_USE_SESSIONS, you must include the CSRF token in your HTML and read the token from the DOM with JavaScript." However, doesn't including that token … -
django admin and autocomplete light: Select2: An instance of jQuery or a jQuery-compatible library was not found
Autocomplete light widget doesn't load completely for the field i'm trying to code it on in admin. Instead, I get the following Select2: An instance of jQuery or a jQuery-compatible library was not found. Make sure that you are including jQuery before Select2 on your web page. Alongside a select box with only one option. This is similar to actualy several questions that have been asked previously about the select2 library, and most of the solutions have involved reordering files in settings.py or running python manage.py collectstatic. But none of those have worked so far for me. The task is to include jQuery before Select2 on my web page... how can that be done? -
Django - (1366, "Incorrect string value:... error
I am getting the following error when I try to add a new record via django admin: OperationalError at /admin/competition/sport/add/ (1366, "Incorrect string value: '\xC4\x9F\xC3\xBC' for column 'object_repr' at row 1") Request Method: POST Request URL: http://127.0.0.1:8000/admin/competition/sport/add/ Django Version: 1.11.4 Exception Type: OperationalError Exception Value: (1366, "Incorrect string value: '\xC4\x9F\xC3\xBC' for column 'object_repr' at row 1") Here is the model: class Sport(models.Model): is_team = models.BooleanField(_("Is Team")) name = models.CharField(_("Name"), max_length=200) And options for mysql backend at my settings.py: 'OPTIONS': { 'charset': 'utf8mb4', 'init_command': 'SET character_set_connection=utf8mb4;' 'SET collation_connection=utf8mb4_unicode_ci;' "SET NAMES 'utf8mb4';" "SET CHARACTER SET utf8mb4;" }, I have updated all of the tables and columns to use utf8mb4 as described here Nothing has worked so far. I get no error when I try to insert a record that contains unicode characters using mysql shell, but the django admin gives the error above. -
django, apache, mod_wsgi on Windows
I am trying to get a django app running on Windows Server 2016 using apache and mod_wsgi. I have tried many, many different things based on what I have read at these (and other) links: How to install mod_wsgi for apache 2.4 and python 3.4 on windows? https://github.com/GrahamDumpleton/mod_wsgi/blob/develop/win32/README.rst Currently I have apache installed from https://www.apachelounge.com/download/VC10/binaries/httpd-2.4.23-win32.zip and pip install mod_wsgi runs without errors, but when I run mod_wsgi-express module-configI get: LoadModule wsgi_module "c:/python27/lib/site-packages/mod_wsgi/server/mod_wsgiNone" WSGIPythonHome "c:/python27" What is that None at the end of the path? What am I doing wrong? -
How to retrieve image from Django through database?
I am trying to have user see their photo once they login. The images already saved into the db, I just need it to appear once they login. Here is my Models & Forms: Models: I am trying to have user see their photo once they login. The images already saved into the db, I just need it to appear once they login. Here is my Models & Forms: Models: class UserProfileInfo(models.Model): class UserProfileInfo(models.Model): # Create relationship (don't inherit from User!) user = models.OneToOneField(User) # Add any additional attributes you want portfolio_site = models.URLField(blank=True) # pip install pillow to use this! profile_pic = models.ImageField(upload_to='profile_pics',blank=True) def __str__(self): # Built-in attribute of django.contrib.auth.models.User ! return self.user.username Forms: class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = ('username','email','password') class UserProfileInfoForm(forms.ModelForm): class Meta(): model = UserProfileInfo fields = ('portfolio_site','profile_pic') -
How to create a custom AutoField primary_key entry within Django
I am trying to create a custom primary_key within my helpdesk/models.py that I will use to track our help desk tickets. I am in the process of writing a small ticking system for our office. Maybe there is a better way? Right now I have: id = models.AutoField(primary_key=True) This increments in the datebase as; 1, 2, 3, 4....50... I want to take this id assignment and then use it within a function to combine it with some additional information like the date, and the name, 'HELPDESK'. The code I was using is as follows: id = models.AutoField(primary_key=True) def build_id(self, id): join_dates = str(datetime.now().strftime('%Y%m%d')) return (('HELPDESK-' + join_dates) + '-' + str(id)) ticket_id = models.CharField(max_length=15, default=(build_id(None, id))) The idea being is that the entries in the database would be: HELPDESK-20170813-1 HELPDESK-20170813-2 HELPDESK-20170814-3 ... HELPDESK-20170901-4 ... HELPDESK-20180101-50 ... I want to then use this as the ForeignKey to link the help desk ticket to some other models in the database. Right now what's coming back is: HELPDESK-20170813-<django.db.models.fields.AutoField>