Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Difference between app_secret_key and secret_key for Django-Auth-App
For the python django package, django-duo-auth, the README shows the proper DUO CONFIG to be like so in settings.py: DUO_CONFIG = { 'DEFAULT': { 'HOST': '<api-host-url>', 'IKEY': '<integration_key>', 'AKEY': '<app_secret_key>', 'SKEY': '<secret_key>', 'FIRST_STAGE_BACKENDS': [ 'django.contrib.auth.backends.ModelBackend', ] } } HOST, IKEY, and SKEY make sense as they are attributes found in the Duo AUTH API, but I am confused as to what app_secret_key would mean. Any suggestions? -
Flushing a Database in Django
I'm setting up a database in django, while trying to flush the database i get the following error: `https://pastebin.com/Ktc203Rv.` While trying to migrate, the following error occured: `https://pastebin.com/Sc9rFQaT` I'm using django version 3.1.6 -
Django REST Framework: validated_data missing certain fields
I'm in the process of creating a registration process for my app. I'm having issues getting things running correctly. My intention is to send off one POST request with all of the necessary JSON to create the various models in Django. My error is that there is a KeyError for 'lat_long' when handling the coordinates. I checked validated_data to find that the data from my JSON body is not making it to the validated_data and neither is distance limit? However, bio, exp, age and town are all there in validated_data. Why is this? Both are declared in the ProfileSerializer and the models seem correct. However both of these fields are not present. In validated_data: 'genres' is just OrderedDict() with nothing inside so it isn't going to create the desired UserGenre instances either. Any help with this would be greatly appreciated, I've been trying to fix this for 4 days to no avail! P.S. If people could take a look at the serializers in particular and tell me am I going about creating multiple models/objects in one request correctly? Or is there a better way of doing it? Here is models.py (I'm using Djangos standard User object and have a Genre … -
Redirect page to dynamic URL Django
I'm a beginner on using django platform to create a mini project website and use a function based view. One of the feature in my project is a profile page that allowing user to edit the personal information. Here is my user profile models.py: class UserProfile(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE, blank=True) company_name = models.CharField(max_length=50, blank=True) company_url = models.URLField(max_length=50, blank=True) country = CountryField(null=True) AFF_CHOICES = (('Academic','Academic'), ('Bussiness','Bussiness'), ('Non-profit','Non-profit'), ('Industry/Government','Industry/Government')) affiliation = models.CharField(max_length=50, choices=AFF_CHOICES, null=True, blank=True) profile_picture = models.ImageField(upload_to='profile_picture', null=True, default='profile_picture/defaultphoto.png') def __str__(self): return str(self.user) Here is my urls.py app_name = 'dashboard' urlpatterns = [ path('', dashboard, name='dashboard'), path('<int:pk>/profile/',profile, name='profile'), path('<int:pk>/edit_profile/',edit_profile, name='edit_profile'), as you can see it will pass user PK so it will look like this (example on profile page) http://127.0.0.1:8000/dashboard/42/profile/ and it's already works. Here is my edit_profile views.py: def edit_profile(request, pk): user = request.user form = UserProfileForm(instance=user) if request.method == 'POST': form = UserProfileForm(request.POST, request.FILES, instance=user,) if form.is_valid(): form.save() messages.success(request, 'Your profile has been updated.') return redirect('/profile/dashboard/') #The problem is here #Still static else : form = UserProfileForm() context = {'editform':form} return render(request, 'dashboard/editprofile.html', context) i've tried this case with static url (not passing the user PK on url) and it is already works. How do i pass the … -
Django Display latest emails to certain user in Template
My django app I have created relies heavily on emails that are sent like this: from django.core.mail import send_mail send_mail( 'Subject here', 'Here is the message.', 'from@example.com', ['to@example.com'], fail_silently=False, ) Lets say that I keep sending an email to an user's email like this: post = get_object_or_404(Post, pk=pk) post_title = post.title author_of_post = post.author post_email = author_of_post.email send_mail( 'An User Comment on Your Post', '''Dear User, ''' ''' Your post, ''' + post_title + ''' was comment on by an user. Want to reply and check it out? --From the People at Red Man 2''' , 'redman2customerservice@gmail.com', [post_email], ) Now I want to add a notifications area, where it will display all the latest emails sent to the user, in the example of above post_email. So how would I do this. To sum up, I want to have a template where an user can see the latest emails sent to their account, sort of like a notification area. Thanks. -
ValueError: signal only works in main thread - Django, Scrapy celery
I am trying to implement a web scraper in my django app using scrapy in a celery task. I keep getting this error. I have tried every solution on here but can't figure it out. I followed this tutorial for my crawl file My crawl.py file from multiprocessing import Process from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings from .spider import AliSpider settings = get_project_settings() class UrlCrawlerScript(): def __init__(self): self.crawler = CrawlerProcess(settings) self.crawler.install() self.crawler.configure() def _crawl(self, url): self.crawler.crawl(AliSpider(url)) self.crawler.start() self.crawler.stop() def crawl(self, url): p = Process(target=self._crawl, args=[url]) p.start() p.join() crawler = UrlCrawlerScript() def url_crawl(url): crawler.crawl(url) My Spider file import scrapy class AliSpider(scrapy.Spider): name = 'ali' def __init__(self, *args, **kwargs): self.url = kwargs.get('url') self.start_urls = [self.url] super(AliSpider, self).__init__(*args, **kwargs) def parse(self, response): title = response.css('.module-pdp-title ::text').extract() images = response.css('.main-image-thumb-ul img::attr(src)').extract() price = response.css('.ma-ref-price span::text').extract() types = response.css('.sku-attr-val span::text').extract() i = {} i['url'] = response.url i['title'] = title i['images'] = images i['price'] = price i['types'] = types return i -
Django Remove Allauth Custom HTML Forms
Hi Guys I'm using Allauth to login with Facebook. I developing the website using Django However it seems that if there is an issue with trying to login with my facebook account. The website is automatically being redirect to the default cancelled html page. Any idea how I can remove such redirection? Thanks -
get the id of the clicked instance in a django panel
I created two buttons and I am going to describe you the creation process and the functionality and finally I will ask my question. I have a django class of heroes. One button makes all heroes mortal, and one which makes all immortal. Since it affects all heroes irrespective of the selection, this needs to be a separate button, not an action dropdown. First, we will change the template on the HeroAdmin so we can add two buttons: @admin.register(Hero) class HeroAdmin(admin.ModelAdmin, ExportCsvMixin): change_list_template = "entities/heroes_changelist.html" Then we will override the get_urls, and add the set_immortal and set_mortal methods on the model admin. They will serve as the two view methods: def get_urls(self): urls = super().get_urls() my_urls = [ path('immortal/', self.set_immortal), path('mortal/', self.set_mortal), ] return my_urls + urls def set_immortal(self, request): self.model.objects.all().update(is_immortal=True) self.message_user(request, "All heroes are now immortal") return HttpResponseRedirect("../") def set_mortal(self, request): self.model.objects.all().update(is_immortal=False) self.message_user(request, "All heroes are now mortal") return HttpResponseRedirect("../") Finally, we create the entities/heroes_changelist.html template by extending the admin/change_list.html: {% extends 'admin/change_list.html' %} {% block object-tools %} <div> <form action="immortal/" method="POST"> {% csrf_token %} <button type="submit">Make Immortal</button> </form> <form action="mortal/" method="POST"> {% csrf_token %} <button type="submit">Make Mortal</button> </form> </div> <br /> {{ block.super }} {% endblock %} And … -
inlineformset_factory validation in template and db save only if child and parent forms are valid
I've a form with a subform like this: TYPE = (("S",'Swing'), ("R","Rapide")) class valuation(models.Model): stock = models.ForeignKey("stock",on_delete=models.CASCADE,related_name='valuation',) date = models.DateField(auto_now_add=True) val_type = models.CharField(choices=TYPE, max_length=1,default='R') user = models.ForeignKey("users.User", on_delete=models.CASCADE) def __str__(self): return f"{self.stock} - {self.date} - {self.val_type}" evolQuote = ( (1, 'High'), (0, 'Undetermine'), (-1, 'Low')) class val_detail_Swing(models.Model): valuation = models.OneToOneField(valuation, on_delete=models.CASCADE) cycleMarket = models.IntegerField(choices=evolQuote, null=False, blank=False) news = models.IntegerField(choices=evolQuote,null=False, blank=False) managementPostion = models.IntegerField(choices=evolQuote,null=False, blank=False) short =models.IntegerField(choices=evolQuote,null=False, blank=False) my views.py ChildFormset1 = inlineformset_factory( valuation, val_detail_Swing, form=valuationSwingModelform, can_delete=False) class valuationCreateviewSwing(CreateView): template_name = "evaluation/evaluation_create.html" form_class = valuationModeform def get_initial(self): # prepopulate form query = self.request.GET return { 'user': self.request.user.pk, 'val_type': "S", 'stock': self.kwargs.get('pk'), } def get_context_data(self, **kwargs): # we need to overwrite get_context_data # to make sure that our formset is rendered data = super().get_context_data(**kwargs) if self.request.POST: data["val_detail_swing"] = ChildFormset1(self.request.POST) else: data["val_detail_swing"] = ChildFormset1() data.update({ "typeVal": "Swing",}) return data def form_valid(self, form): context = self.get_context_data() val_detail_swing = context["val_detail_swing"] if form.is_valid() and val_detail_swing.is_valid(): self.object = form.save() val_detail_swing.instance = self.object val_detail_swing.save() return super(valuationCreateviewSwing,self).form_valid(form) def get_success_url(self): return reverse("stock:stock-list") my forms.py class valuationModeform(forms.ModelForm): class Meta: model= valuation fields = ( 'stock', 'val_type', 'user', ) class valuationSwingModelform(forms.ModelForm): class Meta: model = val_detail_Swing fields = ( 'cycleMarket', 'news', 'managementPostion', 'short',) my template: <form method="post">{% csrf_token %} {{ form.as_p }} … -
pip and django-admin work in command prompt but not in git bash terminal
I have a windows 10, and when I try pip --version or django-admin --version in cmd, it works and I get the version number. When I try using pip or django-admin in my git bash terminal I get the error bash: pip: command not found. So I'm thinking the error isn't without my path variables because pip and django-admin work in cmd. How else can I make it work in my git bash terminal? -
Creating static files directory
I'm currently using the recent version of django. I seem to be experiencing difficulty in creating a path for my static files directory. The error i get is "TypeError: _getfullpathname: path should be string, bytes or os.PathLike, not list". from pathlib import Path BASE_DIR = Path(file).resolve().parent.parent STATIC_URL = '/static/' LOCAL_STATIC_CDN_PATH = [BASE_DIR / 'static_cdn_test'] STATIC_ROOT = '/static_cdn_test/blank/static' STATICFILES_DIRS = [ BASE_DIR / 'staticfiles', '/HP/src/staticfiles', ] MEDIA_ROOT = [BASE_DIR / 'media'] MEDIA_URL = '/media/' -
GET request producing undefined behavior in Django + rpy2
Seeing some odd behavior in Django when using rpy2. rfn.py: from rpy2.robjects import r as R import rpy2.robjects as robjects import json from .models import TestModel # 4-5 various R functions R(''' library(someLib) someFunc <- function() { } ''') class SpectraScores(): def __init__(self): pass # A number of other function which when commented out # do not change the error being produced. views.py: from .rfn import SpectraScores def view_cosine(request): if request.method == 'POST': form = ViewCosineForm(request.POST, request.FILES) if form.is_valid(): sc = SpectraScores(form).info() return render( request, 'chat/view_cosine.html', {'form': form, 'sc': sc} ) else: form = ViewCosineForm() return render(request, 'chat/view_cosine.html', {'form': form}) forms.py: from .models import TestModel class ViewCosineForm(forms.Form): ''' Select any spectra from lab, library, metadata ''' sid = forms.ModelMultipleChoiceField( queryset = TestModel.objects.all(), to_field_name = "test", required = False ) Running from the shell and opening a GET(??) request to "/cosine/" produces this: $ ./manage.py runserver [16/Feb/2021 23:32:08] "GET /cosine/ HTTP/1.1" 200 9083 [16/Feb/2021 23:32:08] "GET /static/js/jquery-3.3.1.min.js HTTP/1.1" 304 0 [16/Feb/2021 23:32:08] "GET /static/js/d3.min.js HTTP/1.1" 304 0 [16/Feb/2021 23:32:08] "GET /static/js/bootstrap.bundle.js HTTP/1.1" 304 0 Not Found: /favicon.ico R[write to console]: Error: ignoring SIGPIPE signal R[write to console]: Fatal error: unable to initialize the JIT *** stack smashing detected ***: terminated at … -
Any changes to make in Django when switching from unencrypted to encrypted database on AWS?
I accidentally created an unencrypted database on AWS that I am using with Django. Everything works fine, but now I need to encrypt the database. I have the plan in place on the AWS side. I was wondering if I need to change anything on the Django end though? Will it continue to work with the database as usual? Do I need to specify the encryption keys somewhere? Are there any security groups to configure? I am experienced with Django but new to AWS Thanks in advance! -
Django Models: update field value on save
I have a model that is accessed via an endpoint that uses the slug: path('test/<str:slug>', TestView.as_view(), name='test_view'), I want to create a dynamic link which requires knowledge of the slug so it can't be assigned on creation since the slug hasn't been generated yet. How can I update the dynamic_link field and update it on creation? class TestModel(models.Model): name = models.CharField(max_length=1000) dynamic_link= models.CharField(max_length=1000, blank=True, null=True) slug = AutoSlugField(_('slug'), max_length=150, unique=True, populate_from=('name',)) def save(self, *args, **kwargs): super().save(*args, **kwargs) -
django return nothing/to the exact same location after a user's action
I am doing a reddit-clone project and one of the feature is to do upvote/downvote. I want the user to be able to click on upvote/downvote right on the post-list.html page and show the updates and nothing else. I tried to return None but django doesn't allow it. I tried to return to the "/" but then django returns a webpage from the top. In addition, I feel that my upvote/downvote takes a long time to update, which is strange, I am wondering if there is a way to speed it up. Here is my base.html that has the upvote/downvote feature: {% for post in posts %} <div class="post"> <div class="vote">{% include "Reddit_app/vote-thumbnail.html" with el=post %}</div> Here is the vote-thumbnail.html <div class="voting_panel"> <div class="vote-logo"><a class="glyphicon glyphicon-chevron-up {% if el|user_has_voted:user == 1 %} text-success {%else%} text-muted {% endif %}" href="{% url 'upvote-thumbnail' pk=el.pk %}"></a></div> <div class="score">{{ el.get_score }}</div> <div class="vote-logo"><a class="glyphicon glyphicon-chevron-down {% if el|user_has_voted:user == -1 %} text-success {%else%} text-muted {% endif %}" href="{% url 'downvote-thumbnail' pk=el.pk %}"></a></div> </div> Here is my urls.py path('content/<uuid:pk>/upvote-thumbnail/', views.vote_thumbnail, {'is_upvote': True}, name='upvote-thumbnail'), path('content/<uuid:pk>/downvote-thumbnail/', views.vote_thumbnail, {'is_upvote': False}, name='downvote-thumbnail') Here is my views.py def vote_thumbnail(request, pk, is_upvote): content_obj = Votable.get_object(pk) content_obj.toggle_vote(request.user, UserVote.UP_VOTE if is_upvote else UserVote.DOWN_VOTE) … -
Configure Apple login in Django rest framework with Allauth and rest-auth
I'm using Django + Django Rest Framework for a project for RESTful services to a mobile APPs. Now I have to integrate Apple-login. For social-login I already using Allauth + Allauth Socialaccount + rest-auth for Facebook login. As reported into Allauth documentation, it seams that supports Apple also. Reading the documentation I read that It's necessary to configure it (into Django settings) using something like this: SOCIALACCOUNT_PROVIDERS = { "apple": { "APP": { # Your service identifier. "client_id": "your.service.id", # The Key ID (visible in the "View Key Details" page). "secret": "KEYID", # Member ID/App ID Prefix -- you can find it below your name # at the top right corner of the page, or it’s your App ID # Prefix in your App ID. "key": "MEMAPPIDPREFIX", # The certificate you downloaded when generating the key. "certificate_key": """-----BEGIN PRIVATE KEY----- s3cr3ts3cr3ts3cr3ts3cr3ts3cr3ts3cr3ts3cr3ts3cr3ts3cr3ts3cr3ts3cr 3ts3cr3ts3cr3ts3cr3ts3cr3ts3cr3ts3cr3ts3cr3ts3cr3ts3cr3ts3cr3ts3 c3ts3cr3t -----END PRIVATE KEY----- """ } } } I'm trying to make a first test using the already described libraries: I added my url: url(r'^api/v1/users/applelogin', AppleLoginAPIView.as_view(), name='applelogin-user-url'), I created my view: class AppleLoginAPIView(SocialLoginView): adapter_class = AppleOAuth2Adapter callback_url = 'https://www.example.com' client_class = AppleOAuth2Client Trying this first test I have some errors and I discovered that It's necessary to create … -
Create object if form querysets only each have 1 result in Django CreateView?
I've got a model that is tied very closely to a few related models. Ultimately I have a generic CreateView for this model which works great: class EvaluationCreateView(CreateView): """ Display the form to create a new :model:`evaluations.Evaluation` **Template:** :template:`evaluations/evaluation_create.html` """ model = Evaluation fields = [ "evaluation_type", "evaluation_level", ] def get_form(self, *args, **kwargs): form = super(EvaluationCreateView, self).get_form(*args, **kwargs) slug = self.kwargs["slug"] # Using the slug from the URL try and get the EvaluationType evaluation_type = get_object_or_404(EvaluationType, slug=slug) # Set the queryset to this evaluation_type form.fields[ "evaluation_type" ].queryset = EvaluationType.objects.filter(id=evaluation_type.id) # Get the related EvaluationLevels to this EvaluationType evaluation_levels = evaluation_type.evaluation_levels.all() # There are no levels for this type - kick off error and 404 if not evaluation_levels: raise Http404( "Sorry, there was an issue with that EvaluationLevel" ) # There is only 1 Type & Level - Create the object and redirect to it if evaluation_levels.count() < 2: # TODO: Logic to create the object and redirect here form.fields["evaluation_level"].queryset = evaluation_levels return form def form_valid(self, form): summative = get_object_or_404( Summative, id=self.kwargs["summative_id"] ) creator_id = get_object_or_404(User, id=self.request.user.id) form.instance.summative = summative form.instance.created_by = creator_id form.instance.updated_by = creator_id return super(EvaluationCreateView, self).form_valid(form) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) You can see in the get_form … -
Django how to reverse a OneToOne relationship models.CASCADE
class BorrowDetails(models.Model): BorrowDate = models.DateField() class Book(models.Model): Title = models.CharField(max_length=30) BorrowDetails = models.OneToOneField(BorrowDetails, on_delete=models.CASCADE, null=True) Is there a way to make it so that when a Book gets deleted then BorrowDetails gets deleted instead of the other way around? I don't want to assign the OneToOne in the BorrowDetails as I want the JSON for my Book to contain BorrowDetails -
Framework for building a site for collaborative blogging with non-techy friends
So my question might be a little vague, but I'm really interested in hearing your take on this. For a while now I've been thinking on building a blog(-ish) website for me and some friends who are not at all into coding. And only we would have access to that site. Now I'm not a huge front- nor backend expert, however I'm super motivated to dive in any kind of framework. Up to now I tried blogdown and the HUGO as kind of a static, but easy approach. To my knowledge this is not made to provide some kind of login-capabilites in order to restrict the access. I could provide them write access for example to the github-repo in order to make posts. But my idea is more like writing the post on the site directly instead of writing it locally and then pushing it to github. I then tried to mess around a bit with python and Django. This looks really promising, but there are so many concepts to grasp that I first wanted to ask here before reading even more on that. Than there is fastpages for python, but again it looks more like a static site generator … -
How to send user account confirmation email if link has expired or account is inactive, using django-allauth
django-allauth customization question: If a user signed up but didn't, for some reason, either receive the email confirmation link or didn't click on it soon enough, I want the user to be able to make a request to receive another confirmation link. Currently, the default is a redirect to inactive_account.html and does not allow the user to request another confirmation link. How can I manually invoke send_email_confirmation in such instances (or in any instance)? -
Stripe with Django - Retrieve product / price from Session
I'm integrating Stripe Checkout with my django website. I have 2 products and everytime a PaymentIntent is successful, I want to fetch the Price related (the product that was bought). I have 2 checkouts, one for each product, and a webhook to listen. views.py - Create a purchase session (exist twice for product 1 & 2) @csrf_exempt def create_checkout_session_product1(request): if request.method == 'GET': domain_url = 'example.com' checkout_session = stripe.checkout.Session.create( success_url=domain_url + 'paiement_ok/', cancel_url=domain_url + 'paiement_ko/', payment_method_types=['card'], line_items=[ { "price" : "price_1...", <----- What I want to fetch "quantity": 1, }, ], mode='payment', customer_email=request.user.get_username(), ) return JsonResponse({'sessionId': checkout_session['id']}) views.py - Webhook to trigger a process after a purchase @csrf_exempt def webhook(request): payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None try: event = stripe.Webhook.construct_event( payload, sig_header, endpoint_secret ) except ValueError as e: # Invalid payload return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: # Invalid signature return HttpResponse(status=400) # Handle the checkout.session.completed event if event['type'] == 'checkout.session.completed': session = event['data']['object'] #then I'd want to do something like : line_items = stripe.checkout.Session.list_line_items(session.id) price = line_items.data.price.id if price == product1: activate_process_product1(session.customer_email) elif price == product2: activate_process_product2(session.customer_email) # Passed signature verification return HttpResponse(status=200) So the webhook works since I get the money. But I don't get … -
How to get Latitude and Longitude from Django Location PointField
Please how do i get the latitude and longitude from Django Location PointField, as i need it pass it to React native. This is what i mean, when i log my location, this is what i get "location": "SRID=4326;POINT (4.570313 7.013668)", and its obviously the lat and long that is there. But i need to extra it from the logged out. I dont know how to go about it please. Or is there a better way to have get location into django, and extra it for the frontend with reactnative? -
How do I configurate nginx with backend and frontend?
I have a simple vue.js and django (as REST API) application that I want to combine with nginx. Currently the frontend is working, but the backend is not. Here's my nginx config: server { listen 80; location / { root /usr/share/nginx/html/; index index.html index.htm; } location /api { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-NginX-Proxy true; proxy_pass http://localhost:8000/; proxy_ssl_session_reuse off; proxy_set_header Host $http_host; proxy_cache_bypass $http_upgrade; proxy_redirect off; } } Visiting localhost works for the static files, but localhost/api leads to a bad gateway error: [error] 29#29: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.18.0.1, server: , request: "GET /api HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "localhost" Also, trying to visit localhost/api via the frontend (axios) just returns the 'You need javascript to display this page' site, which is just part of the frontend. Running the backend seperately, outside of docker and nginx, works fine on localhost:8000. What can I do to make it work? It doesn't necessarily have to be done this way, as long as the frontend and backend can communicate. -
Is there a way to render a request within an if Statement in django?
I am trying to write a django web application for Reversi Game. I have a problem with rendering the new table to the website. views.py def table(request): if request.method == "POST": coord = request.POST.keys() crd = list(coord)[1] x = crd.split("_") r = int(x[0]) - 1 c = int(x[1]) - 1 reversi = ReversiGame() grid = draw_grid(reversi) ctxt = {"table": grid} return render(request, 'table.html', context=ctxt) template {% extends 'base.html' %} {% block main_content %} <div style="text-align: center; width: auto; height:auto; margin-right:auto; margin-left:200px;"> {% for r in table %} <div style="float:left"> {% for c in r %} <form action="" method="post"> {% csrf_token %} {% if c == 2 %} <input type="submit" style="background: #000000; width:50px; height:50px; color:white;" name="{{forloop.counter}}_{{forloop.parentloop.counter}}" value="2"> {% elif c == 1 %} <input type="submit" style="background: #ffffff; width:50px; height:50px;" name="{{forloop.counter}}_{{forloop.parentloop.counter}}" value="1"> {% else %} <input type='submit' style="background: #c1c1c1; width:50px; height:50px;" name="{{forloop.counter}}_{{forloop.parentloop.counter}}" value="o"> {% endif %} </form> {% endfor %} </div> {% endfor %} </div> {% endblock %} urls.py urlpatterns = [ path('', views.HomeView.as_view(), name="home"), path('signup/', views.SignUpView.as_view(), name='signup'), path('profile/<int:pk>/', views.ProfileView.as_view(), name='profile'), path('table/', views.table, name='table') ] When I try to return a HttpResponse within the request.method, the following error is being raised: The view GameConfiguration.views.table didn't return an HttpResponse object. It returned None … -
prepoluate a generec createview
i want that a form is prepoluate with data my model: TYPE = (("S",'Swing'), ("R","Rapide")) class valuation(models.Model): stock = models.ForeignKey("stock",on_delete=models.CASCADE,related_name='valuation',) date = models.DateField(auto_created=True) val_type = models.CharField(choices=TYPE, max_length=1,default='R') user = models.ForeignKey("users.User", on_delete=models.CASCADE) def __str__(self): return f"{self.stock} - {self.date} - {self.val_type}" my view: class valuationCreateviewSwing(CreateView): template_name = "evaluation/evaluation_create.html" form_class = valuationModeform def get_form_kwargs(self): # prepopulate form kwargs = super(valuationCreateviewSwing, self).get_form_kwargs() stck = get_object_or_404(stock, pk=self.kwargs['pk']) kwargs['user'] = self.request.user kwargs['val_type'] = "S" kwargs['stock'] = stck return kwargs def get_context_data(self, **kwargs): # we need to overwrite get_context_data # to make sure that our formset is rendered data = super().get_context_data(**kwargs) if self.request.POST: data["val_detail"] = ChildFormset1(self.request.POST) else: data["val_detail"] = ChildFormset1() data.update({ "typeVal": "Swing",}) return data def form_valid(self, form): context = self.get_context_data() val_detail_Swing = context["val_detail_Swing"] self.object = form.save(commit=False) # add data info neede about valuation model self.object = form.save() if val_detail_Swing.is_valid(): val_detail_Swing.instance = self.object val_detail_Swing.save() return super().form_valid(form) def get_success_url(self): return reverse("stock:stock-list") I've a child form in my view (this part works ok): ChildFormset1 = inlineformset_factory( valuation, val_detail_Swing, form=valuationSwingModelform, can_delete=False) I tried to use ge_for_kwargs but it seems not working as I've an error message : init() got an unexpected keyword argument 'user'