Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Structuring Django application
I am currently working on designing a web application to be used by researchers to conduct reviews. In this application there are two groups of users - participants and administrators. Only administrators can start a review and can assign any user or administrator to participate in the review as an admin or a screener. The general workflow for each review will be: Search medical databases and import thousands of references. Screen references based on title (number of reviewers/admins Screening can be 1 or multiple). Each reviewer will screen all references. Mark each reference as included or excluded. Screen included references based on abstract. Same as above applies. Source full-text as PDF and store for included references. Screen included references based on full text. Same as above applies. Create custom forms. Extract data from included references. Export My question is this, how can I best split these sections into django apps and how should I structure the required databases. Provisionally, I've thought about having these databases: Users. Stores info on screeners and reviewers and which projects a tenner and admin in. Project. Stores basic info on each project including data extraction form. One to many relationship with references table. References. Stores … -
Django Context Processor Login In Issue
I have a login system: def login(request): title = "Login" if request.user.is_authenticated(): return HttpResponseRedirect('/') form = UserLoginForm(request.POST or None) if request.POST and form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = auth.authenticate(username=username, password=password) if user: auth.login(request, user) return HttpResponseRedirect("/")# Redirect to a success page. return render(request, 'accounts/login.html', {'title':title, 'form': form }) def logout(request): auth.logout(request) return HttpResponseRedirect('/accounts/login') and it works fine. However, when I try to add in a context_processor it stops working and gives me the following error: Environment: Request Method: GET Request URL: http://localhost:8000/accounts/login/ Traceback: File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/Users/andyxu/Documents/ece496-web/capstone/views.py" in login 22. return render(request, 'accounts/login.html', {'title':title, 'form': form }) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/shortcuts.py" in render 30. content = loader.render_to_string(template_name, context, request, using=using) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/loader.py" in render_to_string 68. return template.render(context, request) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/backends/django.py" in render 66. return self.template.render(context) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/base.py" in render 206. with context.bind_template(self): File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py" in __enter__ 17. return self.gen.next() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/template/context.py" in bind_template 236. updates.update(processor(self.request)) Exception Type: TypeError at /accounts/login/ Exception Value: 'NoneType' object is not iterable Here is my context_processor.py: from matchalgorithm.models import … -
setting random password in django for USER
I would just like to ask much more expirenced djangos. Is there a pythonic or actually djangonic way to use admin site, Users and generate random password while manually adding usernames? As far as I see, password is required, is there any option to make it non-required and add an app which would generate password? -
django rest framework changing id to url
Suppose, I have a model Collection and one-to-many relationship to CollectionImage class Collection(models.Model): name = models.CharField(max_length=500) description = models.TextField(max_length=5000) publish = models.DateTimeField(auto_now=False, auto_now_add=True) author = models.CharField(max_length=500) def __str__(self): return self.name class CollectionImage(models.Model): collection = models.ForeignKey('Collection', related_name='images') image = models.ImageField(height_field='height_field', width_field='width_field') height_field = models.IntegerField(default=0) width_field = models.IntegerField(default=0) def __str__(self): return self.collection.name I created a Serializer class for my model class CollectionSerializer(ModelSerializer): class Meta: model = Collection fields = [ 'id', 'name', 'description', 'publish', 'author', 'images', ] and a API View class CollectionList(ListAPIView): queryset = Collection.objects.all() serializer_class = CollectionSerializer The problem that i have, is that the field images gives an array of ids, where i would like it to be an array of Image urls, is it possible to do ? -
django python optimize filter queries
I have several params: age, height, weight and so on. I need to make search by this params. Right now I can do it like this: persons.vip = Person.get_vip() params.search.age = request.GET.get('age') if params.search.age: range = params.search.age persons.vip = persons.vip.filter(age__gte=range) else: do somethin params.search.weight= request.GET.get('weight') if params.search.weight: range = params.search.weight persons.vip = persons.vip.filter(age__gte=range) else: do somethin And the same code block for other params like height and so on. How do I optimize this code and get rid off code repetition? -
Cannot Install Fixture: file is encrypted or is not a database
I'm working on a website which allows users to nominate and vote for different positions. I use Python 2.7 and Django 1.10. The position objects were added through django's admin interface on the actual server. Therefore, my local server is empty of any positions. I wanted to add the positions to my local server for the sake of development. I ran the command python manage.py dumpdata voting.Position --=2 > voting/fixtures/default_positions.json. The fixture has been made, and now I want to loaddata. When I run python manage.py loaddata voting/fixtures/default_positions.json (on my local dir. not the website's/server's one), I get the following error: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 305, in run_from_argv self.execute(*args, **cmd_options) File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 356, in execute output = self.handle(*args, **options) File "/usr/lib/python2.7/site-packages/django/core/management/commands/loaddata.py", line 64, in handle self.loaddata(fixture_labels) File "/usr/lib/python2.7/site-packages/django/core/management/commands/loaddata.py", line 104, in loaddata self.load_label(fixture_label) File "/usr/lib/python2.7/site-packages/django/core/management/commands/loaddata.py", line 167, in load_label obj.save(using=self.using) File "/usr/lib/python2.7/site-packages/django/core/serializers/base.py", line 201, in save models.Model.save_base(self.object, using=using, raw=True, **kwargs) File "/usr/lib/python2.7/site-packages/django/db/models/base.py", line 824, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/usr/lib/python2.7/site-packages/django/db/models/base.py", line 889, in _save_table forced_update) File "/usr/lib/python2.7/site-packages/django/db/models/base.py", line … -
Django calling view method twice
This is my url.py code: urlpatterns = [ url(r'^test/', views.test, name='test'), ] This is my views.py code: def test(request): print ("++++++++++++++++++++++++++++++++++++++++++++++++") return render(request, 'my_app/index_test.html') This is my output from console Django version 1.10.6, using settings 'some_project.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. ++++++++++++++++++++++++++++++++++++++++++++++++++++++ [03/Apr/2017 01:24:41] "GET /test/ HTTP/1.1" 200 26814 [03/Apr/2017 01:24:41] "GET /static/css/normalize.css HTTP/1.1" 200 8053 [03/Apr/2017 01:24:41] "GET /static/css/bootstrap.min.css HTTP/1.1" 200 102897 [03/Apr/2017 01:24:41] "GET /static/css/font-awesome.min.css HTTP/1.1" 200 21979 [03/Apr/2017 01:24:41] "GET /static/css/animate.css HTTP/1.1" 200 63414 [03/Apr/2017 01:24:41] "GET /static/css/gg_preloading.css HTTP/1.1" 200 3816 [03/Apr/2017 01:24:41] "GET /static/css/prettyPhoto.css HTTP/1.1" 200 19888 [03/Apr/2017 01:24:41] "GET /static/css/style.css HTTP/1.1" 200 23649 [03/Apr/2017 01:24:41] "GET /static/js/jquery-1.10.2.min.js HTTP/1.1" 200 93107 [03/Apr/2017 01:24:41] "GET /static/js/bootstrap.js HTTP/1.1" 200 58327 [03/Apr/2017 01:24:41] "GET /static/js/waypoints.min.js HTTP/1.1" 200 8044 [03/Apr/2017 01:24:41] "GET /static/js/jquery.scrollto.min.js HTTP/1.1" 200 2434 [03/Apr/2017 01:24:41] "GET /static/js/jquery.localscroll.min.js HTTP/1.1" 200 1560 [03/Apr/2017 01:24:41] "GET /static/js/scripts.js HTTP/1.1" 200 5183 [03/Apr/2017 01:24:41] "GET /static/js/less.min.js HTTP/1.1" 200 143621 [03/Apr/2017 01:24:41] "GET /static/img/empty_1.png HTTP/1.1" 200 15358 [03/Apr/2017 01:24:41] "GET /static/img/empty_2.png HTTP/1.1" 200 15411 [03/Apr/2017 01:24:41] "GET /static/pic/%D0%9D%D0%91_Banner-6.jpg HTTP/1.1" 200 47285 [03/Apr/2017 01:24:41] "GET /static/pic/hotlog_counter.png HTTP/1.1" 200 1700 [03/Apr/2017 01:24:41] "GET /static/pic/%D0%9D%D0%91_Banner-5.jpg HTTP/1.1" 200 31588 [03/Apr/2017 01:24:41] "GET /static/pic/%D0%9D%D0%91_Banner-1.jpg HTTP/1.1" 200 33355 [03/Apr/2017 01:24:41] "GET /static/pic/%D0%9D%D0%91_Banner-2.jpg HTTP/1.1" 200 … -
Django REST framework checks unnecessary permissions
Am I using django rest framework (v3.4.6) object level permissions. However, I cannot figure out a few things. First I created a custom permission that checks if user works for a specific shop: class Works4Shop(BasePermission): def has_object_permission(self, request, view, obj): profile = UserProfile.objects.get(user=request.user) profile = request.user.profile if obj.shop in profile.shops.all(): return True else: return False I then added permission_classes = (Works4Shop,) to a new custom view class ShopItemsView(APIView) Now starts the curious part first I read that I need to explicitly check for object level permissions by calling self.check_object_permissions(request,obj). However what I see is that getting any object through model manager enforces the policy on retrieved objects. Well not exactly, it does call the has_object_permission(self, request, view, obj) but it ignores the result. The issue is the performance, this kind of thing creates to many unnecessary selects to DB. Can anyone explain this? I can also post logs from the DB. -
Django filter by min value
Right now I have this: status = request.GET.get('status') persons = Person.objects.filter(vip_status= status) How do I select all persons with vip_status > status I tried this: persons = Person.objects.filter(vip_status > status) But this didn't work But it didn't work -
Why when I run Django server it fails?
Bottom line: when I run 'python manage.py runserver 8000' I get an exception. What did I do: This is a newly installed Windows 10, so I have installed Python3 and added all parameters to Path Run 'pip install Django' and this is what I got: Then I wanted to run Django server and run 'python manage.py runserver 8000'. Instead of running the server, here is what I got: I know I have missed something, but can't figure out what. What am I missing here? Thanks! -
Django where should I put my CSS file
Where should I put my css file if I have only one file (style.css) ? I use sass for my project and I convert all my sass files to only one css file. But I don't know where I have to put this file.. because normally I would create a static folder for each app but I think that makes no sense if I have only one file... -
Django problems with apache2 mod_wsgi, _sql import error
I'm struggling to run an apache2 server for django. I wanted to try gunicorn, but as I expect apache to be installed in in workplaces more frequently, so I'll stick to it. Problem currently lies (I think) in an Import Error visible in the excerpt from apache error.log. I've tried quite a lot of possible configs, and before it didn't even import django. I'm using virtual env. The developer server from django works just fine both for the app and database. 1 [Sun Apr 02 20:58:52.082706 2017] [wsgi:warn] [pid 13495] mod_wsgi: Compiled for Python/3.4.2rc1+. 2 [Sun Apr 02 20:58:52.082907 2017] [wsgi:warn] [pid 13495] mod_wsgi: Runtime using Python/3.4.2. 3 [Sun Apr 02 20:58:52.104626 2017] [mpm_prefork:notice] [pid 13495] AH00163: Apache/2.4.10 (Raspbian) mod_wsgi/4.3.0 Python/3.4.2 configu red -- resuming normal operations 4 [Sun Apr 02 20:58:52.104798 2017] [core:notice] [pid 13495] AH00094: Command line: '/usr/sbin/apache2' 5 [Sun Apr 02 21:00:18.727276 2017] [wsgi:error] [pid 13499] [remote 192.168.1.106:0] mod_wsgi (pid=13499): Target WSGI script '/home/pi/d jangoProjects/pidjay/pidjay/wsgi.py' cannot be loaded as Python module. 6 [Sun Apr 02 21:00:18.727660 2017] [wsgi:error] [pid 13499] [remote 192.168.1.106:0] mod_wsgi (pid=13499): Exception occurred processing WSGI script '/home/pi/djangoProjects/pidjay/pidjay/wsgi.py'. 7 [Sun Apr 02 21:00:18.727938 2017] [wsgi:error] [pid 13499] [remote 192.168.1.106:0] Traceback (most recent call last): 8 … -
How to make user who has not created certain object have not an access to it using url
I have a system of adding, viewing and editing posts. I want to edit post view be only accessible for user who created this certain post. How can I achieve this point? Currently user which knows an id of a post, can edit it, even if he's not a creator, just using direct url. But I want to avoid this kind of situations. What can I do? urls.py: urlpatterns = [ url(r'^edit/(?P<pk>\d+)/$', views.edit_post, name='edit_post'), ] views.py: def edit_post(request, pk): ... return redirect(reverse('posts:edit_post')) template.html: {% for post in posts %} <p>{{ post.name }} {{ post.date }}<a href="{% url 'posts:edit_post' pk=post.id %}">Edit</a></p> <hr> {% endfor %} -
Create data treeview from flat structure JSON
I'm building a website with Django where I have a JSON dump to index.html based on SQL table. The datadump looks like this: [ { "category": "ADVERTISTING MGMT SERVICES", "sub_category": "CREATIVE WORK & PRODUCTION" }, { "category": "ADVERTISTING MGMT SERVICES", "sub_category": "MEDIA PLANNING & BUYING" }, { "category": "AIR FREIGHT", "sub_category": "AIR FREIGHT" }, { "category": "AIR TRAVEL", "sub_category": "AIR TRAVEL" }, { "category": "AUTOMATION & COMPONENTS", "sub_category": "APPLICATION SOFTWARE" }, { "category": "AUTOMATION & COMPONENTS", "sub_category": "BUTTONS" }, { "category": "AUTOMATION & COMPONENTS", "sub_category": "CABINET CLIMATE CONTROL" } ] I want to create a data treeview based on a category name which should look something like this: - ADVERTISTING MGMT SERVICES - CREATIVE WORK & PRODUCTION - MEDIA PLANNING & BUYING - AIR FREIGHT - AIR FREIGHT - AIR TRAVEL - AIR TRAVEL - AUTOMATION & COMPONENTS - APPLICATION SOFTWARE - BUTTONS - CABINET CLIMATE CONTROL What would be the best approach? I was thinking of processing JSON output so that plugins like jsTree could read the data, but I was not able to make it work. The list will be quite long, 2000+ rows, so some lightweight fast solution would be the best. -
Django class-based DeleteView robust confirmation?
I'm using Django 1.10.6 and I'm using a class-based view DeleteView. Example myapp/views.py: from django.views.generic.edit import DeleteView from django.urls import reverse_lazy from myapp.models import Author class AuthorDelete(DeleteView): model = Author success_url = reverse_lazy('author-list') Example myapp/author_confirm_delete.html: <form action="" method="post">{% csrf_token %} <p>Are you sure you want to delete "{{ object }}"?</p> <input type="submit" value="Confirm" /> </form> Because deleting is a serious operation, I want to add more robust confirmation such that the user needs to type the author name in before the author can be deleted (and it must match. similar to the github confirmation for deleting repositories). I guess this might be implemented as some kind of form validation. What's the django-way to add this type of confirmation? -
Django M2M CreateView and UpdateView from related model
I've got these models: class Company(models.Model): name = models.CharField(max_length=50, null=False, blank=False, verbose_name=ugettext_lazy(u'Name')) building = models.ForeignKey(Building, null=False, blank=False, verbose_name=ugettext_lazy(u'Building')) parking_spaces_count = models.PositiveIntegerField(verbose_name=ugettext_lazy(u'Parking spaces count')) def __unicode__(self): return unicode(self.name) class Car(models.Model): registration_number = models.CharField(max_length=10, blank=False, null=False, verbose_name=ugettext_lazy(u'Registration number')) def __unicode__(self): return unicode(self.registration_number) class Employee(models.Model): first_name = models.CharField(max_length=50, null=False, blank=False, verbose_name=(ugettext_lazy(u'First name'))) last_name = models.CharField(max_length=50, null=False, blank=False, verbose_name=(ugettext_lazy(u'Last name'))) id_number = models.CharField(max_length=20, null=False, blank=False, verbose_name=(ugettext_lazy(u'Identification card number'))) company = models.ForeignKey(Company, null=False, blank=False, verbose_name=ugettext_lazy(u'Company'), related_name='employees') cars = models.ManyToManyField(Car, verbose_name=ugettext_lazy(u'Cars'), related_name='owners') def __unicode__(self): return unicode(' '.join([self.first_name, self.last_name])) and I'd like to be able to implement: 1 - CarCreateView - where I would create a Car object in my database by supplying its registration_number and owners (which is a related field from Employee model) fields. When I try putting 'owners' in fields like that (using Django's CreateView): fields = ('registration_number', 'owners') I get an error "Unknown field(s) (owners) specified for Car". I managed to simulate it with FormView which works: class CarCreateView(FormView): model = Car template_name = 'companies/cars/add.html' form_class = CarCreateForm success_url = reverse_lazy('companies:cars:list') def form_valid(self, form): employees = form.cleaned_data['owners'] registration_number = form.cleaned_data['registration_number'] car = Car(registration_number=registration_number) car.save() car.owners = employees return super(CarCreateView, self).form_valid(form) My question here is - is this DRY or could it be better? … -
Dynamic Fields Django Quiz App
I am really stuck at the moment. I have searched on here, tutorials, and the documentation. I am trying to dynamically create a specific field. For example, a user can chose to have anywhere from 2-6 answers in a multiple choice quiz. However, the tutorials I've followed to seem to be of no help and I have a hard time understanding the documentation. I got very strange answers when using inline formsets. here is my form and model code as it stands. class QuizForm(forms.Form): class Meta: model = Quiz fields = ['title', 'answerA', 'answerB', 'answerC', 'answerD', 'difficulty_level', 'correctAnswer'] title = forms.CharField(max_length=1500) answerA = forms.CharField(max_length=150) answerB = forms.CharField(max_length=150) answerC = forms.CharField(max_length=150) answerD = forms.CharField(max_length=150) difficulty_level = forms.ChoiceField(choices=Quiz.DIFFICULTY_LEVELS) # score = forms.CharField(max_length=150) correctAnswer = forms.CharField(max_length=150) class Quiz(models.Model): quizID = models.AutoField(primary_key = True) title = models.CharField(max_length=1500, default = '') answerA = models.CharField(max_length=150, default='') answerB = models.CharField(max_length=150, default='') answerC = models.CharField(max_length=150, default='') answerD = models.CharField(max_length=150, default='') # score = models.CharField(max_length=150, default='') correctAnswer = models.CharField(max_length=150, default='') DIFFICULTY_LEVELS = ( ('Beginner', '1'), ('Intermediate', '2'), ('Advanced', '3'), ) difficulty_level = models.CharField(max_length=1, choices=DIFFICULTY_LEVELS, default='') def __str__(self): return self.title -
Django and api widget
I am relatively new in web development and I needed your help with the following. I am creating a basic website using Django where a user can manage his portfolio. Now I was using this widget from Tradingview.com in this manner. Now what I wanted to know was if I could somehow store what the user was adding in the watchlist in the database itself and load it when the widget loads next time -
How to select element inside iframe from parent page?
I have a template from which I'm dynamically generating an iframe to another url, within the same domain. Is it possible to select elements on the iframe from my parent page? This is what I have so far: My Parent Template: <a id="load_temp" class="btn btn-warning" style="margin-left: 5px">Load Template</a> var radio_select #get value from iframe $(document).ready(function() { var url = "{% url 'backend_list_template' %}"; var $dialog = $('<div></div>') .html('<iframe id="temp_list" style="border:0;" src="{% url 'backend_list_template' %}" width="100%" height="100%"></iframe>') .dialog({ autoOpen: false, title: 'Template List', height: 625, width: 500 }); $('#load_temp').click(function() { $dialog.dialog('open'); }); }); The iframe template: <h1>List of Templates</h1> <input type="button" value="Refresh Page" onClick="window.location.reload()"><br> {% if templates %} {% for template in templates %} <br><input type="radio" value="{{ template.temp_body }}" name="temp_name">{{ template.temp_name }}<br> {% endfor %} {% endif %} <br><input type="button" id="load_temp" value="Load Template"> #Clicking this load button should have the value of the radio button in the parent template What I'm trying to do is when someone clicks on the load button in the iframe, the variable radio_select should get the value of the radio select from the iframe, so that I can use it in the parent page to process data. Is this possible? -
Django tries to insert null in fields during object update
I have Post entity in my database, and Content entity, Post has foreign key to Content, so it looks like that: class Content(models.Model): ''' Entity contains content for according post, in multiple languages ''' english_title = models.CharField(max_length=100, validators=[MinLengthValidator(3)]) polish_title = models.CharField(max_length=100, validators=[MinLengthValidator(3)]) english_content = models.TextField(blank=True, null=True) polish_content = models.TextField(blank=True, null=True) polish_link = models.CharField(max_length=60, unique=True, validators=[MinLengthValidator(3)]) english_link = models.CharField(max_length=60, unique=True, validators=[MinLengthValidator(3)]) class Meta: unique_together=('polish_link', 'english_link') class Post(models.Model): ''' Its an entity reptesenting a single post. It's content is in 'Content' table ''' content = models.ForeignKey(Content, on_delete=models.CASCADE) category = models.CharField(max_length=50, validators=[MinLengthValidator(3)]) author = models.CharField(max_length=50, validators=[MinLengthValidator(3)]) date = models.DateTimeField() And I'm running test like: def test_can_edit_post(self): c = Client() c.login(username='bunny', password='p455w0rd') response = c.post('/edit_post/', {'id': '2', 'english_content': 'edited english content'}, HTTP_X_REQUESTED_WITH='XMLHttpRequest') content = json.loads(response.content) sys.stdout.write(Post.objects.get(pk=2).content.english_content) sys.stdout.write(json.dumps(content)) self.assertEqual(200, response.status_code) self.assertEqual('OK', content['status']) self.assertTrue('edited' in Post.objects.get(pk=2).content.english_content) And it shows, that 'edited' is not in english_content. When I print content is says that {"text": "{'english_title': ['This field cannot be blank.'], 'polish_title': ['This field cannot be blank.']}"} And my edit function, I'm testing is: @login_required() def edit_post(request): if not request.is_ajax(): return JsonResponse({'text': 'ajax is required'}, status=500) pk = request.POST.pop('id', None)[0] post = request.POST post_info = {} content_info = {} if 'english_title' in post: content_info['english_title'] = post['english_title'] if 'polish_title' … -
How to populate a list looping in another list in Python?
I am making a search page on Django and want to generate a dynamic queryset. I have a list of string filters initiaized like this: filter_names = ('filter1', 'filter2') then, I want to loop in my filter_names list and make a list of Q objects for each filter that comes in the request (with the same names in filter_names). I am creating the list of Q like this: filter_clauses = [Q(filter=request.GET.get(filter)) for filter in filter_names if request.GET.get(filter)] the problem is that the resultant list (filter_clauses) is something like: Q(filter=value1), Q(filter=value2) But I actually want a list like: Q(filter1=value1), Q(filter2=value2) In effect, the loop is not catching the value of the variable filter but interpreting it as "filter". So, am I doing anything wrong in the loop? For more information, I took the idea from this answer, And I'm getting this error: Cannot resolve keyword 'filter' into field. that means, that the framework is searching a field in the searched model with the name 'filter' and obviusly doesn't find it. -
Calling a python function from a javascript code
Is there a way to call a python function from a script block? If there is, can you tell me how about to do it (in details, please?) and preferable a link or video where I can learn more about it. Thanks in advance. -
Generate form directly in template ? (Django)
I have a menu where I want to put forms. This menu is part of my template base.html which will be extended by all my views. My simple form (in myapp/forms.py) class LoginForm(forms.Form): username = forms.CharField(label="name") password = forms.CharField(label="password", widgt=forms.PasswordInput) The simplest way I see it would be to generate the form from views.py in a method that will be called in every method from my views.Something like : def preprocess(request): forms = [] forms.extend(LoginForm(), SubscribeForm(), ... ) return forms def myview1(request): forms = preprocess(request) ... return render(request, "template1.html", locals()) #template1 extends base.html def myview2(request): forms = preprocess(request) ... return render(request, "template2.html", locals()) #template2 extends base.html base.html : <html> {{ forms[0].as_p }} {{csrf_token }} </html> All this code is untested and is really probably not working due to some mistakes, but I bet you get the idea. Is it the best way to do it ? Some way to directly generate a form in the template ? I could also write the form by myself in the template but that's not what I want to achieve. -
django - WSGIRequest object has no attribute PUT
trying to make a put request to the local server using the put request using curl `curl -X PUT -H "Content-Type: application/json" -d '{"connid":"12"}' "127.0.0.1:8000/api/kill"` my code is as follows but i am receiving the same response 'WSGIRequest' object has no attribute 'PUT' def kill(req): conid = req.PUT['connid'] statusres = {} if conid in state: error[conid] = 'true' statusres['status'] = 'ok' else: statusres['status'] = 'invalid connection Id : '+ conid return JsonResponse(statusres) i also used @csrf_exempt before the function -
django session table 'django_session' missing primary key
After Creating a backup file and restoring it, i notice that the primary key was missing in 'django_session' table (im using postgresql). This db file was restored in live site. I noticed that db was utilizing 99% of CPU. Please help me understand what could have happened, to delete the primary key in 'django session' table. I was using this same backup file in uat environment, but dint notice this until it went to prod.