Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not a valid choice error when adding custom values to a ModelChoiceField Django
I am using Django 1.9, I am passing a queryset through to a form so I can display the data in a ModelChoiceField, within the ModelChoiceField I have added two custom values. Although when I submit the form I am getting the error Select a valid choice. That choice is not one of the available choices. views.py def add_basic_album_details(request): users = User.object.all() if request.method=="POST": form = AddBasicAlbumDetails(users,request.POST) if form.is_valid(): name = form.cleaned_data['name'] owner = form.cleaned_data['owner'] album = Album( name=name, owner=owner, ) album.save() return redirect('album_detail',album.id) else: form = AddBasicAlbumDetails(users=users) return render(request,'add_basic_album_details.html',{ 'form':form }) forms.py class AddBasicAlbumDetails(forms.Form): def __init__(self,users, *args, **kwargs): super(AddBasicAlbumDetails, self).__init__(*args, **kwargs) self.fields['user']= ModelChoiceField( queryset=users, label = 'Owner', widget = Select(attrs={ 'class': ' form-control selectpicker', 'data-live-search':'true', }), empty_label = "Not known", required=True ) users = self.fields['user'] users.choices = list(users.choices) + [(0, 'Not applicable'),(1,'Enter user details')] self.fields['name'] = forms.CharField( max_length=100, required=True, label='Name', widget=TextInput(attrs={'class' : ' form-control span12 small-margin-top small-margin-bottom'}), ) -
Basic Django Authentication Error
I've setup a basic authentication, but upon login function which doesnt give any error, if I return something then I get an error stating - {'session_key': ['Session with this Session key already exists.']} This is the code: def header_auth(request): auth_header = request.META['HTTP_AUTHORIZATION'] encoded_credentials = auth_header.split(' ')[1] # Removes "Basic " to isolate credentials decoded_credentials = base64.b64decode(encoded_credentials).decode("utf-8").split(':') return decoded_credentials[0], decoded_credentials[1] def login_view(request): username, password = header_auth(request) user = authenticate(request, username=username, password=password) if user is not None: try: login(request, user) print('after login') except Exception as e: print('login error', e) return HttpResponse('Authorized', status=200) else: return HttpResponse('Not Authorized', status=403) def logout_view(request): logout(request) class FyndUser(AbstractUser): company_id = models.IntegerField(unique=True) If I sent the user object instead of Response then I receive the error that the user object has not attribute get. -
Child Portal creation in Django CMS
How can we create child portals in django-cms like we do in DNN, & how can we manage the access permissions of these child portals? -
What is the best practices of Django REST framework JWT in microservice
I have two separated services: one(A) for authentication, one(B) for content in short. When B receive a request with token, it asks A for authentication. If A says Ok. The request is authenticated. The case is that B don't have User model to get User object from payload that decoded from token. So I decided to user UserStruct to construct User object field by field and assign to request.user in B for further use. Is there any better ways to do that? Any help is really appreciated -
django template and version
I googled the latest version of django and it is 2.0.6 on the official django documentation. But the versions that are given on the official page are just 2.0, 2.1, 1.9 etc. So I was just wondering if the documentation for 2.0 is for all version like 2.0.5, 2.0.6, 2.0.7 etc. Because there is no documentation for version 2.0.6. But again the version 2.0 is different and it is installable with pip. I am totally confused with this. Earlier I was using django 2.0.6 and I had a problem with the template. I first started my project with name web and then made a app named music. Inside that I made a template directory and inside that another music folder and placed my index.html file inside that. so overall the path like this web/music/template/music/index.html. Now I was using render from django.shortcuts. I referenced the index.html file as music/index.html in the view.py file in music directory. But it is unable to find the file and it is just showing error. Pls help me solve this problem. I thought it could be a version problem. -
How to optimize a sort based on "latest" related model
So say we have two models class Product(models.Model): """ A model representing a product in a website. Has new datapoints referencing this as a foreign key daily """ name = models.CharField(null=False, max_length=1024, default="To be Scraped") url = models.URLField(null=False, blank=False, max_length=10000) class DataPoint(models.Model): """ A model representing a datapoint in a Product's timeline. A new one is created for every product daily """ product = models.ForeignKey(Product, null=False) price = models.FloatField(null=False, default=0.0) inventory_left = models.BigIntegerField(null=False, default=0) inventory_sold = models.BigIntegerField(null=False, default=0) date_created = models.DateField(auto_now_add=True) def __unicode__(self): return "%s - %s" % (self.product.name, self.inventory_sold) The goal is to sort a QuerySet of products based on the inventory_sold value of the latest datapoint attached to the product. Here's what I have so far: products = Product.objects.all() datapoints = DataPoint.objects.filter(product__in=products) datapoints = list(datapoints.values("product__id", "inventory_sold", "date_created")) products_d = {} # Loop over the datapoints values array for i in datapoints: # If a datapoint for the product doesn't exist in the products_d, add the datapoint if str(i["product__id"]) not in products_d.keys(): products_d[str(i["product__id"])] = {"inventory_sold": i["inventory_sold"], "date_created": i["date_created"]} # Otherwise, if the current datapoint was created after the existing datapoint, overwrite the datapoint in products_d else: if products_d[str(i["product__id"])]["date_created"] < i["date_created"]: products_d[str(i["product__id"])] = {"inventory_sold": i["inventory_sold"], "date_created": i["date_created"]} # Sort the … -
datepicker is not working in django?
#script added in base.html <script> $(function(){ $('.datepicker').datepicker({ format: 'mm/dd/yyyy', // startDate: '-3d' startDate: "2013-02-14 10:00", changeMonth: true, changeYear: true, yearRange: "1900:2012", uiLibrary: 'bootstrap4', autoclose : true, }); }) </script> -------------------------------- #My class "MessLeaveForm" in forms.py class MessLeaveForm(forms.ModelForm): departure_date = forms.DateField() arrival_date = forms.DateField(widget=forms.DateInput(format='%d/%m/%Y')) departure_time = forms.TimeField(widget=forms.TimeInput(format='%H:%M')) arrival_time = forms.TimeField(widget=forms.TimeInput(format='%H:%M')) verification = forms.ChoiceField(choices=BOOL_VALUES,initial="Pending",widget=forms.HiddenInput(),required=False) approval = forms.ChoiceField(choices=BOOL_VALUES,initial="Pending",widget=forms.HiddenInput(),required=False) status = forms.ChoiceField(choices=BOOL_VALUES,initial="Pending",widget=forms.HiddenInput(),required=False) hostel_suscribed = forms.ChoiceField(choices = HOSTEL_CHOICES,required = True) mess_manager_doc = forms.FileField(required=False) faculty_doc = forms.FileField(required=False) class Meta: model = MessLeaveModel fields = ('idNo','hostel_suscribed','departure_date','departure_time','arrival_date','arrival_time','mess_manager_doc','faculty_doc','verification','approval','status') widgets = { 'departure_date': forms.DateInput(attrs={'class':'datepicker'}), } ---------------------------------------- #my model "MessLeaveModel" in models.py class MessLeaveModel(models.Model): # user = models.ForeignKey(OccupantDetails,null=True,on_delete=models.CASCADE) idNo = models.ForeignKey(OccupantDetails,on_delete = models.CASCADE) username = models.CharField(max_length=255, null=False,blank=False,default="") hostel_suscribed = models.CharField(max_length=255,choices = HOSTEL_CHOICES,null=True) departure_date = models.DateField() arrival_date = models.DateField() departure_time = models.TimeField(null = True,blank = True) arrival_time = models.TimeField(null=True,blank=True) faculty_doc = models.FileField(upload_to='documents/',null=True,blank=True) mess_manager_doc = models.FileField(upload_to='documents/',null=True,blank=True) verification = models.CharField(max_length=255,choices=BOOL_VALUES,default="Pending") approval = models.CharField(max_length=255,choices=BOOL_VALUES,default="Pending") status = models.CharField(max_length=255,choices=BOOL_VALUES,default="Pending") comment = models.CharField(max_length=255,blank=True,null=True,default="") def __str__(self): return '%s_%s_%s' %(self.idNo,self.departure_date,self.arrival_date) ------------------------------------------------- #my django html where i am taking departure date <label class="control-label col-sm-2"> Departure Date</label> <div class="col-sm-10">{{form.departure_date}} I am trying to add datepicker in "departure_date" field of "MessLeaveModel" Model. i have added relevent script in base.html and added this class through widget in meta class of MessLeaveForm. I have extended … -
django-allauth with custom user model throws error
I used django restframework and allauth for simple registration. Also I customized User model that I wanted. [settings.py] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', # Cutom User model 'rest_framework', 'rest_auth', 'django.contrib.sites', 'allauth', 'allauth.account', 'rest_auth.registration', ] # Configure the JWTs to expire after 1 hour, and allow users to refresh near-expiration tokens JWT_AUTH = { 'JWT_EXPIRATION_DELTA': datetime.timedelta(hours=1), 'JWT_ALLOW_REFRESH': True, } # Make JWT Auth the default authentication mechanism for Django REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ), } # Enables django-rest-auth to use JWT tokens instead of regular tokens. REST_USE_JWT = True AUTH_USER_MODEL = 'users.user' SITE_ID = 1 ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_AUTHENTICATION_METHOD = 'email' [/users/models.py] from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser, PermissionsMixin ) from django.db import models from django.utils import timezone from django.utils.translation import ugettext_lazy as _ class UserManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError(_('Users must have an email address')) user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=email, password=password, username=username, ) user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( verbose_name=_('Email address'), max_length=255, unique=True, ) username = models.CharField( verbose_name=_('username'), max_length=30, unique=True ) is_active = models.BooleanField( verbose_name=_('Is active'), default=True ) … -
google cloud app deploy (python) : No module named
I want to deploy my Django app to google cloud. I followed the tutorial given by this page. When I deploy to the cloud(gcloud app deploy), I got this error. I tried installing the 'channels' library by following.. installed it in python2(pip install channels) installed it in python3(pip3 install channels) installed it in python2(in activated virtual environment) installed it in python3(in activated virtual environment) my app.yaml in project folder is.. -
Django update and save asynchronous?
We have a model that only allows one instance of it to be active : class MyModel(models.Model): active = models.BooleanField() def save(self, *args, **kwargs): if self.active: MyModel.objects.update(active=False) super(MyModel, self).save(*args, **kwargs) This appears to work, passes simple tests to ensure only one instance is ever active. However, it was recently used on our production server and appears to be behaving as if the update call is executing after the save and so all instances are ending up with active=False - this doesn't happen all the time. Could it be that the update is running after the save somehow? Or do I need to look elsewhere for the issue? -
How to add CSS and JS files in core Python without using Flask & Django?
I'm noob in python, I'm just learning python now.I tried a lot for adding CSS & JS files in my basic form without using FLASK & Django. Can anyone please help me out of this situation that would be appreciable. Thank you so much and sorry for my English. -
Improving the loading performance of foreignkey fields with thousands of options
I have a similar situation as this post in which I encounter a slow page loading as I have thousands of entries in a foreignkey field. At modelform, is there a way to improve the page loading while keeping the dropdown function? I have used django-select2 library to efficiently find the chosen item in the dropdown, thus want to keep this function. -
CartItem matching query does not exist
I am struggling to add item to the carts and session. When i try to post the item like following way { "product": 3, "quantity": 5 } I get the error "CartItem matching query does not exist." From the view, what I have done is first deserialized the object and then checked if the serializer is valid or not if its valid then I have supplied the product and quantity to add in the cart cart.add(product_instance, quantity) Here cart is an object of Basket(Cart name resembles with the model name so i gave the name Basket). The code for Basket class is CART_ID = 'cart-id' class Basket(object): def __init__(self, request): """ Initialize the cart """ self.session = request.session self.request = request.user # get the current session from request.session.get(CART_ID) cart = self.session.get(CART_ID) if not cart: # cart is not present in the session # save an empty cart in the session # but we expect our cart dictionary to use product ids as keys # and a dictionary with quantity and price as value for each key # by that we can gurantee same product is not added twice cart = self.session[CART_ID] = {} else: try: cart = CartItem.objects.get(id=cart) except CartItem.DoesNotExist: … -
Invalid filter add_class using django-widget-tweaks
I am creating form view using django-widget-tweaks following this tutorial. When I tried to implement add_class filter, I got following error. Invalid filter: 'add_class' Does anyone know how to solve this error? html page {% extends "base.html" %} (% load widget_tweaks %} {% block content %} <form method="post" enctype="multipart/form-data"> <h4 style="margin-top: 0">Project Upload</h4> {% csrf_token %} {% for hidden in form.hidden_fields %} {{hidden}} {% endfor %} {% for field in form.visible_fields %} <div class="form-group"> <label for="{{field.id_for_label}}">{{field.label}}</label> {{field|add_class:"form-control"}} </div> {% endfor %} <button type="submit">Upload</button> </form> {% endblock %} form.py class DocumentForm(forms.ModelForm): class Meta: model=html fields=['project','version','diff','program','location'] -
django template tag missing 1 required positional argument : value
In my django project I have custom template tag to set correct next link in pagination : @register.tag(name='url_replace') def url_replace(request, field, value): print('this is form tag',request,field,value) d = request.GET.copy() d[field] = value return d.urlencode() In my template : {% if is_paginated %} <ul class="pagination pull-right"> {% if page_obj.has_previous %} <li><a href="?{% url_replace request 'page' page_obj.previous_page_number %}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in paginator.page_range %} {% if page_obj.number == i %} <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a href="?{% url_replace request 'page' i %}">{{ i }}</a></li> {% endif %} {% endfor %} {% if page_obj.has_next %} <li><a href="?{% url_replace request 'page' page_obj.next_page_number %}">&raquo;</a></li> {% else %} <li class="disabled"><span>&raquo;</span></li> {% endif %} </ul> {% endif %} Looks every thing fine but it is showing me error Exception Value: url_replace() missing 1 required positional argument: 'value' I am unable to figure out the problem as I passed all three arguments ! -
Django ModelForm: How to Add ForeignKey as Field in Form?
I have Three Models StudentInfo, StdSubject, Marks class StdSubject(StdCommon): REGULAR='R' OPTIONAL='O' SUBJECT_TYPE_CHOICE=( (REGULAR, 'REGULAR'), (OPTIONAL, 'OPTIONAL') ) subject_name = models.CharField('Subject Name', max_length=100) subject_type = models.CharField( 'Subject Type', max_length=1, default=REGULAR, choices=SUBJECT_TYPE_CHOICE) subject_full_marks = models.DecimalField( 'Full Marks', max_digits=5, decimal_places=2, default=100) subject_pass_marks = models.DecimalField( 'Pass Marks', max_digits=5, decimal_places=2) def __str__(self): return self.subject_name class StudentInfo(StdCommon): STD_CLASS=( ('6','Six'), ('7','Seven'), ('8','Eight'), ('9','Nine'), ('10','Ten'), ) STD_GENDER=( ('MALE','Male'), ('FEMALE','Female'), ) STD_GROUP=( ('S', 'Science'), ('B', 'Business Studies'), ('H', 'Humatics'), ('G', 'General') ) std_name = models.CharField('Student Name',max_length=100, help_text='Type only student Full Name like as Nazmul Islam or Nazrul Islam') std_class = models.CharField('Student Class',max_length=2, choices=STD_CLASS, default=6, help_text='Select a class') std_roll = models.IntegerField('Roll Number',help_text='Type Student Roll Number (Only Number)') std_group=models.CharField('Group', choices=STD_GROUP, max_length=1, default='G') std_gender=models.CharField('Gender', max_length=10, choices=STD_GENDER, default='MALE') std_subjects = models.ManyToManyField(StdSubject) def __str__(self): return self.std_name class Marks(StdCommon): std_name=models.ForeignKey(StudentInfo, on_delete=models.CASCADE) subject_name = models.ForeignKey(StdSubject, on_delete=models.CASCADE) subject_marks=models.DecimalField(max_digits=5, decimal_places=2, help_text='Please give proper number') subject_gradepoint=models.DecimalField('Grade Point', max_digits=3, decimal_places=1, blank=True, null=True, help_text="Please keep blank") subject_gpa = models.CharField('Subject GPA', max_length=5, blank=True, null=True, help_text="Please keep blank") std_result=models.FloatField(blank=True, null=True) def __str__(self): return self.std_name.std_name+' Class: '+str(self.std_name.std_class)+' Roll: '+str(self.std_name.std_roll) +' ' + self.subject_name.subject_name +' '+str(self.subject_marks) def subject_grade(self): grade = SubjectGrade(self.subject_marks,self.subject_name.subject_full_marks).subgrade() return grade def subject_grade_point(self): grade = SubjectGradePoint( self.subject_marks, self.subject_name.subject_full_marks).subgrade() return grade def save(self, *args, **kwargs): grade_point = SubjectGradePoint(self.subject_marks, self.subject_name.subject_full_marks).subgrade() gpa = SubjectGrade(self.subject_marks,self.subject_name.subject_full_marks).subgrade() if self.subject_name.subject_type=='O': … -
Django Eclipse: How to setup settings module in eclipse (trying to use django shell)?
So I want to use python shell inside eclipse. When I click django shell environement in eclipse I get the following prompt: https://imgur.com/a/kPGrdgl Now I assume it wants the path to the settings.py file? I so, based on my folder structure (please check the image above!) the path should be rango.settings.py right? I've tried that but I get the ModuleNotFoundError: No module named 'app1' What am I doing wrong? please help! -
Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable?
I am using ubuntu 16.04 .now I am starting my first Django project.please check this error. (unix-9PXH2taC) unix@unix:~/Desktop/django/test_project$ python manage.py runserver Traceback (most recent call last): File "manage.py", line 8, in from django.core.management import execute_from_command_line ImportError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 14, in ) from exc 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? -
bottom part cannot be shown using using django-crispy-forms
I am trying to create form view using django-crispy-view. Even though I could implement form view following the doc, submit button cannot be shown (as shown below) even though I can confirm submit button zooming out to 50%. Does anyone know how to fix this problem? -
inline.bundle.js not included in dist folder after ng build angular 6
Im having an issue. When I run ng serve my angular site works fine. But when I run ngbuild take the files and place them in my django project, run collectstatic by running python manage.py runserver and then attempt to go to my site. I get the following error: raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name) ValueError: Missing staticfiles manifest entry for 'inline.bundle.js' I ran ng build and looked at the dist folder and didn't see a inline.bundle.js has this been removed? Or is this a issue with my settings? my package.json looks like this. { "name": "suitsandtables", "version": "0.0.0", "license": "MIT", "scripts": { "ng": "ng", "start": "ng serve", "build": "ng build", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e" }, "private": true, "dependencies": { "@agm/core": "^1.0.0-beta.2", "@angular/animations": "6.0.7", "@angular/cdk": "^5.2.5", "@angular/common": "6.0.7", "@angular/compiler": "6.0.7", "@angular/core": "6.0.7", "@angular/forms": "6.0.7", "@angular/http": "6.0.7", "@angular/platform-browser": "6.0.7", "@angular/platform-browser-dynamic": "6.0.7", "@angular/platform-server": "6.0.7", "@angular/router": "6.0.7", "@ng-bootstrap/ng-bootstrap": "^1.1.2", "angular-font-awesome": "^2.3.7", "angular-media-queries": "^0.6.1", "angular4-carousel": "^3.1.8", "autoprefixer": "^8.3.0", "bootstrap": "4.0.0-beta.2", "bootstrap-scss": "^4.0.0", "bootstrap-select": "^1.13.0", "core-js": "^2.4.1", "font-awesome": "^4.7.0", "google-fonts": "^1.0.0", "jasmine": "^3.1.0", "jquery": "^1.12.4", "ng-multiselect-dropdown": "^0.1.6", "ng-simple-slideshow": "^1.2.2", "ng2-pdf-viewer": "^3.0.8", "ng2-slide-down": "^0.1.6", "ng2-smooth-scroll": "^1.0.1", "node-gyp": "^3.6.2", "pepjs": "^0.4.3", "popper.js": "^1.14.3", "rebuild": "^0.1.2", "rxjs": "^6.2.1", "rxjs-compat": "^6.2.1", … -
Django - embed textfield in ChoiceField
I am trying to create a multiple-choice question, where one of the choices is to enter the answer yourself. I know how to get a textfield for answer-entry and I know how to get a Multiple-choice field. However, I want the answer-entry to be one of the choices, so that people cannot both enter an answer and select one. Here's an illustration: * Enter your answer: _______ * Chioce 1 * Choice 2 * Choice 3 I don't know how to do this via Django forms. If it were pure HTML, I would do something like the following: <input type="radio" name="Options"> Some Label <input type="text"><br> However, I don't know how to achieve the same thing via Django/Python. -
"ModuleNotFoundError: No module named x" : Pydev configuration correct?
Really struggling with Eclipse Pydev, first time trying it out. Trying to run shell command in python django, however Im getting the following error: ModuleNotFoundError: No module named 'rango' I checked Project > Properties > PyDev - Django to see settings module and both fields saying: "settings / manage module not found... Here is the screen: https://imgur.com/a/rNqXLqf Here is the stack trace: Traceback (most recent call last): File "<input>", line 1, in <module> File "F:\CAB302\java-latest-released\eclipse\plugins\org.python.pydev.core_6.4.1.201806231219\pysrc\_pydev_bundle\pydev_import_hook.py", line 21, in do_import module = self._system_import(name, *args, **kwargs) ModuleNotFoundError: No module named 'rango' Is the Python Path correct? Also I am not sure what a python path represent? (please explain). For refference Python path screen capture: https://imgur.com/a/wUw97OJ What would be the correct path for the error in the photo one? I assume its why I am getting the ModuleNotFoundError? Please help! -
Django Authorization - Return redirect within a function call
I'm adding some custom authorization to verify that logged in users have access to a specific sections of my application. It's not pretty, but it works: view_permissions = { 'admin_list': { 'school':{'userrole':['S','A'], 'usertype':[]}, 'class':{'userrole':['S','A'], 'usertype':[]}, ' ... ' }, 'delete_object': { ... }, 'edit_object': { ... }, } } def check_permissions(request, viewname, objecttype): if(request.user.userrole in view_permissions[viewname][objecttype]['userrole'] or request.user.usertype in view_permissions[viewname][objecttype]['usertype'] ): return True else: return False def delete_object(request, objecttype, objectid): # Redirect to home page if not authorized if(not check_permissions(request, 'delete_object', objecttype)): return redirect('wakemeup:index') # Otherwise, continue processing myobject.delete() ... return admin_list(request, objecttype) What I want to do is move the redirect to be inside the check_permissions function, something like this: def check_permissions(request, viewname, objecttype): if( <check permissions are valid> ): pass # Authorized: Do nothing and continue with caller view logic else: return redirect('wakemeup:index') # Unauthorized: redirect to home def delete_object(request, objecttype, objectid): # Redirect to home page if not authorized check_permissions(request, 'delete_object', objecttype)) The problem is that, the redirect inside the check_permissions function doesn't do anything. It only redirects if I add a return to the calling logic: def delete_object(request, objecttype, objectid): # Redirect to home page if not authorized return check_permissions(request, 'delete_object', objecttype)) I'm guessing it has … -
Django2.0; still cannot get how redirect works
I'm new to Django and I still don't get how redirect works. For now, I use this way to redirect. return HttpResponseRedirect(reverse_lazy('main:index')) and this way works. And now I'm creating another page, and what I want to do is to redirect to the same page after I submit the form data. view.py is like this def add_comment(request, pk): entry = Entry.objects.get(id=pk) if request.method != 'POST': form = CommentForm() else: form = CommentForm(request.POST) if form.is_valid(): new_comment = form.save(commit=False) new_comment.user = request.user return redirect('add_comment', pk=entry.id) return render(request, 'campus_feed/add_comment.html', {'form': form, 'entry': entry, 'comments': comments}) urls.py is like this path('add_comment/<int:pk>', views.add_comment, name='add_comment'), I can enter this page, but after I submit the form, this error happens. NoReverseMatch at /add_comment/5 Reverse for 'add_comment' not found. 'add_comment' is not a valid view function or pattern name. Request URL: http://127.0.0.1:8000/add_comment/5 even though I can enter this url page, I cannot redirect to the same page. How am I wrong with this? Also what is the recommended way to redirect to a page? -
Django-Python admin-site add user text-fields gone
Utilizing the default admin site at www.website.com/admin I click 'add user' and the page displays (see below) but with no text fields/labels. I added a new model to an app... E.G. www.website.com/app1... and the text fields/labels showed and, since it was adding features of a user that did not exist yet, it redirected me to the same flawed defualt add-user page. Please advise.