Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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' -
Getting one-to-many relationship data both ways in Django REST Framework
I'm using Django REST Framework to create the following endpoints: /tenants/ ➞ lists all tenants and includes in the json response the attributes of the Building model they live in. /buildings/ ➞ lists all buildings and includes in the json response the attributes of the Tenants that live in them. My models are: class Building(models.Model): address = models.CharField(max_length = 200) zipcode = models.IntegerField() city = models.CharField(max_length = 100) class Tenant(models.Model): fname = models.CharField(max_length = 200) lname = models.CharField(max_length = 200) building = models.ForeignKey(Building, related_name = 'tenants', on_delete = models.CASCADE) My serializers look like so: class BuildingSerializer(serializers.HyperlinkedModelSerializer): class Meta: fields = ['id', 'address', 'zipcode', 'city'] class TenantSerializer(serializers.HyperlinkedModelSerializer): building = BuildingSerializer() class Meta: model = Tenant fields = ['id', 'fname', 'lname', 'building'] The /tenants/ endpoint works just fine, but I have no idea on how to include the tenants' data in the /buildings/ response. Could anyone give me a clue on this? -
Shared File Lock Python
Is there a way to implement a "Shared File Lock"? Let me explain the concept: A file lock called: GroupOfFeatures, within this lock I want a group of features to be able to run in parallel. So at the same exact time: CPU-1: Locks. Do the work. Unlocks. CPU-2 Locks. Do the work. Unlocks. The problem with a normal file lock is that on the case of CPU-2 before it unlocks it will be already unlocked by CPU-1. Here is the specific real world example. On a microservices architecture, I have 3 services: Costs, Sales and Administration. Costs - keep track of costs. Sales - keep track of sales. Administration - receives both by queues messaging and saves everything in one model/table. The problem that I have is that if I save costs and sales at the same time, it blocks the DB/deadlocks/etc. If I queue them in a single thread and process one first and the other after, then it is too slow. So the solution would be to allow N threads to import either costs or sales into administration, but not both at the same time. Something like this would happen: 10:00am - Receive costs for 1 account … -
I'm trying to deploy an open source app on kubernetes, but the authentication doesn't work when deployed on google cloud
I'm a total beginner, I haven't done anything like this before, so I'm sorry if this is a stupid question, but I couldn't find anything related. I'm trying to deploy a voting app on google cloud on kubernetes. The problem is that the app has almost non-existent documentation, so I don't know if I'm doing something wrong. When I host the app locally, everything works as expected, but when I deployed it on kubernetes when I try to log in, the server throws a 403. Does anyone know what could cause it? Here's the screenshot of the log 1 -
How to write a python calendar function that calls only one week instead of a whole month
I have a question if I am able to write a function that instead of displaying days for a given month would display only a particular week in the month i have something like this in my utils.py file def formatweek(self, theweek, events, ): week= '' for d, weekday in theweek: week += self.formatday(d, events, ) print() return f'<tr> {week} </tr>' def formatmonth(self, withyear=True, ): for week in self.monthdays2calendar(self.year, self.month): cal += f'{self.formatweek(week, events, )}\n' return cal I would appreciate any hints -
How to save excel / csv / dataframe for Django use?
I have a django model with relevant code as follows (question below the code): class Equity(models.Model): equity_name = models.CharField(max_length=255) geography_choices = [('Africa', 'Africa'), ('Asia', 'Asia'), ('Australia', 'Australia'), ('Europe', 'Europe'), ('North America', 'North America'), ('South America', 'South America')] geography = models.CharField(max_length=255, choices=geography_choices, default='North America') sector_choices = [('Communication Services', 'Communication Services'), ('Consumer Discretionary', 'Consumer Discretionary'), ('Consumer Staples', 'Consumer Staples'), ('Energy', 'Energy'), ('Financials', 'Financials'), ('Health Care', 'Health Care'), ('Industrials', 'Industrials'), ('Information Technology', 'Information Technology'), ('Materials', 'Materials'), ('Real Estate', 'Real Estate'), ('Utilities', 'Utilities')] sector = models.CharField(max_length=255, choices=sector_choices, default='Communication Services') def fundamental_list(self): l_fund = [] filtered_articles = Article.objects.filter(equity__industry = self.industry) for filtered_article in filtered_articles: if(filtered_article.equity.equity_name == self.equity_name): l_fund.append([filtered_article.get_fun_score(), filtered_article.get_date(), filtered_article.id, filtered_article.title, filtered_article.get_source()]) else: if (filtered_article.read_through == -1): l_fund.append([float(-1)*filtered_article.get_fun_score(), filtered_article.get_date(), filtered_article.id, filtered_article.title, filtered_article.get_source()]) if (filtered_article.read_through == 1): l_fund.append([filtered_article.get_fun_score(), filtered_article.get_date(), filtered_article.id, filtered_article.title, filtered_article.get_source()]) return l_fund class Article(models.Model): ticker = models.CharField(max_length=5, null=True) source = models.CharField(max_length=50, choices=source_choices, default='Argus') score_choices = [(-5,'-5'), (-4, '-4'), (-3,'-3'), (-2, '-2'), (-1,'-1'), (0,'0'), (1,'1'), (2,'2'), (3,'3'), (4,'4'), (5,'5')] fundamental_score = models.FloatField(choices=score_choices, default=0) sentiment_score = models.FloatField(choices=score_choices, default=0) #Fields for the read-through effect of a news item on related companies. read_through_choices = [(-1, 'Competitive'), (0, 'No Effect'), (1, 'Industry-Wide')] read_through = models.IntegerField(choices=read_through_choices, default=0) #here we attempt the foreign key method for equities possibly??? equity = models.ForeignKey(Equity, … -
Display a nice Django Crispy Forms Validation Error Message
I am trying to get this tutorial to working, but didn't manage to do so yet. My views.py def BlogCreateView(request): context = {} if request.method == 'POST': # create a form instance and populate it with data from the request: form = MessageForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: form.save() context['form']= form return render(request, 'post_new.html', context) else: form = MessageForm() return render(request, 'post_new.html', {'form': form}) My forms.py from django import forms from .models import Post from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit, Row, Column class MessageForm(forms.Form): title = forms.CharField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper(self) self.helper.form_show_labels = True super().__init__(*args, **kwargs) self.helper.form_method = 'POST' self.helper.layout = Layout( Row('title', css_class='form-control-lg'), ) My post_edit.html {% extends 'base.html' %} {% block content %} <h1>Edit Post</h1> <form class="blau" action="" method="post">{% csrf_token %} {{ form.title }} <input type="submit" name="" value="Update"> </form> {% endblock content %} The form seems to work, but I cannot modify/overwrite the pop-up alert which reminds the user to enter the correcht input. Is this even the right way to achieve this? I am open for any help. Thank you a … -
TemplateDoesNotExist at /en/user/login/ when tried to visit the login url in Django 2.2
I am upgrading a Django application from 1.11 to to 2.2. I have completed all the migrations and everything but I am facing this error constantly django.template.exceptions.TemplateDoesNotExist: registration/login.html. I am still currently learning Django apologies in advance if I am missing something stupidly simple. I have attached the error message picture here and the files that might be relevant to this error message. Just for clarification in my settings.py I have the following under TEMPLATES: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ "django.contrib.auth.context_processors.auth", "django.template.context_processors.debug", "django.template.context_processors.i18n", "django.template.context_processors.media", "django.template.context_processors.static", "django.template.context_processors.tz", "django.contrib.messages.context_processors.messages", "django.template.context_processors.request", ] } } ] Here are the othert files that might help debugging: urls.py from django.conf.urls import url, include from django.urls import reverse_lazy from userApp import views from django.contrib.auth import views as django_contrib_auth_views from django.contrib.auth.views import LoginView urlpatterns = [ url(r'^register/$', views.register, name='register'), url(r'^profile/$', views.profile, name='profile'), url(r'^login/$', views.rate_limit_login, name='login'), url(r'^rate_limited/$', views.rate_limited, name='rate_limited'), url(r'^logout/$', django_contrib_auth_views.LogoutView, {'template_name': 'userApp/logged_out.html', 'next_page': '/'}, name='logout'), url(r'^password_change/$', django_contrib_auth_views.PasswordChangeView, {'template_name': 'userApp/password_change_form.html', 'post_change_redirect': reverse_lazy('userApp:password_change_done')}, name='password_change'), url(r'^password_change/done/$', django_contrib_auth_views.PasswordChangeDoneView, {'template_name': 'userApp/password_change_done.html'}, name='password_change_done'), url(r'^password_reset/$', django_contrib_auth_views.PasswordResetView, {'template_name': 'userApp/password_reset_form.html', 'email_template_name': 'userApp/password_reset_email.html', 'post_reset_redirect': reverse_lazy('userApp:password_reset_done')}, name='password_reset'), url(r'^password_reset/done/$', django_contrib_auth_views.PasswordResetDoneView, {'template_name': 'userApp/password_reset_done.html'}, name='password_reset_done'), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', django_contrib_auth_views.PasswordResetConfirmView, { 'template_name': 'userApp/password_reset_confirm.html', 'post_reset_redirect': reverse_lazy('userApp:password_reset_complete')}, name='password_reset_confirm'), url(r'^reset/done/$', django_contrib_auth_views.PasswordResetCompleteView, {'template_name': 'userApp/password_reset_complete.html'}, name='password_reset_complete'), views.py from … -
Django admin prepopulate field based on the value from an save override in models
This problem has been frustrating me because I feel like I have all the pieces but just can't put it together. I'm pretty new to Django and web dev in general and so far it's mostly been pretty smooth. I'm building a simple form app where every form is going to have a unique URL via a randomly generated slug, and each form expires after about a week. Model Token has two fields, 1) tokenid, which is the random slug as well as the pk, and 2) a url field that is created using that slug. I also overrode the save method to get admin to spit out a new slug every time Add gets clicked. My goal was to have the URL field in Django admin to be prepopulated so it's easy for the person generating the form to be able to click, copy and paste. These forms are only going to be sent out after a face-to-face process so I'm not concerned about scalability. I'm aware that once the fields are saved to db, the full URL will appear in the URL field, but it seems like an extra step for managers to make mistakes. #Models.py def get_random_string(): …