Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django redirect to a link crossing views
The situation is like this. When an anonymous user visits a secret view, I used the @login_required decorator which can redirect the user to login view and then back to the secret view after successful login. However, I provided a link to the signup view, in case the user doesn't have an account. After the new account is created, it will be redirected back to the login view and asked for initial login. The problem is the @login_required decorator is not going to work in the new login view. How can I redirect the user to the secret view after firstly clicking a link in the first shown login view then submiting the signup form? Some points to be clear: I have set a default LOGIN_REDIRECT_URL for going to the login page directly, so I don't want to change it this way. Successful signup will redirect to login. -
Django renders template blocks in wrong order
I have a problem with rendering templates in Django. Blocks don't seem to appear in the DOM position they were defined in. Here is my code: I'm using a base template (base.html): <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Partwell Transactional Email</title> <style> ... </style> </head> <body> <span class="preheader">Partwell email</span> <table role="presentation" border="0" cellpadding="0" cellspacing="0" class="body"> <tr> <td>&nbsp;</td> <td class="container"> <div class="content"> <!-- START MAIN CONTENT AREA --> <div class="content-main"> {% block content %} {% endblock content %} {% block content_extended %} {% endblock content_extended %} </div> <!-- END MAIN CONTENT AREA --> {% block unsubscribe %} {% endblock unsubscribe %} <!-- START FOOTER --> <div class="footer"> <table role="presentation" border="0" cellpadding="0" cellspacing="0"> <tr> <td class="content-block"> {% block behalf %} {% endblock behalf %} </td> </tr> <tr> <br /> <span class="apple-link">********Amtsgericht Charlottenburg *********</span> <span class="apple-link">&nbsp;*****</span> <br /> </tr> </table> </div> <!-- END FOOTER --> </div> </td> <td>&nbsp;</td> </tr> </table> </body> </html> And a template that extends the base template. This template is also a base template for all transactional emails (tenant-base.html): {% extends "base.html" %} {% block behalf %} This email was sent on behalf of {{ tenant.name }}. {% endblock behalf %} Ultimately, I'm … -
Django rest framework, bulk delete
I'm working on small project using Django Rest Framework, i would like to delete multiple IDs but i get always an error when i send a delete request by sending IDs /1,2,3,4 as a string, i get id must be an integer. this is my code, class UpdateDeleteContact(APIView): def get(self, request, pk): contactObject = get_object_or_404(Contact, pk=pk) serializeContactObject = ContactSerializer(contactObject) return Response(serializeContactObject.data) def delete(self, request, pk): delete_id = request.get('deleteid', None) if not delete_id: return Response(status=status.HTTP_404_NOT_FOUND) for i in delete_id.split(','): get_object_or_404(User, pk=int(i)).delete() return Response(status=status.HTTP_204_NO_CONTENT) can someone give me an example how to bulk delete -
How do I get this navbar-brand centered on the navbar?
I have tried to get this navbar-brand item centered on the navbar but nothing has worked so far. Can someone help? <nav class="navbar navbar-expand-md navbar-light bg-light mb-4 border"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span></button> <a class="navbar-brand" href="{% url 'a_better_place:home' %}"> A Better Place</a> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link" href="{% url 'a_better_place:contact' %}"> Contact</a></li> </ul> </div> -
how to prevent data from being repeated in the template even though the context is being nested
I am trying to implement an upvote and downvote functionality in my website. I am getting the data in two's and i think this reason is because the suppliers_votes_count is being nested in the suppliers data cominf from the view. How can I avoid this please. This is an image that shows the template And a proof for this is that if i print the result outside of the loop, it works normally. To understand the question better, check the view-supplier.html, you will t=see this {% for vote in suppliers_votes_count %} being nested in this {% for supplier in suppliers %}. I think this is what causes that. views.py def Viewsupplier(request): title = "All Suppliers" suppliers = User.objects.filter(user_type__is_supplier=True) # Get the updated count: suppliers_votes_count = {} for supplier in suppliers: upvote_count = supplier.upvotes downvote_count = supplier.downvotes supplier_count = {supplier: {'upvote': upvote_count, 'downvote': downvote_count } } suppliers_votes_count.update(supplier_count) context = {"suppliers":suppliers, "title":title, "suppliers_votes_count": suppliers_votes_count} return render(request, 'core/view-suppliers.html', context) view-suppliers.html <table class="table table-borderless table-data3"> <thead> <tr> <th>No</th> <th>Email</th> <th>Votes</th> </tr> </thead> <tbody> {% for supplier in suppliers %} <tr> <td>{{forloop.counter}}</td> <td>{{supplier.email}}</td> <td> <div class="table-data-feature"> <a href="{% url 'upvote' supplier.id %}" class="m-r-10"> <button class="item" data-toggle="tooltip" data-placement="top" title="Like"> <i class="zmdi zmdi-thumb-up">&nbsp; {% for vote in … -
Django manytomany field holding Users autofilling
I am pulling data from a json file on the web, and updating it in my django database. I want to keep track of users that are associated with each team, but as soon as a user loads the page once they are added to the model. How do I avoid this? class Team(models.Model): name = models.CharField(max_length=120) abbreviation = models.CharField(max_length=3) id = models.IntegerField(primary_key=True) link = models.CharField(max_length=120) wins = models.IntegerField(default=0) losses = models.IntegerField(default=0) ties = models.IntegerField(default=0) points = models.IntegerField(default=0) users = models.ManyToManyField(User) def getTeams(): import requests baseUrl = "https://statsapi.web.nhl.com/" # INITALIZING THE DATA IN THE DATA DICTIONARY r = requests.get(baseUrl + '/api/v1/teams') originalData = r.json() # i dont need the copyright, only care about the teams originalData = originalData["teams"] for team in originalData: id = team["id"] try: databaseTeam = Team.objects.get(id = id) except Exception: Team.objects.create(id = id) databaseTeam = Team.objects.get(id = id) databaseTeam.name = team["name"] databaseTeam.abbreviation = team["abbreviation"] databaseTeam.link = team["link"] databaseTeam.save() print("done") @login_required def myTeamView(request): t1 = Thread(target=getTeams) t1.start() return(render(request, "teams/myTeams.html", {})) -
No migrations to apply but no such table after migration
I created Django model named Comparison and also generated migration file. When I run migrate, Django says there is no migrations to apply however when I access the model page form admin site it shows 'no such table' error. I browsed DB using 'DB Browser for SQLite' and there seem to be no table named comparison. I probable have made then same named model before and deleted but it should be deleted and is deleted as I browse DB. I'm stuck since usually when django shows no migrations to apply, I should fix it by deleting existing table with the name but there aren't any table to delete. from django.db import models from apps.tag.models import Tag class Comparison(models.Model): topic = models.ForeignKey(Tag, null = True, blank = False, on_delete = models.CASCADE, related_name = 'comparisons') from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('tag', '0013_auto_20201010_2219'), ] operations = [ migrations.CreateModel( name='Comparison', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('topic', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='comparisons', to='tag.Tag')), ], ), ] -
SyntaxError: invalid syntax in polls//urls.py . Why do i get this error?
I'm using django 3.1.7 and following it's create app documentation. I'm stuck at part 3 because it gives syntax error. Here is the urls.py: from django.urls import path from polls import views urlpatterns = [ path('',views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results/'), views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] Error: (rookieCoderEnv) C:\Users\ORCUN\OneDrive\Masaüstü\WebDeveloperBootcamp\DjangoProject\rookieCoder>py manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\ORCUN\anaconda3\envs\rookieCoderEnv\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\ORCUN\anaconda3\envs\rookieCoderEnv\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\ORCUN\anaconda3\envs\rookieCoderEnv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\ORCUN\anaconda3\envs\rookieCoderEnv\lib\site- packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\ORCUN\anaconda3\envs\rookieCoderEnv\lib\site- packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\Users\ORCUN\anaconda3\envs\rookieCoderEnv\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 786, in exec_module File "<frozen importlib._bootstrap_external>", line 923, in get_code File "<frozen importlib._bootstrap_external>", line 853, in source_to_code File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\ORCUN\OneDrive\Masaüstü\WebDeveloperBootcamp\DjangoProject\rookieCoder\polls\urls.py", line 7 path('<int:question_id>/results/'), views.results, name='results'), ^ SyntaxError: invalid syntax "C:\Users\ORCUN\OneDrive\Masaüstü\WebDeveloperBootcamp\DjangoProject\rookieCoder\polls\urls.py", line 7 path('int:question_id/results/'), views.results, name='results'), What is the thing that I'm missing about name? How … -
Django: Cache / History / Logging User Query Requests
I'm a beginner and this is my first first Django project. My task is to find out what queries users enter in the search on the site according to my model, write them in a separate table in the database (PostgreSQL) as a string, in the future I want to create tags for these words and bind them to my records in the model. There are no problems with tags, but it's a problem with saving the search history. I have been looking for a long time and as logging, as history, as a cache, and gives out everything that is not at all what is needed. Any help on how this can be done in Django, maybe I'm missing something? -
Django filter empty fields
Currently I am filtering empty fields in all entries of the queryset like this: data_qs = DataValue.objects.filter(study_id=study.id) #queryset opts = DataValue._meta # get meta info from DataValue model field_names = list([field.name for field in opts.fields]) # DataValue fields in a list field_not_empty = list() # list of empty fields for field in field_names: for entry in data_qs.values(field): if entry.get(field) is not None: field_not_empty.append(field) break It works but not sure if it is an appropriate solution.... Does anyone know how to filter empty values in all the queryset? The table have more than 30 fields, so depending on the study ID some querysets may contain the field1 all empty, other study ID may contain all the field2 empty. Does the Django ORM provide an easy an clean solution to do this? Thanks in advance -
How can I automatically login user after successful registration with redux saga
I am using redux-saga in next.js. This is the registration functions for saga. // this function is registered and waiting for USER_REGISTER_START export function* userRegisterStart() { yield takeLatest(UserActionTypes.USER_REGISTER_START, onRegisterStart); } I dispatch "USER_REGISTER_START" inside register page: const submitHandler = (e: React.FormEvent) => { e.preventDefault(); if (password !== confirmPassword) { setMessage("Passwords do not match"); } else { dispatch(userRegisterStart({ name, email, password })); } }; after the dispatching the start process, this function gets fired by redux-saga export function* onRegisterStart(action: StartRegisterAction) { const { name, email, password } = action.payload; try { const config = { headers: { "Content-type": "application/json" } }; const { data } = yield axios.post( `${process.env.DJANGO_API_URL!}/api/users/register/`, { name, email, password }, config ); console.log("data", data); yield put(userRegisterSuccess(data)); yield put(userLoginSuccess(data)); // attempt to login Router.push("/"); } catch (e) { yield put(userRegisterFailure(e.message)); } } User is successfully registered, i get the data from django, and checked the admin panel. However I could not figure out how to make user logged in. I fired this right after successful registration yield put(userLoginSuccess(data)); But this did not work. -
How to enter data into the fields of model class to html table?
I have a model class 'Client' that has multiple fields. for example (installment_month, installment_amount, installment_date). I am taking these three inputs from user using addinstallment_form.html. My model.py and addinstallment.html are given below: models.py class Client(models.Model): name = models.CharField(max_length = 100) dob = models.SlugField(max_length = 100) CNIC = models.SlugField(max_length = 100) property_type = models.CharField(max_length = 100) down_payment = models.IntegerField() date_posted = models.DateTimeField(default=timezone.now) installment_month = models.CharField(max_length = 100) installment_amount = models.IntegerField(null=True) installment_date = models.SlugField(max_length = 100, null=True) addinstallment.html {% extends "property_details/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content_section"> <form method="post"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4"> Add New Installment</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Add Installment</button> </div> </form> </div> {% endblock %} And there is one more view in which I am printing the entered fields in table. and table has three columns (installment_date, installment_month, installment_amount). When I enter the data it saves this in respective columns of the table. But when I want to add installment for the client 2nd time, then it replaces the data entered before. my html file where I set my table is given below: client_details.html {% extends "property_details/base.html" %} {% block content %} <legend class="border-bottom mb-4"><h3>{{ … -
how to send the firebase token at the django backend with vue?
i can't send the firebase token to the backend, i thought the problem was that the function was not asynchronous but it still didn't work for me, please i need help, thanks! user.getIdToken(true) .then(function(idToken) { const path = 'http://localhost:8000/api/google-login' console.log(idToken) axios.post(path , idToken) .then((response) => { console.log('anda o no anda') }) .catch((error) => { console.log(error); }); }).catch(function(error) { console.log(error) }); the error in console. POST http: // localhost: 8000 / api / google-login 500 (Internal Server Error) but if I copy the idtoken and send it manually to the backend it works. -
How to configure .htaccess for Django and React?
I have this .htaccess # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION BEGIN PassengerAppRoot "/home/user/repositories/Snow-API" PassengerBaseURI "/" PassengerPython "/home/user/virtualenv/repositories/Snow-API/3.7/bin/python3.7" PassengerAppLogFile "/home/user/logs/djangoapi" # DO NOT REMOVE. CLOUDLINUX PASSENGER CONFIGURATION END # DO NOT REMOVE OR MODIFY. CLOUDLINUX ENV VARS CONFIGURATION BEGIN <IfModule Litespeed> SetEnv SECRET_KEY </IfModule> # DO NOT REMOVE OR MODIFY. CLOUDLINUX ENV VARS CONFIGURATION END AddHandler 000-default .conf Options -MultiViews RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.html [QSA,L] How do I enter the condition that when going to the subdomain api.domain.com or domain.com/api, I can go to the project API? -
How can I get a list of "ProductoSeralizer" in my "UsuarioSerializer" Django
I need the products that each user has ordered, like in the "UsuarioSerializer" i was thinking to put a field "productos" which is a list of "ProductoSeralizer", but the model "Usuario" do not have a direly relación with "ProductoSeralizer", so it give me an error when I try that, how can solve this? I need a JSON response like this: [ { "id": 1, "cantidad_de_productos": 12, "fecha": "2021-03-21T06:26:26.981487Z", "correo": "user1@email.com", "password": "pass", "productos" : [ {}, {} ] }, { "id": 2, "cantidad_de_productos": 0, "fecha": "2021-03-21T06:26:56.700399Z", "correo": "user2@email.com", "password": "pass", "productos" : [ {}, {} ] } ] models.py class Entidad(models.Model): fecha = models.DateTimeField(auto_now=True) class Meta: abstract = True class Usuario(Entidad): correo = models.EmailField(unique=True) password = models.CharField(max_length=20) def __str__(self) -> str: return self.correo class Orden(Entidad): solicitante = models.ForeignKey(Usuario, related_name='ordenes', on_delete=models.CASCADE) productos = models.ManyToManyField('Producto', through='Detalle') class Producto(Entidad): nombre = models.CharField(max_length=20, unique=True) ordenes = models.ManyToManyField('Orden', through='Detalle') def __str__(self) -> str: return self.nombre class Detalle(Entidad): cantidad = models.PositiveIntegerField() orden = models.ForeignKey(Orden, related_name='detalles', on_delete=models.CASCADE) producto = models.ForeignKey(Producto, related_name='detalles', on_delete=models.CASCADE) serializers.py class ProductoSerializer(serializers.ModelSerializer): class Meta: model = Producto fields = '__all__' class ProductosUsuarioSerializer(serializers.ModelSerializer): cantidad = models.IntegerField() class Meta: model = Producto fields = '__all__' class DetalleOrdenSerializer(serializers.ModelSerializer): class Meta: model = Detalle exclude = ['orden'] class … -
Django DetailView and Update related on same Form
I have two models that are related. The first model - Program , has a bunch of files that I want to display because some of the fields are computed based on the second model. The second model is called Segments - and is related by the Program ID Field. There can be zero or more segments. I need to display the Program fields, and all of the current segments. Within each segment you have the ability to edit a segment. When the user clicks that, I display a detail form (much like the one they are on) but the applicable Segment should show up as an Update form. The tricky thing is - I only want the segment that was clicked to be on a segment update form, the rest of the segments should display as 1 line summaries. The models look like this.. class Program(models.Model): air_date = models.DateField(default="0000-00-00") air_time = models.TimeField(default="00:00:00") service = models.CharField(max_length=10) block_time = models.TimeField(default="00:00:00") block_time_delta = models.DurationField(default=timedelta) running_time = models.TimeField(default="00:00:00") running_time_delta = models.DurationField(default=timedelta) remaining_time = models.TimeField(default="00:00:00") remaining_time_delta = models.DurationField(default=timedelta) title = models.CharField(max_length=190) locked_flag = models.BooleanField(default=False) deleted_flag = models.BooleanField(default=False) library = models.CharField(null=True,max_length=190,blank=True) mc = models.CharField(null=True,max_length=64) producer = models.CharField(null=True,max_length=64) editor = models.CharField(null=True,max_length=64) remarks = models.TextField(null=True,blank=True) audit_time = … -
How can I run nginx server automatically
I have a django web app on google cloud compute engine and this is its link: delam.shop and it uses NGINX web server. but they force me to type runserver command each time I want to access to the app.. So how can I make the app run automatically all the day! Is there any way someone can tell me to do it! thanks in advance -
When activating virtualenv still global dependencies are installed
I am having issues with virtualenv installations on a mac. First change to the directory and activate virtualenv cd my-project/ virtualenv venv source venv/bin/activate Second...my terminal changes to the virtualenv and install Django version 3.1.7 (venv) andrescamino@Robertos-MacBook-Pro WJKTM % pip install Django==3.1.7 To make sure the installation is on the virtualenv i make a pip freeze and these are the results (venv) andrescamino@Robertos-MacBook-Pro WJKTM % pip freeze asgiref==3.3.1 Django==3.1.7 pytz==2021.1 sqlparse==0.4.1 Then I start the project (venv) andrescamino@Robertos-MacBook-Pro WJKTM % django-admin startproject bandsite However when I go to the editor and check the settings file...it still shows the version installed globally which is the 3.1.2 Generated by 'django-admin startproject' using Django 3.1.2. Am i missing something? -
Displaying foreign key in django admin panel
I cant seem to find the correct answer to display 1 foreign key value: it displays "house label" in the correct "table" it displays the value. but it does not give the perfect "column" name. i would love to display "house_name" in the table.. any idea's? admin.py from django.contrib import admin from .models import UserProfile,House # Register your models here. class UserProfileAdmin(admin.ModelAdmin): def house_label(self, obj): return obj.house.house_name list_display = ('user', 'api_key','house_label') admin.site.register(UserProfile,UserProfileAdmin) admin.site.register(House) models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class House(models.Model): house_name = models.CharField(max_length=500,blank=False, null = False) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name ="profile") api_key = models.CharField(max_length=500, blank=False, null = False) house = models.ForeignKey(House, on_delete=models.CASCADE, related_name = "house") -
Django overriding ModelAdmin classes with a function requiring Model name
In my admin.py, I have a lot of ModelAdmin classes and I want them to all override a function, has_module_permission. I want to base the module permission off of the user's permissions for the model corresponding to the ModelAdmin, and to do that I need to know the model name in order to run request.user.has_perm('app.add_<model>') or something similar. I think an easy way of doing this is to create a class that has this function which is somehow able to get the model name, and then have each of the ModelAdmin classes inherit from that. The problem is that I don't know how to access the model's name from ModelAdmin. What's the best way of doing this? -
Model field not updating in admin page even if value changes
I apologize for my confusing title but I hope the code explains it better. In my views.py file I have the follow view def create_view(request): context = {} form = CreateForm(request.POST) if request.method == "POST": if form.is_valid(): instance = form.save(commit=False) instance.author = request.user instance.save() instance.author.profile.participating_in = Post.objects.get( title=instance.title ) instance.save() print(instance.author.profile.participating_in) context["form"] = form return render(request, "post/post_form.html", context) when I print out the value of instance.author.profile.participating_in it shows up in my terminal however when I check the admin page it doesnt update at all. I'm sure I messed up somewhere silly but I cant seem to find it. Thanks! -
Check if item exists in database by field value
I have a class called Product and I want to check if there is already a product in the database with the same title. class Product(models.Model): title = models.CharField(max_length=255) ... for (something in something): check if db contains product with a title of 'Some Product' -
Limit django channels connections
I'm building some simple django sockets with channels. How can I limit the number of simultaneous connections accepted? Something like class BridgeConsumer(WebsocketConsumer): def connect(self): print('Bridge connected') # Accept only if there are at most N connections self.accept() def disconnect(self, close_code): print('Bridge disconnected') This seems trivial but I was unable to find an answer Thanks -
Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data, how can I resolve this error [closed]
I am trying to fetch data from django with JS, but I get the error, and I cannot find where the problem is can anyone help. Using Dango admin I have sample post for the application but fetching the data is problematic. The html <body> <div id="posts"></div> <script src="{% static 'network/network.js' %}"></script> </body> The JS Code document.addEventListener("DOMContentLoaded", displayPost) function displayPost(){ const post_item = document.createElement('div') fetch('/allPost') .then(response => response.json()) .then(posts => { //console.log(posts); posts.forEach(function(post){ postContent = `<div> <p>${post.poster}</p> <p>${post.content}</p> <p>${post.datetime}</p> <p>${post.like}</p> </div>` post_item.innerHTML =postContent; document.querySelector('#posts').append(post_item); }); }); } the url.py urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("newPost", views.new, name="new"), path("allPost", views.allPost, name="allPost"), ] the view.py def allPost(request): posts = Posts.objects.all() posts = posts.order_by("-dateTime").all() return JsonResponse([post.serialize() for post in posts], safe=False) the models.py class Posts(models.Model): posterUsername = models.ForeignKey(User, on_delete=models.CASCADE, related_name="post_creator") postContent = models.CharField(max_length=64) dateTime = models.DateTimeField(auto_now_add=True) like = models.IntegerField() # def __str__(self): # return self.id def serialize(self): return { "id": self.id, "poster": self.posterUsername, "dateTime": self.dateTime.strftime("%b %d %Y, %I:%M %p"), "like": self.like } -
Django Form Will Not Validate On Ubuntu/Apache2
I've been having some trouble getting this form to be valid. I've been able to get it to run locally and on Heroku. However, I am now trying to get it to run on Ubuntu/Apache2 and the form will not validate. This is sample of my form and view. The date1 and date2 variables get plugged into an API request, however, since the form is not valid, I keep getting a local variable is referenced before its assignment. #****** Form ******# class RequestForm(forms.Form): start_date = forms.DateTimeField(input_formats=["%Y %m %d %H:%M:%S"],widget=forms.TextInput(attrs={ 'class':'form-control inputDate ', 'type': 'datetime-local' })) end_date = forms.DateTimeField(input_formats=["%Y %m %d %H:%M:%S"],widget=forms.TextInput(attrs={ 'class':'form-control inputDate', 'type': 'datetime-local' })) #****** END Form ******# #*********** View *****************# class ReportView(TemplateView): template_name = 'reports/report.html' def get(self, request): form = RequestForm() return render(request, self.template_name, {'form': form}) def post(self, request): form = RequestForm(request.POST) if form.is_valid(): date1 = form.cleaned_data['start_date'].strftime("%Y-%m-%d %H:%M:%S") date2 = form.cleaned_data['end_date'].strftime("%Y-%m-%d %H:%M:%S") url = "****" payload = "{\"request\": {\"method\": \"switchvox.callLogs.search\", \"parameters\": {\"start_date\": \""+date1+"\", \"end_date\": \""+date2+"\", \"account_ids\": [\"1139\",\"1140\",\"1143\"], \"sort_field\": \"start_time\", \"sort_order\": \"ASC\", \"items_per_page\": \"8000\", \"page_number\": \"1\"}}}" headers = { 'User-Agent': 'curl/7.47.1', 'cookie': "lang_locale=en_us", 'Content-Type': "application/json", 'Authorization': "******" } urllib3.disable_warnings() response = requests.post(url, data=payload, headers=headers, verify=False) call_report = response.json() print(type(call_report)) itemBank = [] for i in call_report["response"]["result"]["calls"]["call"]: itemBank.append(( i["uniqueid"], …