Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
update objects before access using DetailView (Django)
I am using DetailView in Django. I have a model including certain time field(taxi_time), and I would like compare the time and now. If taxi_time < datetime.now(), I want to change a field(taxi_is_closed) in the model from False to True. So before users access the post, I need to (automatically) check the time and modify taxi_is_closed. How can I do it? My View.py : @method_decorator(login_required(login_url='/login/'), name='dispatch') class RecruitView(PermissionRequiredMixin, generic.DetailView): model = Recruit template_name = 'taxi/recruit.html' def has_permission(self): return self.request.user.profile.email_confirmed def handle_no_permission(self): error_message = '아직 인증이 완료되지 않았습니다. 이메일 인증을 완료해주세요! :)' if self.raise_exception: raise PermissionDenied(self.get_permission_denied_message()) return render(self.request, 'taxi/info.html', {'error_message': error_message}) def get_context_data(self, **kwargs): context = super(RecruitView, self).get_context_data(**kwargs) #pdb.set_trace() img_var = self.get_object().taxi_popnow*10 + self.get_object().taxi_poptot img_name = str(img_var) context['img_name'] = img_name context['ApplyForm'] = ApplyForm() return context MY model.py : class Recruit(models.Model): taxi_time = models.TimeField('출발 시각') taxi_is_closed = models.BooleanField('마감', default=False) def chk_closed(self): now = datetime.datetime.now() taxi_datetime = datetime.datetime.combine(self.taxi_date, self.taxi_time) is_full = self.taxi_poptot <= self.taxi_popnow is_past = taxi_datetime <= now if (is_full or is_past): self.taxi_is_closed = True else: self.taxi_is_closed = False self.save() I picked only related code. -
Django Use ManyToManyField Data in View
models.py class Profile(models.Model): profile_name = models.CharField(max_length = 255, blank = False) extra_profile_text = models.CharField(max_length = 50, blank = False) class Category(models.Model): category_name = models.CharField(max_length = 50, blank = False) extra_category_text = models.CharField(max_length = 50, blank = False) class ProfileCategory(models.Model): profile = models.ManyToManyField(Profile) category = models.ManyToManyField(Category) forms.py class ProfileCategoryForm(forms.ModelForm): class Meta: model = ProfileCategory fields = ('profile', 'category',) views.py def task(request): if request.method == "POST": form = ProfileCategoryForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user #use [profile_name, extra_category_text data] that user selected post.save() form.save_m2m() return redirect('somewhere') else: form = ProfileCategoryForm() context = {'form': form } return render(request, 'some_app/somewhere.html', context) I want to bring 'profile_name', 'extra_category_text' datas in view when user select from ProfileCategoryForm. process will be Front: user select one of Profile, one of Category > Save Back: get user selected Profile, Category datas(ex: profile_name, extra_profile_text) > do some task > Save to ProfileCategory model. it seems that I need to use queryset but no clue at all :( -
Django - Default Profile Picture not showing
I have a question about images and imagefields. However, the default picture I chose does not show up, only a blank circle. This was my default picture Models.py class UserProfile(models.Model): user = models.OneToOneField(User) description = models.CharField(max_length=255, default='') city = models.CharField(max_length=100, default='') website = models.URLField(default='') def __str__(self): return self.user.username class ProfilePicture(models.Model): user = models.ForeignKey(User) image = models.ImageField(upload_to='profile_image', default='profile_image/Default.jpg') Forms.py class UploadPictureForm(forms.Form): image = forms.ImageField() profile.html <div class="container"> <div id="left"> <div id="profilecard"> {% if user.userprofile.image %} <img class="circular--square" src="{{ }}" width="200" height="200"> {% endif %} <div id="info"> <br> <h3>{{ user.first_name }} {{ user.last_name }}</h3> <p>@{{ user }}</p> <p>{{ user.userprofile.city }}</p> <p>{{ user.userprofile.website }}</p> <p><i>{{ user.userprofile.description }}</i></p> </div> </div> -
Django testing user model fails but it works in the browser
I am new to testing and am trying to run the following tests but I get a 404 assertion error because the method that tries to reverse the url cannot find the category that had been created in the setUp method. I can create categories in the browser using the superuser with no problem and the url responds with 200 status. Could you help me understand what I am doing wrong? Test: from __future__ import unicode_literals from django.core.urlresolvers import reverse from django.test import TestCase from django.contrib.auth.models import User from cataloger.models import Category class CatalogerCategoriesTests(TestCase): def setUp(self): tom = User.objects.create_user(username="tom", password="1234567") Category.objects.create(name="cell phone", description="current cell phone types in the market.", created_by=tom) def test_category_page_success_status_code(self): url = reverse('category_items', kwargs={'pk': 1}) response = self.client.get(url) self.assertEquals(response.status_code, 200) Fail: Traceback (most recent call last): File "/home/ubuntu/workspace/cataloger/tests_categories.py", line 48, in test_category_page_success_status_code self.assertEquals(response.status_code, 200) AssertionError: 404 != 200 Models: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User class Category(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=300) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(null=True) created_by = models.ForeignKey(User, related_name="categories") Views: from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.models import User from cataloger.models import Category def category_items(request, pk): category = get_object_or_404(Category, pk=pk) return render(request, … -
AssertionError: 200 != 404
====================================================================== FAIL: test_dont_remember_cc (p38.tests.test_stripepayment.StripePaymentTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/infinity/.virtualenvs/p38-1/src/p38/p38/tests/test_stripepayment.py", line 77, in test_dont_remember_cc self.assertEqual(200, rs.status_code) AssertionError: 200 != 404 ---------------------------------------------------------------------- Ran 1 test in 1.200s View class OnlinePaymentView(CustomerViewMixin, TemplateView, CreateView): template_name = 'zoneclient/payment.html' form_class = OnlinePaymentForm object = None def get_success_url(self): return reverse('zoneclient-dashboard', kwargs={'clientcode': self.get_customer().code}) def get(self, request, clientcode=None): self.object = self.get_customer() return self.render_to_response({ 'customer': self.get_customer(), 'is_quickform': False, 'form': self.form_class(user=self.get_customer()), }) def post(self, request, clientcode=None): if self.request.POST.get('quickform'): self.object = self.get_customer() try: amount = '%0.2f' % float(self.request.POST.get('amount')) except ValueError: amount = '' # Paypal invoice = { 'business': settings.PAYPAL_BUSINESS, 'amount': '%0.2f' % float(request.POST.get('amount')), 'item_name': _('Online payment'), 'invoice': generate_invoice_id(self.get_customer().pk), 'notify_url': get_full_url(self.request, 'paypal-ipn'), 'return_url': '{}'.format( get_full_url(self.request, 'paypal-payment-done')), 'cancel_return': '{}'.format( get_full_url(self.request, 'paypal-payment-cancel')), 'currency_code': 'CAD', } return self.render_to_response({ 'customer': self.get_customer(), 'is_quickform': False, 'paypal_invoice': invoice, 'paypal_form': PayPalPaymentsForm(initial=invoice), 'form': self.form_class( user=self.get_customer(), initial={'amount': amount}), }) else: log.info('{} submitted a payment via website'.format(usr(request))) return super(OnlinePaymentView, self).post(request) def get_form(self, form_class): kwargs = self.get_form_kwargs() kwargs['user'] = self.get_customer() return form_class(**kwargs) def form_valid(self, form): amount = '%0.2f' % float(form.cleaned_data.get('amount')) payment = StripePayment(self.get_customer()) # Newly entered card if form.cleaned_data['cc_hash'] == 'new': pargs = { 'exp_month': form.cleaned_data['expdate'].month, 'exp_year': form.cleaned_data['expdate'].year, 'name': form.cleaned_data['name'], 'number': form.cleaned_data['acct'], 'cvc': form.cleaned_data['cvv2'], 'card': 'new', 'ip': get_client_ip(self.request), 'remember_cc': form.cleaned_data.get('remember_cc')} # Using stored card else: pargs = { 'card': form.cleaned_data['cc_hash'], 'remember_cc': … -
Django Pagination and Ajax Refresh
I got this simple Django model, class Person(models.Model): name = models.CharField(max_length=100) that I want to display using paginator showing only 1 item (name) per page. A left and right arrow when pressed will show the previous and next item in the paginator queryset using Ajax refreshing only the name. I'm using jQuery for Ajax. Question is when refreshing by Ajax how do you know the current page number and in this case the current page number corresponded to the currently shown name and so to display the next or previous item in the list using page_next and page_previous? -
ImportError: cannot import name. Cannot import class from the model.py
I got a full code from github and everything was OK, server worked without any problems. But then I tried to do some changes, like adding a new class in the model.py and trying to import it to the admin.py I got such an error: ImportError: cannot import name TechnicalExamination. Of course, I did migrations before this, using python manage.py makemigrations and python manage.py migrate. Here is my class in model.py: class TechnicalExamination(models.Model): class Meta: verbose_name_plural = 'Technical Examinations' technician = models.CharField(max_length=70) person = models.ForeignKey(Person, on_delete=models.CASCADE) start_date = models.DateField() end_date = models.DateField() def get_fields(self): pairs = [] for field in self._meta.fields: name = field.name try: pairs.append((name, getattr(self, "get_%s_display" % name)())) except AttributeError: pairs.append((name, getattr(self, name))) return pairs def __str__(self): return str(self.technical) Here is my admin.py: from __future__ import unicode_literals from django.contrib import admin from .models import Person, Car, InsuranceCompany, Policy, HealthExamination, TechnicalExamination admin.site.register(Person) admin.site.register(Car) admin.site.register(InsuranceCompany) admin.site.register(Policy) admin.site.register(HealthExamination) admin.site.register(TechnicalExamination) And here is my root: enter image description here -
Django urls.py mistaking two close urls
i'm adding forms to my app to modify my lobbys (my custom model). In urls.py, here is my urlpattern: urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^lobbys/$', views.LobbyListView.as_view(), name='lobbys'), url(r'^lobby/(?P<pk>[\w-]+)/$', views.LobbyDetailView.as_view(), name='lobby-detail'), url(r'^lobby/create/$', views.LobbyCreate.as_view(), name='lobby_create'), url(r'^lobby/(?P<pk>\d+)/update/$', views.LobbyUpdate.as_view(), name='lobby_update'), url(r'^lobby/(?P<pk>\d+)/delete/$', views.LobbyDelete.as_view(), name='lobby_delete'), ] The problem is the following: The third url is supposed to link to a single lobby template identifed with a UUID field as the primary key. Without the three last lines everything worked fine, but when I added my three urls for the forms, I'm getting the error Exception Value: ["'create' is not a valid UUID."] I understand urls.py is taking "create" as a primary key instead of considering it as an urls to an other view. How can I bypass this problem? Thank you very much. -
python manage.py makemigrations giving error on upgrading django
My project was working fine with django 1.11 This is my manage.py file #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myfoodsite.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise 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?" ) raise execute_from_command_line(sys.argv) until I upgraded my django to django 2.0.0 By using pip install python=2.0.0 , The output was as follows (myvenv) shubhendu@shubhendu-HP-Pavilion-g6-Notebook-PC:/home/foodballbear$ python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/foodballbear/myvenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/foodballbear/myvenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/home/foodballbear/myvenv/lib/python3.5/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/foodballbear/myvenv/lib/python3.5/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/foodballbear/myvenv/lib/python3.5/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in … -
When should celery be restarted?
I use celery to process asynchronous tasks. I understand that when I update the code within these tasks, or When i want to register a new task, then I must restart celery to see the reflection of these changes. Do I need to restart celery if I update some code, that is within the same file, but not a registered celery task? Are there other reasons on when I should restart celery during a deploy? thanks much! -
Django custom settings for app
I am currently developing an app for django that needs to have some custom settings that can be changed at runtime by admin users, and those settings have to be accessible to another separate system that uses the same database. On one hand, we could store those settings in a json file and have it accessible to both systems, as only the django system will actually make any changes to the settings. On the other hand, we could just store those settings as a lone entry in the database. The first choice seems quite cumbersome to deal with, and might result in some problems of multiple accesses, while the other would need a whole table in the database for a single entry. Is any of these ideas any good, or is there something I'm overlooking? -
How to fix Django's the view didn't return an HttpResponse object. It returned None instead?
I'm getting the following error: The view KSUvity.authentication.views.registerAttendee didn't return an HttpResponse object. It returned None instead I think it's because there is a logical error in my function. I have several if and else statements to check several conditions. This is the function in views.py: def registerAttendee(request,pk): act = Activity.objects.get(pk=pk) act.save() attendee, _ = Attendee.objects.get_or_create(student=request.user) volunteer = Volunteer.objects.filter(student=request.user) ActvsStudentAttending=Activity.objects.filter(attendee=attendee) ActvsStudentVolunteering=Activity.objects.filter(volunteer=volunteer) if act.volunteer.filter(student=request.user).exists(): messages.error(request, 'You\'re already registered as a volunteer for this activity!', extra_tags='alert') return redirect('home/#work') elif act.attendee.filter(student=request.user).exists(): messages.warning(request, 'You\'re already registered as an attendee for this activity!', extra_tags='alert') return redirect('home/#work') elif ActvsStudentAttending.exists(): for x in ActvsStudentAttending: if x.startDate.date() == act.startDate.date(): messages.error(request, 'You\'re already registered in the '+x.title+' activity that is held on the same day as '+act.title+'!', extra_tags='alert') return redirect('home/#work') elif ActvsStudentVolunteering.exists(): for x in ActvsStudentVolunteering: if x.startDate.date() == act.startDate.date(): messages.error(request, 'You\'re already registered in the '+x.title+' activity that is held on the same day as '+act.title+'!', extra_tags='alert') return redirect('home/#work') else: act.attendee.add(attendee) messages.success(request, 'You\'re successfully registered as an attendee!', extra_tags='alert') return redirect('home/#work') Is the error being raised because of the inner if inside the for loop? If yes, how should I fix it? I don't have an else for these cases so I don't know what I'm missing here. … -
pylint_django throwing exception
I am using Python v3.6, Django v2.0 and am having a problem with pylint_django. Firstly, if I run "pylint polls/" to run it on a folder it runs fine and show all the code issues for all the files in the folder. There are a bunch of linting errors that falsely show due to the django framework, and I have been informed that using the pylint_django plugin will get rid of these. I have installed the plugin using "pip install pylint_django", but when I try and run pylint using this plugin, it errors: C:\Users\Michael\Dev\DjangoProject>pylint --load-plugins pylint_django polls/ Traceback (most recent call last): File "c:\users\michael\appdata\local\programs\python\python36-32\Lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "c:\users\michael\appdata\local\programs\python\python36-32\Lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\Michael\Envs\Django\Scripts\pylint.exe\__main__.py", line 9, in <module> File "c:\users\michael\envs\django\lib\site-packages\pylint\__init__.py", line 16, in run_pylint Run(sys.argv[1:]) File "c:\users\michael\envs\django\lib\site-packages\pylint\lint.py", line 1268, in __init__ linter.load_plugin_modules(self._plugins) File "c:\users\michael\envs\django\lib\site-packages\pylint\lint.py", line 495, in load_plugin_modules module.register(self) File "c:\users\michael\envs\django\lib\site-packages\pylint_django\plugin.py", line 22, in register start = name_checker.config.const_rgx.pattern[:-2] AttributeError: 'NoneType' object has no attribute 'pattern' Anyone know what I might be doing wrong? Thanks -
python manage.py makemigrations gives attributeError: module 'django.views.debug' has no attribute 'TECHNICAL_500_TEMPLATE' error
I am setting my project as said in this project from github Steps I took.. Started the project by this command django-admin startproject theprojectname --extension py,yml,json --name Procfile,README.md,.env.example --template=https://github.com/vintasoftware/django-react-boilerplate/archive/boilerplate-release.zip then i installed the pip packages pip install -r requirements-to-freeze.txt Saved them pip freeze > requirements.txt Ran the npm update commands npm update --save npm update --save-dev cp goDiary/settings/local.py.example goDiary/settings/local.py cp .env.example .env and after that python manage.py makemigrations And I have almost same code except that I refactored the name After making pip install -r requirements.txt And the output when I am making the migrations is this Are my confs correct? (myvenv2) shubhendu@shubhendu-HP-Pavilion-g6-Notebook-PC:/home/goDiary$ python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 27, in <module> execute_from_command_line(sys.argv) File "/home/goDiary/myvenv2/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/goDiary/myvenv2/lib/python3.5/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/home/goDiary/myvenv2/lib/python3.5/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/goDiary/myvenv2/lib/python3.5/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/home/goDiary/myvenv2/lib/python3.5/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, … -
django Q objects ValueError: too many values to unpack (expected 2)
I am trying to build Q objects dynamically. This is my code: class StudentiRicerche(ListAPIView): serializer_class = StudentiLista def get_queryset(self): query_params = self.request.query_params q_objects = Q() for k, v in query_params.items(): param = '{0}__icontains={1}'.format(k, v) # k and v are dynamic values q_objects &= Q(param) queryset = Studenti.objects.filter(q_objects) # Here i get an error return queryset With this code I am getting a ValueError on the line where I use filter I have also tried to use a list of Q objects insted of Q objects directly in this way: class StudentiRicerche(ListAPIView): serializer_class = StudentiLista def get_queryset(self): query_params = self.request.query_params q_list = [] for k, v in query_params.items(): param = '{0}__icontains={1}'.format(k, v) q_list.append(Q(param)) # Q with 'and' condition queryset = Studenti.objects.filter(*q_list) # here I get an error also return queryset But here I am getting again the same error! Any idea?? -
Error during template rendering - Error with urls in Django [on hold]
Image of error Image of views Image of urls what can I do about it? -
How to pass extra formatting info through form into template?
I am working on a Django based form. I am using widget-tweaks. The template portion looks like: ... {% for field in profileForm.visible_fields %} <div class="form-group"> {{ field.label_tag }} {% if profileForm.is_bound %} {% if field.errors %} {% render_field field class="form-control is-invalid" %} {% for error in field.errors %} <div class="invalid-feedback"> {{ error }} </div> {% endfor %} {% else %} {% render_field field class="form-control is-valid" %} {% endif %} {% else %} {% render_field field class="form-control" %} {% endif %} {% if field.help_text %} <small class="form-text text-muted">{{ field.help_text }}</small> {% endif %} </div> {% endfor %} <button type="submit">Submit</button> </form> ... This is using Bootstrap. At the top of the outer loop a div is created. There is one of these form-group divs per field. I would like to set a Bootstrap column size on each div that needs one. In the form definition I tried creating a dict() to hold the custom widths, as in: class ProfileForm(forms.Form): bootstrap_div_width = dict() first_name = forms.CharField( max_length=64, label='First Name', required=True ) bootstrap_div_width['First Name'] = "col-xs-4" last_name = forms.CharField( max_length=64, label='Last Name', required=True ) bootstrap_div_width['First Name'] = "col-xs-4" ... I then tried to access the dict in the template as: {% for field … -
Django - forms - fields not mandatory to fill
I am creating a register form with django. This is my form code: class RegisterForm(forms.ModelForm): username = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Username'})) email = forms.EmailField(label="Email", widget=forms.EmailInput(attrs={'class':'form-control', 'placeholder':'Your email'})) email2 = forms.EmailField(label="Confirm Email", widget=forms.EmailInput(attrs={'class':'form-control', 'placeholder':'Confrim your email'})) password = forms.CharField(label="Password",widget=forms.PasswordInput(attrs={'class':'form-control','placeholder':'Password'})) password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control','placeholder':'Confirm password'}), label="Confirm Password") first_name = forms.CharField(label="First name", widget=forms.TextInput(attrs={'class':'form-control','placeholder':'First name'})) last_name = forms.CharField(label="Last name", widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Last name'})) home_address = forms.CharField(label="Home Address", widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Home Address'})) anonymous = forms.ChoiceField(label="Do you want to be anonymous?", widget=forms.CheckboxInput) class Meta: model = User fields = [#fields are going to be shown here 'username', 'password', 'password2', 'email', 'email2', 'first_name', 'last_name', 'user_type', 'home_address', 'photo_profile', 'anonymous', ] Last week, I added widget property for all the fields in the form, because I want to use bootstrap in my template. But now, a user need to fill in all the fields in the register form. However, my user template looks like this, it is not asking all the fields to be filled: class User(AbstractBaseUser): last_login = models.DateTimeField(default=timezone.now) username = models.CharField(max_length=255, unique=True) first_name = models.CharField(max_length=255, blank=True) last_name = models.CharField(max_length=255, blank=True) full_name = models.CharField(max_length=255, blank=True) email = models.EmailField(blank=True, unique=True) anonymous = models.BooleanField(default=False) home_address = models.CharField(max_length=255, blank=True) user_type = models.CharField(max_length=10, choices=USER_TYPE, default="patient") photo_profile = models.FileField(null=True, blank=True) is_staff = models.BooleanField(default=False) is_active = … -
Wagtail admin ,CheckboxSelectMultiple not saving data
@register_snippet class Numbers(models.Model): number = models.IntegerField() class State(models.Model): state = models.CharField(max_length=100) number = ParentalManyToManyField(Numbers) class HomeStateNumber(State): page = ParentalKey('home.HomePage', related_name='helpline') api_fields = ['state', 'number'] panels = [ FieldPanel('state'), FieldPanel('number',widget=forms.CheckboxSelectMultiple), ] class HomePage(Page): content_panels = [ FieldPanel('title'), ImageChooserPanel('cover_page'), InlinePanel('ticker', label="ticker"), InlinePanel('helpline', label="helpline"), ] I want to add one than more number in a state , wagtail shows correct order in admin , when you select number from multiple and save the page, data is not saved. It remains None (queryset) Is there any other way to do this ? I think i am doing wrong somewhere Please help -
How to detect window pop up created by user in python django?
Is there any way you can configure your python code to catch if the user is using pop up message such as alert("hello world")? I couldn't find any dedicated window alert method in python and really struggling to experiment my XSS game. This vulnerable example takes everything from the user. #views.py from django.shortcuts import render from django.http import HttpResponse def test(request): if request.method == 'GET': context = {'comments' : ''} else: context = {'comments' : request.POST['comments'] } response = render(request,'attack1.html',context) #disabling xss protection header response['X-XSS-Protection'] = 0 return response #html <!DOCTYPE html> <html> <head> </head> <body> <form action="" method="POST"> {% csrf_token %} Say something: <br> <textarea rows="3" cols="60" name='comments'>{{comments}}</textarea> <br> <input type="submit" value="comments"> </form> <br> Your comment: <b>{{comments|safe}}</b> </body> </html> -
Getting a A {% csrf_token %} was used in a template, but the context did not provide the value. Error in DJango
When I execute it from this point: Firswt I log in to the Application (the authentication system is created using the one from DJango) Eventually, I will land on a HTML template that runs the code below {% csrf_token %} The code above calls he following: @login_required def homepage(request): app_logonid = request.user.username return render(request, 'mainadmin/base.html', { 'firstname': app_logonid }, ) When following this sequence of steps, I get the following warning: A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext. Why am I getting this and how can I resolve it? TIA -
Django Rest Framework: Issue using OrderingFilter and django-filter simultaneously
I have a viewset which needs to have both flexible ordering by parameter and filtering by parameter for a custom list() over-ride. I am able to get ordering to work as well as filtering on various parameters via django-filter, but I cannot get them both to function simultaneously. Here is my simplified views.py code that works for ordering the results: class AssetViewSet(viewsets.GenericViewSet, AssetPaginationMixin,): queryset = Asset.objects.all() pagination_class = AssetPagination serializer_class = serializers.AssetSerializer filter_backends = (OrderingFilter, ) ordering_fields = ('id', 'session_id') filter_class = AssetFilterSet def list(self, request): assets = self.filter_queryset(self.get_queryset()) serializer = self.get_serializer(assets, many=True) return Response(serializer.data) And here is the code that works for filtering: class AssetViewSet(viewsets.GenericViewSet, AssetPaginationMixin,): queryset = Asset.objects.all() pagination_class = AssetPagination serializer_class = serializers.AssetSerializer filter_backends = (OrderingFilter, ) ordering_fields = ('id', 'session_id') filter_class = AssetFilterSet def list(self, request): assets = AssetFilterSet(request.query_params) serializer = self.get_serializer(assets, many=True) return Response(serializer.data) And finally, my filters.py code: class AssetFilterSet(django_filters.FilterSet): project_id = django_filters.NumberFilter() submitted = django_filters.TypedChoiceFilter(choices=BOOLEAN_CHOICES, coerce=strtobool) class Meta: model = Asset fields = ['project', 'submitted'] The only difference is the first line in list(). For some reason, it seems like the AssetFilterSet needs to be applied directly within list() in order to take effect and is otherwise bypassed if I use self.filter_queryset in … -
django testing passing request.user to foreignKey field, "Event.creator" must be a "User" instance
I am trying to write test for a view that creates an event model object. The event model contains a foreignKey field that references auth user as the creator of the model object. In the test I tried logging in the user which I assumed would set the request.user to the user logged in. The view that is being tested references request.user when creating the event the works fine when triggered normally through ajax but when I run the test I keep getting the error below. Also I have tried creating the user within the test function instead of referencing the user created at "class.setupTestData()", same error. error ValueError: Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x108ae9cc0>>": "Event.creator" must be a "User" instance. model class Event(models.Model): name = models.CharField(max_length=200) event_type = models.CharField(max_length=200, null=True) creator = models.ForeignKey(User, on_delete=models.CASCADE, null=True) attendees = models.ManyToManyField(User, related_name='attendees') start_date = models.DateField(null=True) start_time = models.TimeField(null=True) end_date = models.DateField(null=True) end_time = models.TimeField(null=True) location = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True) description = models.TextField() def __str__(self): return self.name view def createEvent(request): # dec vars event_title = str(request.POST['event-title']).title() event_type = str(request.POST['event-type']) event_location = str(request.POST['event-location']) event_description = str(request.POST['event-description']) event_start_date = str(request.POST['event-start-date']) event_start_time = str(request.POST['event-start-time']) event_end_date = str(request.POST['event-end-date']) event_end_time = str(request.POST['event-end-time']) creator = request.user … -
django 1.10, custom auth backend, is it ok to use just 1 custom backends?
I read it(Log in user using either email address or username in Django) and use this backend custom backend: from django.conf import settings from django.contrib.auth.models import User from django.contrib.auth.backends import ModelBackend class EmailOrUsernameModelBackend(ModelBackend): def authenticate(self, username=None, password=None): if '@' in username: kwargs = {'email': username} else: kwargs = {'username': username} try: user = User.objects.get(**kwargs) if user.check_password(password): return user except User.DoesNotExist: return None and settings.py: AUTHENTICATION_BACKENDS=[ 'logintest.custombackend.EmailOrUsernameModelBackend', ] Although it works well but I wonder whether I should use backend like this: AUTHENTICATION_BACKENDS=[ 'logintest.custombackend.EmailOrUsernameModelBackend', 'django.contrib.auth.backends.ModelBackend' ] Do I use it both backends? or It's ok for just one custom backend? -
Django can not import a local python package when runserver
I'm developing a simple django app, but I encounter an import issue. Here is my folder structure: django_intuitive_pagination/ ├── example │ ├── config │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── items │ │ ├── admin.py │ │ ├── apps.py │ │ ├── __init__.py │ │ ├── migrations/ │ │ ├── models.py │ │ ├── tests.py │ │ ├── urls.py │ │ └── views.py │ └── manage.py ├── intuitive_pagination │ ├── __init__.py │ ├── mixins.py │ ├── paginator.py │ ├── templates/ │ ├── templatetags/ │ └── views.py ├── runtests.py └── tests/ I add intuitive_pagination in example.config.settings.py as a django app. Add in example.items.views.py, I also import a class from intuitive_pagination.views.py. However, when I run python manage.py command, django complaint ImportError: No module named 'intuitive_pagination' I am sure the top level of the project did in python path >>> sys.path [..., '/home/light/Workspace/PycharmProjects/DjangoProjects/django_intuitive_pagination'] full stack: Traceback (most recent call last): File "/home/light/.virtualenvs/intuitive_pagination/lib/python3.5/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/home/light/.virtualenvs/intuitive_pagination/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/home/light/.virtualenvs/intuitive_pagination/lib/python3.5/site-packages/django/utils/autoreload.py", line 251, in raise_last_exception six.reraise(*_exception) File "/home/light/.virtualenvs/intuitive_pagination/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/light/.virtualenvs/intuitive_pagination/lib/python3.5/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/home/light/.virtualenvs/intuitive_pagination/lib/python3.5/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File …