Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django two types of users, profile permission for owner or second type
In my Django REST api, I have two types of users, provider and consumer, each is one-to-one linked with user object from django.contrib.auth. I want to make the consumer profiles available to all provider users to read but not to consumer users. The only consumer to read the profile is the owner, who should be able to edit it too. I want to make a permission class class ConsumerProfilePermission(BasePermission): ''' if provider -> read only if owner or admin -> full access if other consumer -> permission denied ''' so I won't have to check the permission in the view. How should I go about this? -
create_user() takes from 2 to 4 positional arguments but 6 were given
after i fill the registration form and click submit this error pops up "create_user() takes from 2 to 4 positional arguments but 6 were given" and also it doesn't use the validation inside the form in the template doesn't check if the username or email are already in the database or even checking if the the passwords are matching or not forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.forms.widgets import PasswordInput, TextInput from django.core.exceptions import ValidationError class CustomUserCreationForm(forms.Form): username = forms.CharField(widget=TextInput(attrs={'class':'validate','id': 'icon_prefix', 'type': 'text'}), min_length=4, max_length=150) email = forms.EmailField(widget=TextInput(attrs={'class':'validate','id': 'icon_prefix', 'type': 'text'})) first_name = forms.CharField(widget=TextInput(attrs={'class':'validate','id': 'icon_prefix', 'type': 'text'}), min_length=2, max_length=150) last_name = forms.CharField(widget=TextInput(attrs={'class':'validate','id': 'icon_prefix', 'type': 'text'}), min_length=2, max_length=150) password1 = forms.CharField(widget=PasswordInput(attrs={'class':'validate','id': 'icon_prefix', 'type': 'password'})) password2 = forms.CharField(widget=PasswordInput(attrs={'class':'validate','id': 'icon_prefix', 'type': 'password'})) def clean_username(self): username = self.cleaned_data['username'].lower() r = User.objects.filter(username=username) if r.count(): raise ValidationError("Username already exists") return username def clean_first_name(self): first_name = self.cleaned_data['first_name'] return first_name def clean_last_name(self): last_name = self.cleaned_data['last_name'] return last_name def clean_email(self): email = self.cleaned_data['email'].lower() r = User.objects.filter(email=email) if r.count(): raise ValidationError("Email already exists") return email def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise ValidationError("Password don't match") return password2 def save(self, commit=True): user = … -
Django channels - server initiated message
In the case of a chat (tutorial) the communication between users is always initiated by users. I think that writing a game is slightly different because a game is a statefull entity that should sometimes react regardless of users' actions. For instance: handling turn timeout (a player should react withing 30 seconds and if he doesn't then the game should change its state and send some message to players. So my question is: Where should the game object be stored (to be available to all joining players)? How to manage this kind of timeout: setup timer, cancel it if the player reacted? It seems that games should be available in every instance of consumer and that game should "live its own life". -
Django view templates filter database
Whats is the best approach to filter context. I want to view on my index page last three objects from Roslina and related to them all Images with the same nazwa_polska(foreign_key) my model.py **class Roslina(models.Model): id_rosliny = models.AutoField(primary_key=True) nazwa_polska = models.CharField(max_length=256) nazwa_lacinska = models.CharField(max_length=256) opis = models.TextField() data = models.DateField() def __str__(self): return self.nazwa_polska class Images(models.Model): nazwa_polska = models.ForeignKey(Roslina, related_name='image', on_delete=models.CASCADE) image = models.ImageField(max_length=255, upload_to=generate_filename); def __str__(self): return self.nazwa_polska.nazwa_polska** views.py from django.shortcuts import render from django.views.generic import ListView,TemplateView from . import models # Create your views here. class IndexView(TemplateView): template_name='index.html' def get_context_data(self, **kwargs): context = super(IndexView, self).get_context_data(**kwargs) context['zdjecia'] = models.Images.objects.all() context['rosliny'] = models.Roslina.objects.all() return context class WyborAtlasu(TemplateView): template_name='basic_app/wyborAtlasu.html' -
Geodjango on Heroku cannot find libjasper.so.1
I'm using this buildpack for geo-django https://github.com/TrailStash/heroku-geo-buildpack/commit/5ae45e57353aab6a9fb2f0443e9ea0974d8b29ba which is supposed to be a fix for a heroku-16 + geodjango issue. Still I am returned an error saying OSError: libjasper.so.1: cannot open shared object file: No such file or directory libjasper does not exist. The full traceback: /app/.heroku/python/lib/python3.6/site-packages/daphne/server.py:12: UserWarning: Something has already installed a non-asyncio Twisted reactor. Attempting to uninstall it; you can fix this warning by importing daphne.server early in your codebase or finding the package that imports Twisted and importing it later on. UserWarning, Traceback (most recent call last): File "manage.py", line 29, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 338, in execute django.setup() File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/app/.heroku/python/lib/python3.6/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line … -
django User table don't have user show me email field
how to put if condition no user in Usertable then show me email id.other then don't show the email_field. my goal sending email invitation in django.any one can help me thanks in advance -
django. Passing id from one template to second template
I need to pass id from one template to another template. In template i am iterating over one model {% for project in all_projects %} <h3>{{ project.name }}</h3> <a href="{% url 'docs:platforms' %}?project={{ project.id }}"></a> {% endfor %} This going to one template where my url looks like url(r'^$', views.ProjectsListView.as_view(), name='index'), url(r'^platforms/$', views.PlatformsIndexView.as_view(), name='platforms'), url(r'^platforms/nodes/$', views.PlatformsNodesListView.as_view(), name='platforms_list'), Browser url that i have is http://127.0.0.1:8000/platforms/?project=1 that's ok good. But from second template i need to send third template another parametrs and filters. So how do i can get id of project? I can not send now project id to third template because i am not iterating over it. How to remember id of project? views.py class ProjectsListView(ListView): template_name = 'project/projects.html' model = Project context_object_name = 'all_projects' class PlatformsIndexView(TemplateView): template_name = 'project/platforms.html' class PlatformsNodesListView(ListView): template_name = 'project/general.html' model = Platform context_object_name = 'all_platforms' def get_queryset(self): queryset = super().get_queryset() type_filter = self.request.GET.get('type') project_filter = self.request.GET.get('project') if type_filter in [Platform.BACKEND, Platform.ANDROID, Platform.IOS, Platform.FRONTEND]: queryset = queryset.filter(type=type_filter) if project_filter: queryset = queryset.filter(project__id__exact=project_filter) else: raise Http404 return queryset Please explain me. Thank you in advance -
User has no profile when trying to authenticate against LDAP
I am trying to authenticate an LDAP-user but since I created a model extension it just would not work anymore. Here is where the problem is: C:\Python27\lib\site-packages\django_auth_ldap\backend.py in authenticate user = ldap_user.authenticate(password) C:\Python27\lib\site-packages\django_auth_ldap\backend.py in authenticate self._get_or_create_user() C:\Python27\lib\site-packages\django_auth_ldap\backend.py in _get_or_create_user self._user.save() models.py in save_user_profile > @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User) salutation = models.CharField(max_length=30, default='') title = models.CharField(max_length=30, default='') @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() Do I have to change the source code in C:\Python27\lib\site-packages\django_auth_ldap\backend.py or is it even possible to authenticate against LDAP with an extended model? If you have any idea, do not hesitate to post it. -
Handling extra attributes and logging - when redirecting to external URI from Django app
I recently added an HTML-based share on whatsapp button to my mobile web application built via the Django framework: <a rel="nofollow" target="_blank" href="whatsapp://send?text=https://example.com" data-link="whatsapp://send?text=https://example.com" data-action="share/whatsapp/share"> <button><img src="whatsapp.svg">Share</span></button> </a> Now I'd like to track all the clicks on this share button. Being a server-side developer, an obvious way is to POST to a view, log the click, and then redirect from there. Specifically, in the template: <form method="POST" action="{% url 'whatsapp_share' %}"> {% csrf_token %} <button><img src="whatsapp.svg">Share</span></button> </form> In the view: def whatsapp_share(request): if request.method == 'POST': clicker_id = request.user.id # log the click and clicker_id, preferably asynchronously return redirect("whatsapp://send?text=https://example.com") This looks simple enough. But look at the <a> tag closely in the original snippet at the top. It contains data-link and data-action attributes as well. How do I include these data-* attributes in the redirect as well? Secondly, I feel one drawback of using the aforementioned view-based approach is a server roundtrip. Ergo, in the pure HTML case, the client took care of everything, however, with the Django view involved, the server has to be invoked first (adding latency). Is there an alternative way to do this such that the client doesn't have to wait for the click to be … -
Django admin list display - prefetch against custom names
I have created some custom names for my list display but they are generating over 500 queries in my admin list display. I have added a select and prefetch QuerySet (which works on the edit form) and looks to have cut some of the list display down. However I think the get_xxx fields need to be prefetched too? but am not sure on how to do this? class DeviceCircuitSubnetsAdmin(admin.ModelAdmin): search_fields = ['device__hostname','circuit__ref_no','subnet__subnet_type__subnet_type','subnet__subnet',] list_display = ('get_device','get_circuit','get_subnet','get_subnet_type') def queryset(self, request): return super(DeviceCircuitSubnetsAdmin, self).queryset(request) \ .select_related('circuit') \ .select_related('device') \ .select_related('subnet') \ .prefetch_related('device__site_') \ .prefetch_related('circuit__circuit_type') \ .prefetch_related('circuit__provider') \ .prefetch_related('subnet__subnet_type') \ def get_device(self, obj): return obj.device.site get_device.admin_order_field = 'device' #Allows column order sorting get_device.short_description = 'Device' #Renames column head def get_circuit(self, obj): try: return obj.circuit.ref_no except: return '' get_circuit.admin_order_field = 'circuit__ref_no' #Allows column order sorting get_circuit.short_description = 'Ref No' #Renames column head def get_subnet(self, obj): return obj.subnet.subnet get_subnet.admin_order_field = 'subnet__subnet' #Allows column order sorting get_subnet.short_description = 'Subnet' #Renames column head def get_subnet_type(self, obj): return obj.subnet.subnet_type get_subnet_type.admin_order_field = 'subnet__subnet_type__subnet_type' #Allows column order sorting get_subnet_type.short_description = 'Subnet Type' #Renames column head -
where to write this part of the code (nephila/django-meta)
Good afternoon, I'm installing into the project https://github.com/nephila/django-meta, I can not figure out where to write this part of the code (highlighted with asterisks and directed arrow, see below): Usage Configure django-meta according to documentation Add meta information to your model: from django.db import models from meta.models import ModelMeta class MyModel(ModelMeta, models.Model): name = models.CharField(max_length=20) abstract = models.TextField() image = models.ImageField() ... _metadata = { 'title': 'name', 'description': 'abstract', 'image': 'get_meta_image', ... } def get_meta_image(self): if self.image: return self.image.url need help right here**************************************************************===> Push metadata in the context using as_meta method: class MyView(DetailView): def get_context_data(self, **kwargs): context = super(MyView, self).get_context_data(self, **kwargs) context['meta'] = self.get_object().as_meta(self.request) return context For Function Based View can just use as_meta() method for pass “meta” context variable: def post(request, id): template = 'single_post.html' post = Post.objects.get(pk=id) context = {} context['post'] = post context['meta'] = post.as_meta() return render(request, template, context) Include meta/meta.html template in your templates: {% load meta %} <html> <head {% meta_namespaces %}> {% include "meta/meta.html" %} </head> <body> </body> </html> -
Matching query does not exist when trying to edit specific object in Django
I have created an application in which users can make bookings which are stored in booking objects. In each booking there is an automatically generated UUID randomly generated code. I am in the process of creating an edit view and in order to do this I need to filter the view per unique_id. When I do this I get the error "Booking matching query does not exist". Please find code below. views.py def addstudents(request, unique_id=None): booking = Booking.objects.get(unique_id=unique_id) if (request.method == 'POST'): form = BookingForm(data=request.POST, instance=booking) if form.is_valid(): form.save(commit=True) return redirect('teachers:upcoming') else: booking_dict = model_to_dict(booking) form = BookingForm(booking_dict) return render(request, 'teachers:studentadd') models.py class Booking(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) unique_id = models.UUIDField(unique=True, default=uuid.uuid4, editable=False) coursename = models.CharField(max_length=200) daterequired = models.DateTimeField(default=datetime.now(timezone.utc)) students = models.CharField(max_length=200) length = models.IntegerField() matches = models.ManyToManyField(Student, related_name='matches') slug = models.SlugField(max_length=40, blank=True) def save(self, *args, **kwargs): if not self.pk: self.slug = slugify(self.coursename) super(Booking, self).save(*args, **kwargs) def __str__(self): return str(self.user.username) forms.py class BookingForm(forms.ModelForm): class Meta: model = Booking exclude = ['user', ] widgets = { 'students': forms.TextInput(attrs={'placeholder': 'Number of Students'}), 'length': forms.TextInput( attrs={'placeholder': 'Time needed in hours'}), 'coursename': forms.TextInput( attrs={'placeholder': 'Name of your course for students'}), } labels = { 'daterequired': 'What date and time do you require?', 'coursename': … -
Display currently set image in Django ImageField instead of URL
I have a Django ModelForm with an ImageField. When the user edits the model the Image Field displays: Is there a way to use the URL presented beside "Currently" to display/render the set image instead of the actual URL. -
How to filter taggit tags with related items fields using the Django ORM?
I have a model where I use the django-taggit TaggableManager: from django.db import models from model_utils import Choices from taggit_autosuggest.managers import TaggableManager LANGUAGE_CHOICES = Choices( ('de', 'Allemand - Deutch'), ('en', 'Anglais - English'), ('es', 'Espagnol - Español'), ('fr', 'Français'), ('it', 'Italien - Italiano'), ('jp', 'Japonais - 日本語'), ('ko', 'Coréen - 한국어'), ('pt', 'Portugais - Português'), ('th', 'Thaï - ไทย'), ('vi', 'Vietnamien - Tiếng Việt'), ('zh', 'Chinois - 中文'), ) class Recipe(models.Model): language = language = models.CharField( max_length=5, choices=LANGUAGE_CHOICES, default=LANGUAGE_CHOICES.en ) tags = tags = TaggableManager( help_text="Use tab to add a new term.", blank=True ) How can I grab all the recipes tags with their related recipe language? -
In PyCharm Django version
How can I use Django 1.11 as default version in pycharm ? Letting you know that I'm using macOS and default Django version is 2.0.3 ! -
Uploading file using axios
Hi I'm trying to upload a file to server and I'm having difficulty sending the file. I'm using Django at the backend and I've already set up a put endpoint allowing users to send files and I confirmed it works as intended using postman. However, I'm having trouble uploading on the frontend. So this is how my code looks on the frontend end. selectFileManually.addEventListener('change', function(event){ event.stopPropagation(); event.preventDefault(); axios.put('http://127.0.0.1:8000/api/v1/fileupload/', { file: this.files[0] }).then(resp => console.log(resp.data)).catch(err => console.log(err.response.data)) } } }) Here selectFileManually is an input[type='file']. However, when I send this request the server comes back with the following error: "Missing filename. Request should include a Content-Disposition header with a filename parameter and when I look at the payload it's complete empty: `{file: {}}' even though you can clearly see I provided a file to send. This is how my code looks at the backend # views.py from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.parsers import FileUploadParser, MultiPartParser import os # Create your views here. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) class FileUploadView(APIView): parser_classes = (MultiPartParser, FileUploadParser, ) def put(self, request, format=None): print(request.data) with open(os.path.join(BASE_DIR, 'api/media', request.data['file'].name), 'wb') as f: for chunk in request.data['file'].chunks(): f.write(chunk) return Response(status=204) #urls.py from … -
empty queryset when overriding `BaseFilterView` and `ListView` ` django-filter==2.0.0.dev1`
the problem is in how BaseFilterView changed: django-filter==1.0.2 class BaseFilterView(FilterMixin, MultipleObjectMixin, View): def get(self, request, *args, **kwargs): filterset_class = self.get_filterset_class() self.filterset = self.get_filterset(filterset_class) self.object_list = self.filterset.qs context = self.get_context_data(filter=self.filterset, object_list=self.object_list) return self.render_to_response(context) django-filter==2.0.0.dev1 class BaseFilterView(FilterMixin, MultipleObjectMixin, View): def get(self, request, *args, **kwargs): filterset_class = self.get_filterset_class() self.filterset = self.get_filterset(filterset_class) if self.filterset.is_valid() or not self.get_strict(): self.object_list = self.filterset.qs else: self.object_list = self.filterset.queryset.none() context = self.get_context_data(filter=self.filterset, object_list=self.object_list) return self.render_to_response(context) in my CustomLV(BaseFilterView, ListView) I am facing problem of empty queryset when not specifying any filter. Providin an empty one like ?city= or whatever makes it works. I see strict is about how filter should behave when smth goes with it wrong, but still not getting it right. docs https://django-filter.readthedocs.io/en/stable/index.html -
HttpRequestResponse reloading to same page in django 2.0.3
1.I am trying to develop a simple blog using django 2.0.3. in the view.py when i was trying to redirect to page from edit.html or create.html it is redirecting to it self when i was giving the url manually it is still loading to same page i don't know why. views.py from django.shortcuts import render,get_object_or_404,redirect from django.http import HttpResponseRedirect,HttpResponse from posts.models import Post from posts.forms import PostForm from django.contrib import messages from django.urls import reverse def post_create(request): form = PostForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) instance.save() HttpResponseRedirect(instance.get_absolute_url()) context = {"title":"Create Blog","form":form} return render(request,"create.html",context) def post_detail(request,id): instance = get_object_or_404(Post,id=id) context = { "title": instance.title, "instance":instance } return render(request,"detail.html",context) def post_update(request,id): instance = get_object_or_404(Post,id=id) form = PostForm(request.POST or None,instance=instance) if form.is_valid(): instance = form.save(commit=False) instance.save() messages.success(request,"Saved") HttpResponseRedirect(instance.get_absolute_url()) context = { "title": "Edit Blog", "instance":instance, "form":form } return render(request,"edit.html",context) def post_delete(request): context = {"title":"Delete"} return HttpResponse("<h1>delete</h1>") def post_list(request): queryset = Post.objects.all().order_by('-timestamp') context = { "title":"List", "object_list":queryset } return render(request,"index.html",context) 2.this my urls.py urls.py from django.contrib import admin from django.urls import path,include,re_path from . import views app_name = 'posts' urlpatterns = [ path('admin/', admin.site.urls), re_path(r'^$',views.post_list,name="list"), re_path(r'^create/$',views.post_create,name="create"), re_path(r'^(?P<id>\d+)/$',views.post_detail,name="detail"), re_path(r'^(?P<id>\d+)/edit/$',views.post_update,name="update"), re_path(r'^delete$',views.post_delete), ] 3.this my models.py model.py from django.db import models from django.urls import reverse … -
I want to edit Course Fields and Step Fields together on Page Please How can I do it? in Django
Here is models.py https://dpaste.de/LkuF I have Course and their step fields. How can I edit together in template Course and their step need to edit please? -
Django customise Default Group model
I m fairly new to Django and I want customise Django's default Group model with my own requirements, Default django's Group model look like this: class Group(models.Model): name = models.CharField(_('name'), max_length=80, unique=True) permissions = models.ManyToManyField( Permission, verbose_name=_('permissions'), blank=True, ) I want to change add a new field and make name field and that new field as one composite primary key. Is there anyway this could be done? Any suggestions would be appreciated. Thanks -
django. Get only current day. Only day without time
I want to get current day for now. Only day. For example today is 20-March i need use it in my queryset query = self.filter(Q(busyrooms__end_date__day=datetime.now().date()), Q(reservedrooms__end_date__day=datetime.now().date())) Tried to use datetime.now().date() but i got error TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.date' -
Cannot load font in Django for AMP page
On an AMP page I want to add a reference to my font in the styles tag. Can we use static to do so? @font-face { font-family: 'Font Awesome 5 Brands'; font-style: normal; font-weight: normal; src: url("{% static '/webfonts/fa-brands-400.eot' %}"); src: url("{% static '/webfonts/fa-brands-400.eot?#iefix' %}") format("embedded-opentype"), url("{% static '/webfonts/fa-brands-400.woff2' %}") format("woff2"), url("{% static '/webfonts/fa-brands-400.woff' %}") format("woff"), url("{% static '/webfonts/fa-brands-400.ttf' %}") format("truetype"), url("{% static '/webfonts/fa-brands-400.svg#fontawesome' %}") format("svg"); } In my body section this works fine for me. <amp-img src="{% static '\located_in\picture.jpg' %}" width="16" height="9" layout="responsive" > </amp-img> I am getting the following error: Error during template rendering In template C:\users\frank\desktop\test_env\src\templates\fontawesome\fontawesome-all.css, error at line 2702 Invalid block tag on line 2702: 'static'. Did you forget to register or load this tag? -
Creating a custom primary_key field
I originally had the standard default id field for my Django model. However I want to switch to a random 10-15 alphanumerical string. Here's the string if you're curious (it works): def random_string(chars=string.ascii_letters + string.digits): size = random.randrange(10, 15) return str(''.join(random.choice(chars) for _ in range(size))) And here's my model. I simply added in the field and did migrate & makemigrations: class Post(models.Model): id = models.CharField(max_length=18, primary_key=True, default=random_string()) user = models.ForeignKey(User, blank=True, null=True) content = models.TextField(null=True, blank=True) Expectedly it wan't a smooth changeover - when I make a Post, I get the following non_field_error: Non Errors: <bound method BaseForm.non_field_errors of <PostForm bound=False, valid=False, fields=(content;id;user)>> [20/Mar/2018 09:38:37] "POST /post/ HTTP/1.1" 200 11482 views def post(request): if request.user.is_authenticated(): form_post = PostForm(request.POST or None, request.FILES or None) if form_post.is_valid(): instance = form_post.save(commit=False) instance.user = request.user instance.save() return HttpResponseRedirect('/') else: form_post = PostForm() print('Errors:', form_post.errors) #prints nothing print('Non Errors:', form_post.non_field_errors) context = { 'form_post': form_post, } return render(request, 'post/post.html', context) else: return HttpResponseRedirect("/accounts/signup/") Can anyone tell me why I get that non_field_error? Here's the accompanying form to the model: class PostForm(forms.ModelForm): class Meta: model = Post fields = [ 'content', 'id', 'user' ] -
extended template working but main template is not working django
views.py def base(request): return render(request,"base.html",{'':''}) def index(request): return render(request,"index.html",{'':''}) base.html <html> <head>ppppppppp</head> <body> <h1>this is base template</h1> </body> </html> index.html {% extends "base.html" %} {% block content %} <body> <h1> Welcome to my app </h1> </body>` {% endblock content %} Here the issue is django is not at all recognising index.html only displaying extended template. -
Check box in django redux form. I am using django-redux
I have added two check box in django redux registration form. Now, I can check both the option, But I want user to select any one at a time. How to achieve that? Below is my code models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class UserSelection(models.Model): employer = models.BooleanField() candidate = models.BooleanField() user = models.OneToOneField(User) forms.py from django import forms from registration.forms import RegistrationFormUniqueEmail class MyRegForm(RegistrationFormUniqueEmail): employer = forms.BooleanField() candidate = forms.BooleanField() regbackend.py from registration.backends.default.views import RegistrationView from .forms import MyRegForm from .models import UserSelection class MyRegistrationView(RegistrationView): form_class = MyRegForm def register(self, form_class): new_user = super(MyRegistrationView, self).register(form_class) p = form_class.cleaned_data['employer'] q = form_class.cleaned_data['candidate'] new_profile = UserSelection.objects.create(user=new_user, employer=p, candidate=q) new_profile.save() return new_user