Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix urlpatternes does not match
I am using Django and javascript to create an URL that is entered by a form input but after submitting it I am getting an error that page does not exist even I have the pattern urlpatterns=[ path('chat',views.index,name='index'), path('chat/<str:room_name>',views.room,name='room'), ] and the javascript code is document.querySelector('#room-name-submit').onclick = function(e) { var roomName = document.querySelector('#room-name-input').value; window.location.pathname = '/chat/' + roomName + '/'; }; for example, if we enter lobby my url will be chat/looby and it should match with the 'room' , but I am getting error Using the URLconf defined in mychat.urls, Django tried these URL patterns, in this order: chat [name='index'] chat/ [name='room'] admin/ The current path, chat/lobby/, didn't match any of these. -
Django ORM: construct query that would look for match on field in object at the last position of many to many field
I stumbled upon something I can't figure out by myself - while filtering (in Django ORM) query I would like to query for objects meeting condition, that some field of last object in the list of many to many objects is equal to some input. It may sound not so obvious, so below I provide an example: Animal model class Animal(models.Model): name = models.TextField(null=True, blank=False) awards = models.ManyToManyField(Award, related_name='awards') Award model class Award(models.Model): name = models.TextField(null=False, blank=False) place = models.TextField(null=True, blank=True) date = models.DateTimeField(null=True) Having these classes, I would like to construct query like this: Animal.objects.filter(awards__name__last='National Award') Because Animal.objects.filter(awards__name='National Award') normally returns (when using .values()) list looking like this: [{'name': u'National Award', 'place': u'capital', 'date': datetime.datetime(2018, 7, 13, 5, 2, 45, 23000), u'id': 1}, {'name': u'International Award', 'place': u'capital', 'date': datetime.datetime(2018, 10, 1, 1, 1, 55, 79000), u'id': 2}] and for such object, query would ommit it, because 'National Award' is not on the last position on the list, but if this object would have switched these entries, it would be returned by this query, since the last object name is equal to 'National Award'. I do not want to use date field for this query. -
CORS did not succed when deployed on heroku https, works locally
I have a fullstack Django and React app, which works perfectly on my local machine with no issues, but when I deploy it on Heroku I got this well-known error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at (...), but the problem does not occur when I use HTTP instead of HTTPS. Could it has something to do with https configuration? Middleware MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS config CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True -
Django constance variable check in settings.py
I am trying to enable custom logging toggle check inside settings.py as shown below(the code is at the bottom of the file): from constance import config if config.CUSTOM_LOGGING: LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format': '%(asctime)s [%(levelname)s] : %(message)s' }, }, 'handlers': { 'default': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': 'pd_temp/celery_logs/allume_feed_jobs.log', 'maxBytes': 1024 * 100, # 100 kB 'backupCount': 5, 'formatter': 'standard', }, }, 'loggers': { '': { 'handlers': ['default'], 'level': 'DEBUG', 'propagate': True }, } } But I am getting this error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Any workaround for the above scenario would be very helpful. Thanks! Ref: Django constance (https://django-constance.readthedocs.io/en/latest/) -
Error: Please define stage 'create_pg_db' in your Zappa settings
Intro: I am deploying a django app to aws lambda severlessly using zappa. My RDS instance has a postgres database. I am watching rich jones djangocon video on how to deploy django app severlessly using zappa. So far I have managed to reach the part where I need to add a database to my project. I have already done pip install zappa-django-utils and added it to my INSTALLED_APPS. Now when I try to run zappa manage create_pg_db production I get the error Error: Please define stage 'create_pg_db' in your Zappa settings. I even tried zappa manage create_pg_db I am still getting the same error Below is how my zappa_settings.json file looks: { "production": { "aws_region": "us-east-1", "django_settings": "Cool.settings", "profile_name": "default", "project_name": "cool", "runtime": "python3.6", "s3_bucket": "cool-7dsfsdf5", "project_directory": "/tmp/code", "slim_handler": true, "vpc config": { "SubnetIds": [ "subnet-3132ss13b", "subnet-321321319", "subnet-2c2313223", "subnet-5ljlkjljd", "subnet-132121357", "subnet-f925f9c7" ], "SecurityGroupIds": [ "sg-a9asdasd" ] } }, "production_ap_northeast_1": { "aws_region": "ap-northeast-1", "extends": "production" }, "production_ap_northeast_2": { "aws_region": "ap-northeast-2", "extends": "production" }, ... All regions.. } How do I define stage 'create_pg_db' in your Zappa settings. Does anyone know the steps ahead of this -
How to send data with multiple dynamic form id with Djano, Ajax, and javascript?
Sorry before that i have bad english. So i want to send data from django form with ajax and javascript, but the problem is i have add button to add more field, every time i add field the field id increase i already tried with single form id, its success, but with multiple dynamic id it fail My html : {{ ipform.management_form }} {% for form in ipform %} <div class="form-group"> <div class="row form-row spacer"> <div class="col-2"> <label>{{form.ipaddr.label}}</label> </div> <div class="col-4"> <div class="input-group"> {{form.ipaddr}} <div class="input-group-append"> <button class="btn btn-success add-form-row">+</button> </div> <div class="col-2"> <p id="cekip"></p> </div> </div> </div> </div> </div> {% endfor %} Javascript: function updateElementIndex(el, prefix, ndx) { var id_regex = new RegExp('(' + prefix + '-\\d+)'); var replacement = prefix + '-' + ndx; if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement)); if (el.id) el.id = el.id.replace(id_regex, replacement); if (el.name) el.name = el.name.replace(id_regex, replacement); } function cloneMore(selector, prefix) { var newElement = $(selector).clone(true); var total = $('#id_' + prefix + '-TOTAL_FORMS').val(); newElement.find(':input').each(function() { var name = $(this).attr('name') if(name) { name = name.replace('-' + (total-1) + '-', '-' + total + '-'); var id = 'id_' + name; $(this).attr({'name': name, 'id': id}).val('').removeAttr('checked'); } }); total++; $('#id_' + prefix + '-TOTAL_FORMS').val(total); $(selector).after(newElement); var … -
dynamically generate category list into base template with django class base views
views.py from django.shortcuts import render, get_object_or_404 from django.utils.decorators import method_decorator from django.views.decorators.gzip import gzip_page from django.views.decorators.http import condition from django.views.generic.detail import SingleObjectMixin from django.utils import timezone from django.views.generic import \ ListView, DetailView from .models import ( Book, Category, Author, Language, Currency, Tag, ) from django.db.models import Q class BookList(ListView): model = Book context_object_name = 'book_list' template_name = 'books/book_lists.html' paginate_by = 12 extra_context = { 'category_list': Category.objects.all(), 'author_list': Author.objects.all(), 'language_list': Language.objects.all(), } def get_queryset(self): query = self.request.GET.get('q') if query: object_list = self.model.objects.filter( Q(name_of_the_book__icontains=query) | Q(author__first_name__icontains=query) | Q(category__name__icontains=query) ) else: object_list = self.model.objects.all() return object_list class SingleCategoryView(DetailView): model = Category template_name = 'books/single_category.html' paginate_by = 12 extra_context = { 'category_list': Category.objects.all(), 'author_list': Author.objects.all(), 'language_list': Language.objects.all(), } class SingleAuthorView(DetailView): model = Author template_name = 'books/single_author.html' extra_context = { 'category_list': Category.objects.all(), 'author_list': Author.objects.all(), 'language_list': Language.objects.all(), } class SingleLanguage(DetailView): model = Language template_name = 'books/single_language_list.html' extra_context = { 'category_list': Category.objects.all(), 'author_list': Author.objects.all(), 'language_list': Language.objects.all(), } class BookDetails(DetailView): model = Book template_name = 'books/book_details.html' # extra_context = { # 'category_list': Category.objects.all(), # 'author_list': Author.objects.all(), # 'language_list': Language.objects.all(), # } def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['now'] = timezone.now() return context Here BookList view is my home page. In my base template, I've added some kind of … -
Django template, loop through items if their id is equal to parent loop name
I'm trying to loop through different Zones and then show the items which are part of this zone Zone is a model, has a name and a ForeignKey. Planche is a model which has Zone as ForeignKey. I'm looping through zones to display each zone. In that loop I'm looping all Planches and would like to display only the ones that have Zone as a ForeignKey. class Zones(models.Model): name = models.CharField(max_length=30) genre = models.ForeignKey(ZoneTypes, on_delete=models.CASCADE) def __str__(self): return self.name class Planche(models.Model): pzone = models.ForeignKey(Zones, on_delete=models.CASCADE) ref = models.CharField(max_length=5, default="1") length = models.IntegerField() width = models.IntegerField() orientation = models.CharField(max_length=30) def __str__(self): return self.ref Template <div> <h1><a href="/">My list of planches</a></h1> </div> {% for z in zones %} <div> <h2><a href="/zone/{{ z.name }}">Zone name: {{ z.name }}</a></h2> {% for p in planches %} {% if p.pzone == z.name } <h1><a href="planche/{{ planche.ref }}">Ref: {{ p.ref }}</a></h1> <p>Length: {{ p.length }} - Width: {{ p.width }}</p> <p>Orientation: {{ p.orientation }} {% endif %} {% endfor %} </div> {% endfor %} {% if p.pzone = z.name %} returns False, They both return the same string if I just display them {{ p.pzone }} and {{ z.name }} but I guess they aren't the same … -
NoReverseMatch Django Chat message another user
I'm probably missing something here, but I have a connect page in which the logged in user can chat to another user by clicking on a Chat? link located on each users profile. The chat functionality is built using Django Channels and is accessed via the url pattern site/messages/username where username is the other_user that the current_user is chatting with. I currently have the chat? link as <a class='btn btn-light' href="{% url 'thread' username %}" id="chat">Chat?</a> However that throws the error NoReverseMatch Reverse for 'thread' not found. 'thread' is not a valid view function or pattern name. I have tried following the docs and adding username as an arg / taking it off but I keep hitting this same error. The chat app is included in settings.py and the urls are included in admin.py. The connect and chat are separate apps. Below is relevant code. Thank you for your time and help! chat/urls.py from django.urls import path, re_path from .views import ThreadView, InboxView app_name = 'chat' urlpatterns = [ path("", InboxView.as_view()), re_path(r"^(?P<username>[\w.@+-]+)", ThreadView.as_view(), name='thread'), ] chat/views.py class ThreadView(LoginRequiredMixin, FormMixin, DetailView): template_name = 'chat/thread.html' form_class = ComposeForm success_url = './' def get_queryset(self): return Thread.objects.by_user(self.request.user) def get_object(self): other_username = self.kwargs.get("username") obj, created … -
'NewPost 'Object has no attribute 'user'
In my forum app,I want to show post details with it's author name. In 'new-post' class in views.py I tried to save the author name by post.user = self.request.user But whenever my current login user submits his new post it gives the mentioned error. views.py: class NewPost(CreateView): form_class = PostForm template_name = 'post_form.html' @login_required def form_valid(self,form): post = form.save(commit=False) post.user= self.request.user post.save() return redirect('website:details', post=post) forms.py: class PostForm(forms.ModelForm): class Meta: model = Post fields=('title','description') Models.py: class Post(models.Model): user = models.ForeignKey(User, on_delete =models.CASCADE) title = models.CharField(max_length = 500, blank = False) description = models.TextField() def __str__(self): return self.title AttributeError at /website/add/ 'NewPost' object has no attribute 'user' Request Method: POST Request URL: http://127.0.0.1:8000/website/add/ Django Version: 1.9 Exception Type: AttributeError Exception Value: 'NewPost' object has no attribute 'user' Exception Location: C:\Python27\lib\site-packages\django-1.9-py2.7.egg\django\contrib\auth\decorators.py in _wrapped_view, line 22 Python Executable: C:\Python27\python.exe Python Version: 2.7.14 Python Path: ['C:\Users\as_couple\Desktop\STUDENTTRACKERSYSTEM', 'C:\WINDOWS\SYSTEM32\python27.zip', 'C:\Python27\DLLs', 'C:\Python27\lib', 'C:\Python27\lib\plat-win', 'C:\Python27\lib\lib-tk', 'C:\Python27', 'C:\Python27\lib\site-packages', 'C:\Python27\lib\site-packages\django_admin-1.1.1-py2.7.egg', 'C:\Python27\lib\site-packages\django_excel_response2-2.0.8-py2.7.egg', 'C:\Python27\lib\site-packages\django_six-1.0.4-py2.7.egg', 'C:\Python27\lib\site-packages\django-1.9-py2.7.egg'] -
Connecting django with oracle database
Im a beginner to django. Someone help to connect Oracle 11g db with django 2.0 in windows. What is the requirements and how to connect and what are the changes to be done. -
Django rollback transaction after perform_create
I am trying to use transaction.atomic with django without any luck I know I am doing something wrong but I dont know what. class SnapshotView(BaseViewSet): serializer_class = SnapshotSerializer @transaction.atomic def perform_create(self, serializer): # this will call serializer.save() snapshot = snapshot = super().perform_create(serializer) # this will run some code can raise an exception SnapshotServices.create_snapshot(snapshot=snapshot, data=serializer.initial_data) the first method that creates a new snapshot will pass the second will raise but still I can see my snapshot instance in the db, why is that? I am in transaction block and something fails, is django not suppose to do a rollback? the second method will throw a custom exception I read the doc and it seems that I am doing everything right. -
Django admin plugin for scanning table list
Is there any Django Admin plugin, which scans on start the whole schema for table/column list and configures Django Admin for all tables in schema? I want to make admin panel for non-django application, because there is no better admin panel than Django, but I don't want to sync schema definition between node.js and Django -
Error with celery worker in elastic beanstalk (using django and SQS) [ImportError: The curl client requires the pycurl library.]
I'm trying to deploy to elastic beanstalk a django project that uses celery periodic tasks, using SQS. I've been more or less following the instructions here: How to run a celery worker with Django app scalable by AWS Elastic Beanstalk? When I deploy to eb, the periodic tasks are not being executed. Checking the celery-beat log, everything seems right: celery beat v4.2.1 (windowlicker) is starting. __ - ... __ - _ LocalTime -> 2019-01-27 09:48:16 Configuration -> . broker -> sqs://AKIAIVCNK32ABCHNNZSQ:**@localhost// . loader -> celery.loaders.app.AppLoader . scheduler -> django_celery_beat.schedulers.DatabaseScheduler . logfile -> [stderr]@%INFO . maxinterval -> 5.00 seconds (5s) /opt/python/run/venv/local/lib64/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. """) [2019-01-27 09:48:44,659: INFO/MainProcess] beat: Starting... [2019-01-27 09:48:44,660: INFO/MainProcess] Writing entries... [2019-01-27 09:48:44,809: INFO/MainProcess] DatabaseScheduler: Schedule changed. [2019-01-27 09:48:44,809: INFO/MainProcess] Writing entries... [2019-01-27 09:48:49,865: INFO/MainProcess] Writing entries... [2019-01-27 09:49:00,409: INFO/MainProcess] Scheduler: Sending due task sum_two_numbers (sum_two_numbers) [2019-01-27 09:50:00,050: INFO/MainProcess] Scheduler: Sending due task sum_two_numbers (sum_two_numbers) [2019-01-27 09:51:00,045: INFO/MainProcess] Scheduler: Sending due task sum_two_numbers (sum_two_numbers) [2019-01-27 09:51:50,543: INFO/MainProcess] Writing entries... [2019-01-27 09:52:00,048: INFO/MainProcess] Scheduler: Sending due task sum_two_numbers (sum_two_numbers) [2019-01-27 09:53:00,045: INFO/MainProcess] Scheduler: … -
How can I set the field value in django admin based in another field's lookup?
I'd like to get the product price of the selected product and set to price in Order_line. Theres are the models: class Category(models.Model): name = models.CharField(max_length=255) class Product(models.Model): part_number = models.CharField(max_length=255) category = models.ForeignKey('Category') price = models.DecimalField(max_digits=10, decimal_places=2) class Order(models.Model): customer = models.CharField(max_length=255) class Order_line(models.Model): order = models.ForeignKey('Order', on_delete=models.CASCADE) category = models.ForeignKey('Category', on_delete=models.CASCADE) product = models.ForeignKey('Product', on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) -
Django is usable for data persistence?
I want use data persistence, but I had seen that spring for Java is better. But I want learn python but also I want use data persistence. What is your recommendation? -
Wagtail ListBlock - how to access first (any) element in template?
I have ListBlock called imagesin Wagtail. It works well. If I put {% page.images %} in a template, it render the html code like: <ul> <li>item1</li> <li>item2</li> </ul> But I am unable to find out how to get the first item of the list isolated. Or at least how to iterate over the list manually. I am pretty sure the solution is simple, however I am unable to google it, find in the docs, or understand from the wagtail source. -
Django Channels tutorial error - ConnectionRefusedError: [Errno 10061]
I am following the tutorial but when i check if the channel layer can communicate with Redis it is giving me error. I am using Window 10 OS. ERROR File "C:\Users\Suleman\AppData\Local\Programs\Python\Python37-32\lib\asyncio\base_events.py", line 935, in create_connection await self.sock_connect(sock, address) File "C:\Users\Suleman\AppData\Local\Programs\Python\Python37-32\lib\asyncio\selector_events.py", line 475, in sock_connect return await fut File "C:\Users\Suleman\AppData\Local\Programs\Python\Python37-32\lib\asyncio\selector_events.py", line 505, in _sock_connect_cb raise OSError(err, f'Connect call failed {address}') ConnectionRefusedError: [Errno 10061] Connect call failed ('127.0.0.1', 6379) setting.py CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } -
Why am I receiving Forbidden (CSRF token missing or incorrect)?
I have been receiving Forbidden (CSRF token missing or incorrect) I have tried different solutions found on Stack Overflow but I am unable to fix it! I have tried to use the render_to_response, and when I do that I receive this error: This is usually caused by not using RequestContext. "A {% csrf_token %} was used in a template, but the context " This is the forms.py from django import forms from django.forms import widgets class AskForm(forms.Form): name = forms.CharField( max_length=30, widget=forms.TextInput( attrs={ 'placeholder': 'Write your name here' 'class': 'ask-page-input' 'label': 'Student Name' } )) email = forms.EmailField( max_length=254, widget=forms.EmailInput( attrs={ 'placeholder': 'Write your Email here' 'class': 'ask-page-input' 'label': 'Email' } )) subject = forms.CharField( max_length=50 widget=forms.TextInput( attrs={ 'placeholder': 'Write your Question or Related Subject here' 'class': 'ask-page-input' 'label': 'Subject' } )) message = forms.CharField( max_length=2000, widget=forms.Textarea( attrs={ 'placeholder': 'Write your message here' 'class': 'ask-page-input' 'label': 'Message' } )) source = forms.CharField( # A hidden input for internal use max_length=50, # tell from which page the user sent the message widget=forms.HiddenInput() ) def clean(self): cleaned_data = super(ContactForm, self).clean() name = cleaned_data.get('name') email = cleaned_data.get('email') subject = cleaned_data.get('subject') message = cleaned_data.get('message') if not name and not email and not subject and … -
Wagtail url prefix for a custom Page model
This question is probably trivial, but I am unable to see a simple solution. I have custom page model representing Post: class PostPage(Page): I would like to make all instances of this model (all Posts) accessible only with url prefix /posts/ Example: User creates new Post, the assigned slug will be awesome-first-post What should happen is, that /awesome-first-post/ will result in 404, while /posts/awesome-first-post/ will display the post. Note: I want this prefix only for the specific model Postpage. Other pages should be served directly from their slug. -
how to get django pagination unique item id across all pages?
I am learning how to implement django pagination. I want to let user save all changes (the whole form no matter which pagination )when he/she clicks the save-all button. However, when using forloop.counter0, the django will render duplicate forloop counter. How can I generate continuous unique id from 0 to n-1 so that at views.py, the views can recognize every items? Thanks! {% for thing in things %} <tr id="tr-{{ thing.id }}"> <td style="display:none"><input type="text" name="hidden-id-{{ forloop.counter0 }}" value="{{ thing.id }}"></td> </tr> {% endfor %} -
How to save bio using forms.ModelForm
I tried multiple links on stackov. but none worked, I can't get my bio form to save the data on the db for the user profile :/ I managed to save the first name and last name, but I can't make the bio save... This is my code: profile.html <div class="tab-pane active" id="home"> <br> <div class="form-group"> <div class="col-6"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <label for="first_name"> <h4>First name</h4> </label> {{ user_ProfileForm.first_name |as_crispy_field }} <label for="last_name"> <h4>Last name</h4> </label> {{ user_ProfileForm.last_name |as_crispy_field }} <p> {{ user_BioAndSocialForm.bio |as_crispy_field }} </p> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Update</button> </div> </form> </div> </div> <br> <hr> </div> views.py @login_required def profile(request): if request.method == 'POST': user_ProfileForm = UserProfileForm(request.POST, instance=request.user) user_BioAndSocialForm = BioAndSocialForm(request.POST, instance=request.user) if user_ProfileForm.is_valid() and user_BioAndSocialForm.is_valid: user_ProfileForm.save() user_BioAndSocialForm.save() messages.success(request, f'Profile updated!') return HttpResponseRedirect(request.path_info) else: messages.error(request, _('Please correct the error below.')) else: user_ProfileForm = UserProfileForm(instance=request.user) user_BioAndSocialForm = BioAndSocialForm(instance=request.user) context = { 'user_ProfileForm': user_ProfileForm, 'user_BioAndSocialForm': user_BioAndSocialForm } return render(request, 'users/profile.html', context) forms.py class BioAndSocialForm(forms.ModelForm): class Meta: model = Profile fields = ['bio'] def __init__(self, *args, **kwargs): super(BioAndSocialForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_show_labels = False models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) birth_date = models.DateField(null=True, blank=True) #Image feature upload image = models.ImageField(default='default.jpg', upload_to='profile_pics') … -
Deploy Django and ReactJS on Nginx
I deployed Django app on Nginx with configuration below server { listen 80; server_name server_domain_or_IP; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/sammy/myprojectdir; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Now, I want to deploy React App in the same server. After the deployment of React App, I still want to access Django Admin through server_domain_or_IP/admin and REST APIs through server_domain_or_IP/[api_url]. The URL to serve the index.html from React Apps will be on server_domain_or_IP. Can I just add another location like below and things will still go well? # where my frontend js files are location /frontend { alias /home/sammy/frontend; } In order to clear confusion between React App and Rest APIs route, I am planning to append /api on the Rest API route. Inside React JS, I am already calling the API with http://127.0.0.1:8000/author_list/. Will Nginx works fine without /api? -
How do I access variables from form_valid in get_success_url in a FormView?
After a user submits my form, I want to redirect the user to one of two URLs depending on the form input. Here is my code: class MyClass(FormView): template_name = 'my_template.html' form_class = MyForm def form_valid(self, form, *args, **kwargs): response = super().form_valid(form, *args, **kwargs) self.title = form.cleaned_data.get('title') self.special_id = form.cleaned_data.get('special_id') return response def get_success_url(self): if self.special_id: next_page = reverse_lazy('home:home', kwargs={'special_id': self.special_id}) else: initial_link = reverse_lazy('home:home') next_page = '{}?title={}'.format(initial_link, self.title) return next_page This code above does not work. One problem is that get_success_url doesn't recognize the variables self.special_id or self.title. How can I redirect users to different pages depending on the values in the form? -
Generating files after adding model instance through django admin interface
I'm writing a model for a website. When a user adds an instance of the model through the Django admin, I want to catch the event and automatically generate files, including adding a reference path field for those created files. Django admin has a clean method that can be overridden. I can create and update files and fields through this. def clean(self): info = self.cleaned_data.get('info') ... #Generate IO paths from info self.cleaned_data['template_path'] = template_path self.instance.template_path = template_path return self.cleaned_data I need to create a distinction between add and change events, so I'm not writing files and changing the pathing post object creation. Is there a way to do this within clean, or should I be looking elsewhere to create fields & update fields?