Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to convert form data to django?
How to convert form data to django? I have a html formalary that sends several arrays given. for example: <input name="item[0]nome"/> <input name="item[0]descriaco"/> <input name="item[1]nome"/> <input name="item[1]descriaco"/> This comes from the html form With this I can pass the data to a view in Django using post and at the same time pass an is_valid. Goodbye then. When trying to grab the dest object items as array, I came across a problem. The Django Form returns me the key with the name "item[0]name" Instead of returning an array with: item[{ "nome": value, "descricao": value}, { "nome": value, "descricao": value} ] Thank you for attention. -
Getting django rest framework jwt authentication to work [django rest, angular 5]
so I have installed djanogo rest framework JWT and set the settings and authetication classes. According to this guide. I will leave out the settings as they are correct, and that is not where the problem lies. It is also to not post too much code https://getblimp.github.io/django-rest-framework-jwt/ I then make a call to a authorization view on my server from the front end let token = "hardcoded token just to get the service working"; if(token != null){ this.authservice.authorizetoken(token) .subscribe( (req: any)=>{ console.log(req); } ); // grab the permissions a user has and who they are by token authorizetoken(token){ return this.http.get(userauthorization, { headers: new HttpHeaders().set('Authorization', 'JWT' + token ) }); } then in my django here is the view code: class UserAuthorization(APIView): authentication_classes = (JSONWebTokenAuthentication,) def get(self, request, *args, **kwargs): print(request.user) return Response({}) but I keep getting anonymousUser returned. Shouldn't it be a user object since I am passing a token in the header? I dont know what I am doing wrong. -
django : 'Manager' object is not iterable
I'm trying to make a table getting data from models. But I'm getting this error : TypeError at /main/ 'Manager' object is not iterable Template File: 3 <head> 4 <meta charset="UTF-8"> 5 <title>Acc</title> 6 7 </head> 8 <body> 9 <h1>The Values are:</h1> 10 {% if main %} 11 12 <table> 13 {% for obj in main %} 14 <tr> 15 <td>{{ obj.isTremor }}</td> 16 <td>{{ obj.isFall }}</td> 17 </tr> 18 {% endfor %} 19 </table> 20 21 {% endif %} 22 </body> 23 </html> I'm sorry if this is a very absic question, but I'm very new to this. Thanks EDIT 1 : View that renders this : def main(request): acc_list = AccModel.objects acc_dict = {'main': acc_list} return render(request, 'appTwo/main.html', context=acc_dict) URL : url(r'^main/', views.main, name='main'), -
How to get inputs in get_queryset() in Django
I'm currently trying to convert my FBV function to a CBV one. class SearchListView(ListView): def get_queryset(self): search_text = request.GET.get('search_text') ... But, I'm already stuck with the beginning part. I need a value of search_text to filter my queryset afterward. When using FBV, I got inputs through reqest.GET.get() but it doesn't work anymore in CBV. What can replace it with? -
Looping ahref with django and javascript
I'm trying to generate chart for each ahref link but ahref is not rendering chart and all ahref link is not working. I have side navbar where I have all the database tables listed with ahref link to each table and click on table link that should render chart. Here is my portion of code: <form type="get" enctype="multipart/form-data"> {% csrf_token %} <ul class="list-group"> {% for table in tables %} <li> <a href="/test/tablesgrowth/?search2={{ table|safe }}" onclick="tablechart();return false;">{{ table|safe }}</a> </li> {% endfor %} </ul> </form> <div class="col-lg-9"> <h2> Growth </h2> <br> <div id="tablechart"></div> </div> function tablechart() { var tablechart = c3.generate({ bindto: '#tablechart', data: { x: 'x', columns: [{{ tdates|safe }}, {{ tdata|safe }} ] }, axis: { x: { type: 'timeseries', tick: { format: '%Y-%m-%d' } }, y: { label: { text: 'Data Growth in GB', position: 'outer-middle' } } } }); } views.py: args={'tdates': daily_date,'tdata': data,'tables': tables_list} return render(request,'test/datagrowth.html',args) I'm newbie to Django & javascript. Please help me out. -
Django 404 on POST request
I'm trying to send a form via POST on my site, however, it appears the first part of the POST URL is being chopped off leading to it not being able to match the correct url. The form I'm trying to send in the template: <form action= "{% url 'change_portrait' %}" method="post"> {% csrf_token %} <h5>Edit Portrait</h5> <input type="hidden" name="portrait_id" value="{{image.pk}}"> <button type="submit" name="button" class="btn btn-primary">Submit Changes</button> </form> which correctly renders to: <form action= "/AdminDashboard/EditPortraits/ChangePortrait/" method="post"> <input type='hidden' name='csrfmiddlewaretoken' value='iCt1xvIc1KZXErhbcMNepk2daHXApGih' /> <h5>Edit Portrait</h5> <input type="hidden" name="portrait_id" value="14"> <button type="submit" name="button" class="btn btn-primary">Submit Changes</button> </form> The action URL is correct, and is where I want the form to be submitted to. However, when the form is submitted I get a 404 with the following message: Using the URLconf defined in ZachWebsite.urls, Django tried these URL patterns, in this order: ^admin/ ^AdminDashboard/ ^ ^SundayPortraits/ [name='sunday_portraits'] ^ ^Contact/ [name='contact_submission'] ^ ^SubmitOrder/ [name='submit_buy_order'] ^ ^BuyPrint/ [name='buy_print'] ^ ^$ [name='index'] ^ ^Login [name='login'] ^ ^Logout [name='logout'] ^ ^media\/(?P<path>.*)$ The current URL, EditPortraits/ChangePortrait/, didn't match any of these. Here is my base urls.py urlpatterns = [ url(r'^AdminDashboard/', include('AdminDashboard.urls')), url(r'^', include('mainApp.urls')) ] And AdminDashboard.urls: urlpatterns = [ url(r'^EditPortraits/ChangePortrait/', views.change_portrait, name='change_portrait'), url(r'^EditPortraits/', views.edit_portraits, name='edit_portraits'), url(r'^', views.dashboard, name='dashboard'), ] … -
Validating html sliders
I am very new to programming and I am working on an online experiment with Django. We are using sliders extensively throughout the experiment as an input device, and we need to find a way to validate the sliders to make sure our participants actually moved/clicked on the sliders somehow. The form input should be integers, and I have tried: 1. clearing the starting value 2. setting the starting value to a decimal so it won't pass integer check when submitting the form(it passed anyway for some reason) 3. setting the starting value to a string (broke the slider altogether) Got no joy from any of these methods. I am using carpe custom slider to remove the hovering number when dragging the slider. http://carpe.ambiprospect.com/slider/ Here are my codes: HTML: <div class="form-group {% if form.trust.errors %}has-error {% endif %}"> <label class="control-label" for="trust">Your Trust</label> <input id="trust" name="trust" type="range" style="width: 300px;" tabindex="0" min="0" max="100" step="1" value="50.111111111111111111" data-carpe-decimals="0" value="{{form.trust.value}}" </div> <div class="btn_block"> <button type="submit" class="btn btn-primary pull-right" alt="proceed to next page">Next</button> </div> forms.py: class TaskbeginForm(forms.Form): trust = forms.IntegerField() As I am very new to html and know nothing about javascript, please treat me like a pre-schooler and I can probably only understand very simple … -
Session ID tokens in django without auth.models.User
I know that one can set up authentication with the built in django login(request, user), request.is_authenticated when the user acquires the sessionid cookie, and authenticate(request, username="foo", password="bar"). However, underneath this interface, django creates a User object in the database. I am authenticating using other means, namely LDAP. I can opt for just passing the username and password for LDAP every single time, but having a sessionid token would be ideal. Is there any way to use the same login(), request.is_authenticated, authenticate() API but without using the User model underneath? Another alternative is fine as well. The one restriction that I have is that I do not want to use another library. Thanks! -
How to make files available download in Django
This is my model class UploadAssignment(models.Model): doc=models.FileField() assignment = models.ForeignKey(AssignAssignment, on_delete=models.CASCADE) student= models.ForeignKey(Student, on_delete=models.CASCADE) This is my view to upload. def upload_assignment(request,pk): student = get_object_or_404(Student,user_id=request.user) assign = get_object_or_404(AssignAssignment, pk=pk) if request.method == 'POST': form = AssignmentUpload(request.POST, request.FILES) if form.is_valid(): m=form.save(commit=False) m.student_id=student.user_id m.assignment_id=assign.pk print(m) m.save() messages.success(request, 'Assignment upload is successful') return redirect('home') else: form = AssignmentUpload() return render(request, 'accounts/students/uploadassignments.html', { 'form': form }) I'd like to write a view function for lecturer to download those files with upload assignment primary key. Any one have any idea? -
Django REST Framework Jalali date compatibility issues
I am using Python 3.5, Django 2.0 and Django REST Framework 3.7.7 I added django-jalali 3.0.2 to my apps for jalali calelndar compatibility. This app works fine when using admin or shell, but when I send requests using DRF, datetime object is validated using the Gregorian calendar. As a result I cannot use date with a string like 1397-02-31 or 1397-02-30. This is the response I get: HTTP 400 Bad Request Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "schedule_time": [ "Enter a valid date/time in YYYY-MM-DD HH:MM[:ss[.uuuuuu]] format." ] } THis error originates from line 252 of django_jalali/db/models.py try: # Seconds are optional, so try converting seconds first. t = time.strptime(datetime_obj, '%Y-%m-%d %H:%M:%S') because srtptime presumes datetime_obj is Datetime object not jDatetime. As mentioned before this is not a problem in admin or shell. I also have tested setting locale to 'fa_IR' and changing the object manager but no luck so far. Is there a clean solution for this or do I have to write my own app? P.S. I've noticed date_hierarchy in admin only uses Datetime (not jDatetime). I tried changing it but it fails django checks. how can I change this to jalali? I've also … -
Elasticsearch-dsl nested queries
I am using elasticsearch-dsl library in my djanog project to index data and then query it back. I have the following models: class Comments(models.Model): comment_id = models.CharField(max_length=1000,blank=True,null=True) user_post_id = models.ForeignKey('UserPosts',null=True) score = models.CharField(max_length=1000,blank=True,null=True) text = models.TextField(blank=True,null=True) creation_date = models.CharField(max_length=1000,blank=True,null=True) def __unicode__(self): return self.comment_id def indexing(self): obj = CommentsIndex( meta={'id': self.id}, comment_id=self.comment_id, user_post_id=self.user_post_id, score=self.score, text=self.text, creation_date=self.creation_date, ) obj.save(index='comments-index') return obj.to_dict(include_meta=True) class UserPosts(models.Model): user_post_id = models.CharField(max_length = 1000 , blank = True , null = True) user_post_type_id = models.CharField(max_length = 1000 , blank = True , null = True) accepted_answer_id = models.CharField(max_length = 1000 , blank = True , null = True) creation_date = models.CharField(max_length=1000,blank = True , null = True) score = models.CharField(max_length = 1000 , blank = True , null = True) view_count = models.CharField(max_length = 1000 , blank = True , null = True) body = models.TextField( blank = True , null = True) last_editor_user_id = models.CharField(max_length = 1000 , blank = True , null = True) last_editor_display_name = models.CharField(max_length = 1000 , blank = True , null = True) last_edit_date = models.CharField(max_length = 1000 , blank = True , null = True) last_activity_date =models.CharField(max_length = 1000 , blank = True , null = True) title = models.CharField(max_length = … -
Django Transactions: How to run extra code during rollback?
Imagine you have a User model in your web app, and that you need to keep this user in sync with an external service via an API. Thus, when you create a user locally, you need to create it remotely as well. You have all your operations under transaction.atomic() and you try to keep all your 3rd-party API calls after the atomic block, which is reasonable. But, a system being a system, it grows in complexity until the point you have some really hard to remove 3rd-party calls within an update call. That said, is there a way to extend Django's transaction mechanism, kind of adding some callback functions, like rollback.add_callback(clean_3rdparty_user(user_id=134))? That way I can guarantee that all necessary rollback actions are taken and my system is in sync? -
Django render_to_string cannot get i18n settings
Code (Django 1.9.5): translation.activate("en-gb") print translation.ugettext("test string") html_content = render_to_string(html_template_path) Template: {% load i18n %} {{ LANGUAGE_CODE }} {% trans "test string" %} The print statement, with ugettext, works as expected, translating my text, but the result of render_to_string is simply "test string". The template render not only fails to translate, but it doesn't even have a value for LANGUAGE_CODE at all. I would assume this is something to do with it missing a request context of some sort (i18n works in my regular views) but this function is being run as part of background script so needs to work without a request. A previous thread (How to set the language in render_to_string helper?) suggests that this should just work. Passing in a blank Context() has no effect on the result. Manually passing LANGUAGE_CODE didn't trigger the translation to happen either. Anybody have an ideas what's going wrong here? Thanks. -
Accessing specified database in migrate command django inside database router
Using Django 1.11, I am attempting to create a custom router to pick a database based on the URL that is used. For instance, if the URL is customer1.example.com, I want to pick the database 'customer1', and similarly if it is customer2.example.com, I want it to pick the database 'customer2' My current setup works great! One problem - when I try to run migrations (or other database dependent commands), then it fails - even if I specify the database using the --database option, such as python manage.py migrate --database customer1 I'm not sure what to do, as there is no request for those - I want to actually return the exact name specified in the command line (such as customer1). But it isn't in hints, or any of the other options. How do I access the command line option that was used to run the command? Otherwise I have nothing to return! This is my setup: settings.py: # Database to connect to DATABASES = { 'default': {}, 'customer1': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'xxxx', 'USER': 'yyyy', 'PASSWORD': 'zzzz', 'HOST': '192.168.168.176', 'PORT': '1521', }, 'customer2': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'xxxx', 'USER': 'yyyy', 'PASSWORD': 'zzzz', 'HOST': '192.168.168.179', 'PORT': '1521', } } # Specify … -
Using ValidationError and not redirecting to a new page
My form looks like this: class Form(forms.Form): smth = forms.ChoiceField(label='Smth', choices=[(x, x) for x in my_settings.measurements]) def clean_smth(self): smth = self.cleaned_data['smth'] if problem_condition: raise ValidationError("this sucks") return smth My view has this: if request.method == 'POST': try: form = Form(request.POST) except ValidationError as e: pass else: if form.is_valid(): form.save() return redirect('this_current_page') else: form = Form() In an ideal world, the user would submit the form and be redirected to the same exact page. If there were an error, the user would be on the same page but the error would be listed below the form. Instead, the error (inserted by the exception ValidationError) ends up in the middle of the form, creating an ugly line break. I've tried many ways to format / handle ValidationError in the template, to no avail. I want to do this all on the same page; not have some annoying separate page that the user is redirected to in case of error. It's easier to just correct the form in situ than to see the fault on another page, press back, and try again. How can I have the error printed prettily on the same template, when the error is from ValidationError? -
Celery not work: Cannot connect to amqp://guest:**@127.0.0.1:5672//
I can not run the celery worker + docker + django. I download image rabbit and linked worker, and at run I get error: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. worker_1. Django: 1.11, calary: 4.1.0. What doing wrong? docker-compose rabbit: image: rabbitmq:latest ports: - "5672:5672" worker: build: ./project volumes: - ./main:/src/app depends_on: - rabbit links: - web #django project entrypoint: /src/app/calery.sh calery from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.settings') app = Celery('app') app.config_from_object('django.conf:settings', namespace='APP') app.autodiscover_tasks() @app.task(bind=True) def add(): print('Task') -
what path am i have to use in view django cv2
i already have tried the static function but still the same problem in this code i wan't to recognise the face and return the name of the person enter image description here image 1 enter image description here image2 enter image description here image3 -
Django M2M Accessors using Externalized M2M Model
Assume we're working with two models from 3rd party libraries, trivially User and Car. Both are non-abstract and are complex enough that I want to avoid, for example, introducing multi-table inheritance to extend either with additional fields. I need to model a Many-to-Many relationship between these Models. Obviously, I can create an M2M table in the usual (from a database perspective) way: class UserCar(models.Model): user = models.ForeignKey(User) car = models.ForeignKey(Car) However, a M2M relationship in Django is normally represented by a ManyToManyField (on one side or the other) that comes with magic. For example, user.cars.add(car) car in user.cars User.objects.filter(cars=car) ... If I'm externalizing the M2M relationship, I won't get these features by default. For example, a user will need to write User.objects.filter(usercar_set__car=car). I'm working on the assumption that others will use this like (if not literally as) a 3rd party library so I really want to provide standard interfaces despite the constraints. Is there an easy way to inject the usual M2M magic on both sides of the relationship? UserCar is basically a through= table. Can I create a dummy field and call a method or two (e.g. contribute_to_class and contribute_to_related_class) to get this done? I tried puzzling through ForeignKey … -
Dynamically set choices in django model based on whether adding a new record or editing existing
I'd like to have one set of choices if adding a new record and a different set if editing an existing record. I thought something like the following would work but it doesn't. class MyModel(models.Model): CHOICES = (('1', 'Option 1'), ('2', 'Option 2'), ('3', 'Option 3'), ('4', 'Option 4'),) def test(self): if self.pk: return True if test is True: CHOICES = (('1', 'Option 1'), ('2', 'Option 2'),) my_field = models.CharField(max_length=1, choices=CHOICES) -
Increasing Django login security and password strengths
When I create the Django superuser , if I try to add a weak password Django doesn't let me, but for normal users, in admin, or using register form I can add very simple password. How can I ad the password validation from the superuser creation to all users ? Can the number of login bad tries be limited (I prefer without third-party) -
Remove repeatable @pytest.mark.django_db decorator in pytest
Is there a way to remove @pytest.mark.django_db decorator or passed it once for all tests? -
Unable to run Django in pipenv shell
If I run: $ pipenv install django $ pipenv shell (user-nKDraKU3) $ python manage.py shell I get a ModuleNotFoundError: Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' ... ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Shouldn't that work when I'm in the "activated" pipenv environment? However, this works fine: $ pipenv run python manage.py shell Python 3.6.5rc1 (default, Mar 14 2018, 06:54:23) [GCC 7.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> -
synchronizing sqlite3 to external db in django
folks, i am building trying to build an app that stores its data on sqlite3 and then synchronizes it to the maybe postgres in the cloud, i have tried django-synchro, it seeems quite outdated, i had to make several changes to it before it could work with Django 2.0 , I now face this issue AttributeError: 'ManyToManyField' object has no attribute 'rel' and the code related to it is def get_intermediary(models): res = {} for model in models: res.update((m2m.rel.through, _get_remote_field(m2m)) for m2m in model._meta.many_to_many if not m2m.rel.through._meta.auto_created) is there a way i can get around this or maybe a django package that can help with synchronizing with two databases .Thanks -
Django: Searchable form field for ManyToMany relationship
Say I have model A which has a ManyToMany attribute joining it to model B. When a user creates a model A, via some forms, they are appropriately presented with a MultipleChoiceField containing all model B objects. Now, there are a lot of model B objects. Is there a way to make thi s MultipleChoiceField searchable? Ideally I'd like to have something like this: Where each [+] represents a choice in some particular attribute of B. How could I go about achieving this? -
Django only updates template when server restarts
When I make changes to the html templates in my Django project, the changes are only reflected in the browser when my local server restarts. If I refresh without restarting the server, the updates aren't reflected. This is happening for every template in my project. Initially I thought this was a static file issue, but all other static files refresh properly (js, css etc.) I have django.contrib.staticfiles in my INSTALLED_APPS. Below is how I have things set up in settings.py: STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'debug': False, 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'common.contexts.appname' ], }, }, ]