Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Do I need a User Class in my models? Or is there an easy fix to the foreign key?
Made some modification to my code (there is was some mistake) which created a new problem. Pulling the following error message: "insert or update on table "main_productreview" violates foreign key constraint "main_productreview_user_id_bdd4771a_fk_main_user_id" DETAIL: Key (user_id)=(3) is not present in table "main_user"." (I used to have a User class in my models.py which I have removed as registered Users where not moved to Main. Removing the class sorted the problem, but created this one) What I am trying to do: when a user is logged in, the user can leave a review against a specific product. Any idea? Models.py from django.db import models from django.contrib.auth.models import User from decimal import Decimal import locale import logging class Product(models.Model): name = models.CharField('Product Name', max_length=120, null=True) description = models.TextField(blank=True, null=True) price = models.DecimalField(null=True, max_digits=6, decimal_places=3) #venue = models.ForeignKey(Venue, blank=True, related_name="venue", on_delete=models.CASCADE) tasters = models.ManyToManyField(User, blank=True) image_url= models.URLField('Image Web Address', blank=True) product_url = models.URLField('Product Web Address', blank=True) class Meta: db_table='Product' def __str__(self): return str(self.name) RATING=( (1,'1'), (2,'2'), (3,'3'), (4,'4'), (5,'5'), ) class ProductReview(models.Model): user=models.ForeignKey(User, on_delete=models.CASCADE) product=models.ForeignKey(Product,related_name="comments", on_delete=models.CASCADE) review_text=models.TextField(max_length=250) review_rating=models.IntegerField(choices=RATING,max_length=150, default=0) date_added = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s - %s - %s'%(self.user, self.product, self.date_added) Views.py from django.shortcuts import render, redirect from django.http import … -
Django Form/Models: Adding Row Data To Existing Model Instance Via Form
Description of Database Hello so my problem is that I have a Database with three models: Beacon: Which collects data about hosts that ping back data to it. Command_Node: Which collects commands to be executed by the host in question via a form submitted by the website user. Executed_Commands: Which will collect any Commands contained within a Command_Node when they are collected through a query by a connecting machine via a function to be implemented, it will also delete the Commands in a Command_Node as they are now previous commands. (To be implemented) Problem I want to add multiple commands to a single instance of a Command_Node. Via a form, which allows me to select which host I want to give commands to, and which allows me to select which commands to issue to which host. It should then adds those commands into the current_commands column of that Command_Node as a new row, in the selected Command_Node instance. However I don't know how to do this. I don't need to edit existing commands, I don't need to create a new Command_Node instance as the present code does. I just need to add more rows to existing instances. Any ideas on … -
django.core.exceptions.ImproperlyConfigured: Set the DB_NAME environment variable
I have some troubles. I'm running Django on Ubuntu 20.04. Everytime that I try to set environment variable instead of a string i get an error, when I use python3 manage.py runserver I am getting django.core.exceptions.ImproperlyConfigured: Set the DB_NAME environment variable and I am using docker , docker-compose . my config/settingsfile: env = environ.Env( DEBUG=(bool, False), ) DEBUG = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': env('DB_NAME'), 'USER': env('DB_USER'), 'PASSWORD': env('DB_PASSWORD'), 'HOST': env('DB_HOST'), 'PORT': 5432, } } EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = env('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD') SERVER_EMAIL = EMAIL_HOST_USER DEFAULT_FROM_EMAIL = EMAIL_HOST_USER BACKEND_DOMAIN = '' my .env file: DB_NAME=my_db_name DB_USER=postgres DB_PASSWORD=my_password EMAIL_HOST_USER=my_email_address EMAIL_HOST_PASSWORD=my_password OPENROUTE_API_KEY= MY FILES: enter image description here -
How can i get parameter from a url with django
i have this in the url: localhost/apli/orden/devices/Instalacion%20LB%20+%20BA/ so i need to get the parameter Instalacion%20LB%20+%20BA in a view, how can i do it? this is the url path: path('orden/devices/<str:tipoOrden>/', asignDevicesView.as_view(), name='devices_ot') I clarify that I do not use models where this info is saved, the info comes from a variable from js that I rescue from an object of a web service -
Add the result of a queryset to another queryset
I have 2 models : class ModelA(models.Model): some_fields = .... class ModelB(models.Model): model_a = models.ForeignKey(Model_A) How can I in my viewset of ModelA return a response which will include all ModelB who have model_a as FK ? Can I do it in the get_queryset function ? -
Architecture clarification for Warehouse Django application
everyone, I've started implementing my next project under the Warehouse title :) And actually, I am stuck, again. I guess I've made things too complicated and I don't know how to get out of it. So basic assumptions of Warehouse application: We have a few products You take the goods to the warehouse - the order consists of multiple products. You must know the purchase price and qty for each of them. Some model which will store information about current stock status. I guess it will be Singleton? You sell products from Warehouse - order consists of products sell price, product qty Ok, It seems to me all the above are basic assumptions, below is what I wrote to reach my target but I am pretty sure it doesn't work as is intended. I will be very grateful for any tips and tricks and clarification on architecture. class OrderIn(models.Model): # Standard fields last_updated = models.DateTimeField(auto_now=True, editable=False) ordered = models.DateField(auto_now_add=True, editable=True) received = models.DateField(auto_now_add=True, editable=True) class OrderOut(models.Model): # completed = models.BooleanField(default=False) # Standard fields last_updated = models.DateTimeField(auto_now=True, editable=False) ordered = models.DateTimeField(auto_now_add=True, editable=True) class MiddleOrder(models.Model): order_in = models.ForeignKey(OrderIn, on_delete=models.CASCADE, blank=True, null=True) order_out = models.ForeignKey(OrderOut, on_delete=models.CASCADE, blank=True, null=True) def save(self, *args, **kwargs): super(MiddleOrder, … -
NameError name 'F' is not defined
when i tried this code to add 10 point to user after he fill out one survey it show this error However, I am running into a problem. I get the error: models.py", line 22, in give_coins user.coins = F('coins') + count NameError: name 'F' is not defined models.py class User(AbstractUser): user_pic = models.ImageField(upload_to='img/',default="",null=True, blank=True) coins = models.IntegerField(default=10) def get_image(self): if self.user_pic and hasattr(self.user_pic, 'url'): return self.user_pic.url else: return '/path/to/default/image' def give_coins(user, count): user.coins = F('coins') + count user.save(update_fields=('coins',)) user.refresh_from_db(fields=('coins',)) views.py : @require_http_methods(["POST"]) def submit_survey(request): request.user.give_coins(count=10) form_data = request.POST.copy() form_items = list(form_data.items()) print("form_items", form_items) form_items.pop(0) # the first element is the csrf token. Therefore omit it. survey = None for item in form_items: # Here in 'choice/3', '3' is '<choice_id>'. choice_str, choice_id = item choice_id = int(choice_id.split('/')[1]) choice = Choice.objects.get(id=choice_id) if survey is None: survey = choice.question.survey choice.votes = choice.votes + 1 choice.save() if survey is not None: participant = Participant(survey=survey, participation_datetime=timezone.now()) participant.save() return redirect('/submit_success/') so .. where is the error here -
Problem with Cors and fetching information in react
I have a problem with CORS and fetch with REACT.JS. That's my code: let componentMounted = true; useEffect(() => { const getCars = async () => { const response = await fetch('http://127.0.0.1:8000/dealership/cars/?format=json', {mode: 'no-cors'}); if(componentMounted){ setData(await response.clone().json()); setFilter(await response.json()); } return () => { componentMounted = false; } } getCars(); }, []); In the Chrome console i have this error: Uncaught (in promise) SyntaxError: Unexpected end of input (at Cars.js:17:1) at getCars (Cars.js:17:1) And this: Cross-Origin Read Blocking (CORB) blocked cross-origin response http://127.0.0.1:8000/dealership/cars/?format=json with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details. In the backend i have Django and I have import Cors-headers like this: CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000', ] -
Django & POSTMARK API Templates
I'm trying to send a receipt template using POSTMARK API from my Django application but I'm struggling with retrieving multiple items under receipt details. I'm converting my query of items within an order to a list, then from the list, we are serializing it to JSON. Here is the output I get with the JSON with products when I run print: [{'product__name': 'Pokemon 25th Anniversary', 'quanity': 1, 'product__point_price': 100.0}] The serialization all looks correct however if you have multiple items, this becomes an issue. If you look down at my code under receipt details you will see I had to specify [0] before specifying the key name. How do I do this without specifying [0] so I can get all items? Here is my code : VIEW @login_required def checkoutcomplete(request): customer = request.user order = Order.objects.get(customer= customer , complete = False, ) favorites = Favorite.objects.filter(customer = customer.id) today_date = datetime.datetime.today() today_date_strf = datetime.datetime.strftime(today_date,"%m/%d/%Y" ) items = order.orderitem_set.all() data = list(items.values("product__name","quanity","product__point_price")) save_json = json.dumps(data, indent = 2) my_cart_json = json.loads(save_json) #POST MARK API url = "https://api.postmarkapp.com/email/withTemplate" payload = json.dumps({ "From": "", "To": "", "TemplateId": 28132290, "TemplateModel": { "counselor_name": "Fellow Counselor", "student_name": student.student_name, "receipt_id": str(order.transaction_id), "date": today_date_strf, "points": order.get_cart_total, "receipt_details": [ { … -
I am trying pass the obj2 to the frontend but it is not working passing it show the previous values not the updated values in django
when I am trying to pass the context in the post method it works and displays the content in the front-end but when I am trying to pass the context in the get method it is not working. I am trying to change the view based on the filer. if(request.POST): # it is form print("%%%%%%%%%%%%%% post ") chapter_tag = request.POST.get('chap_tag') chapter_name = request.POST.get('chap_name') pub_id_chap = pub_id[0][0] data = { 'chapter_tag': chapter_tag, 'publication_id': pub_id_chap, 'std': int(clas), 'chapter_name': chapter_name } form = chapter_details_master_form(data) if form.is_valid(): form.save() print("*********** ___________") pub_id, summa_list = chapter_list(pub, sub, clas) content = { 'pubk_list': mylist, 'obj': summa_list } redirect(reverse('publication_chapter_list')) return render(request, "publication_chapter_list.html", content) else: print(form.errors.as_data()) #print('$$$$$$$$$$$$',pub,sub,clas) pub_id, summa_list = chapter_list(pub, sub, clas) content = { 'pubk_list': mylist, 'obj': summa_list } print('----------------------------') return render(request, "publication_chapter_list.html", content) if request.method == 'GET': print("%%%%%%%%%%%%%% get ") pub = request.GET.get('publication') clas = request.GET.get('class_value') sub = request.GET.get('subject_id') flag = request.GET.get('flag') request.session['clas'] = clas request.session['sub'] = sub request.session['pub'] = pub pub_id = 0 if flag: pub_id, summa_list = chapter_list(pub, sub, clas) request.session['pub_id'] = pub_id #print('%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%% ',summa_list) chapter_tag_list = summa_list request.session['list_chap'] = summa_list content = { 'pubk_list': mylist, } content['obj'] = chapter_tag_list print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ', content) return render(request, "publication_chapter_list.html", content) -
Django User Model (Employee and Customer)
I am currently working on a mobile app delivery system which involves two types of users: "Employee" and "Customer". Each type of user would have different views and permissions within the app. In addition, each type of user would their own "profile", if you will. The employee's profile purpose is mostly just to designate company roles. The customer's profile is mostly used to save an address for delivery. I am trying to get some opinions on what the best practice to achieve something like this would be. I can't decide if its better to use AbstractBaseUser or AbstractUser. Below is a visual of the models I am wanting to create along with their relationship: Below is the the user/models.py file that I mocked up: class UserTypes(models.Model): type = models.CharField(max_length=100) def __str__(self): return self.type class User(AbstractBaseUser): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField() phone_number = models.CharField(max_length=20) is_employee = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) def __str__(self): return f'{self.first_name} {self.last_name}' # if user.is_employee == True class EmployeeProfile(models.Model): EMPLOYEE_ROLES = ( ('Driver', 'driver'), ('Production', 'production'), ('Manager', 'manager') ) user = models.OneToOneField(User, on_delete=models.CASCADE) role = models.CharField(max_length=12, choices=EMPLOYEE_ROLES) def __str__(self): return self.user # if user.is_customer == True class CustomerProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company = … -
Django, more type of user - I need advice
I need advice. I want make 3 types of user: member (only nickname/password/email) company (nickname/password/email/company/regon + permision for edit model) admin My question is aobut how make model for this users: make big model for member and company together but field which are only for comapny make empty for member. Next to by admin panel i can make group and add "comapny" ppl make 2 type of user (here i will need advice like what i should use on it) and seperate website register for member and company and login should be the same form Thank you for answer -
How can I show posts on page using django TemplateView class?
I used a ready-made template for the blog project. When the button is clicked on the template in home page, a modal opens and login registration processes are performed from here. On the home page, both view and login and register functions should work at the same time. I did login and registration with template view, but this time my posts disappeared. no error on the page or terminal.Anybody can help me to do this! Thanks all! views.py class HomeView(TemplateView): # model = Post template_name = 'blog/index.html' # ordering = ['-last_updated'] def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) context['posts'] = Post.objects.all() print(context['posts']) return context def get(self, request, *args, **kwargs): return self.render_to_response({'loginform': AuthenticationForm(prefix='loginform_pre'), 'registerform': UserCreationForm(prefix='registerform_pre')}) def post(self, request, *args, **kwargs): # self.object_list = self.get_queryset() loginform = _get_form(request, AuthenticationForm, 'loginform_pre') registerform = _get_form(request, UserCreationForm, 'registerform_pre') if loginform.is_bound and loginform.is_valid(): # Process loginform and render response user = loginform.get_user() login(request, user) return redirect('index') elif registerform.is_bound and registerform.is_valid(): user = registerform.save() login(request, user) return redirect('index') return self.render_to_response({'loginform': loginform, 'registerform': registerform}) html template <div class="row"> {% for post in posts %} <div class="col-lg-4 col-md-6 col-12 mb-4"> <div class="blog-item"> <div class="image-blog"> <img src='{{ post.image.url }}' alt="blogImage" class="img-fluid" style="height: 162px;overflow: hidden;"> </div> ... -
intcomma after widthratio in Django templates
I want to do "intcoma" after "widthratio" in the Django template. I thought about it as below, but it doesn't work. {{ {% widthratio p.price 2 1 %}|intcomma }} -
How to manipulate Django Admin
I created this class: class Orcamento(models.Model): id = models.IntegerField(primary_key=True) Cliente = models.CharField(max_length=40, default=0) Cod_Cliente= models.CharField(max_length=40, default=0) N_Orcamento = models.CharField(max_length=40, default=0) Endereço = models.CharField(max_length=50, default=0) Email = models.CharField(max_length=40, default=0) Telefone = models.CharField(max_length=40, default=0) Departamento = models.CharField(max_length=40, default=0) Data = models.CharField(max_length=40, default=0) Revisao = models.IntegerField(default=0) #Serviços = models.CharField(max_length=100, default=0) Serviços = ArrayField(models.CharField(max_length=50),default=list, size=20) #função para usar o nome do objeto e não a instância def __str__(self) -> str: return self.Cliente But in the Admin page "Serviços" has just 1 field and not a array, how can I manipulate it? I want to enter with some date in more than 10 fields Image bellow: Djando Admin page -
Django get sum of value from list of objects in jsonfield
I have a model with the following implementation class MyModel(models.Model): data = models.JSONField(null=True, blank=True) The I have json in this format: { "name": "Name", "irrelevant_list": [], "items": [ { "name": "Name 1", "quantity": 1, "other_list_of_objects": [] }, { "name": "Name 2", "quantity": 2, "other_list_of_objects": [] } ] } I want to annotate db rows with the sum of quantity (i.e. quantity = 3 for this db row), I have tried multiple approaches, still not getting the right query. -
Sending emails with django and Celery - how to return error message if sending failed?
I'm using django with celery to send emails with verification code. I use third-party service (SendGrid) to send emails. If there is any error on the email server side (say, I exceeded a daily email limit) I want to tell users about that, but since celery is async and does not return the actual response from the server, how could I accomplish that? -
django.db.migrations.exceptions.NodeNotFoundError: Migration app.0172_auto_20220603_1746 dependencie _auto_20220601_2313')
I deleted some migration files that were giving me the error. Then when I write "python3 manage.py showmigrations" I get the following error: root@chat-manager:/var/www/jinabot# python3 manage.py makemigrations Traceback (most recent call last): File "manage.py", line 23, in <module> main() File "manage.py", line 19, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.7/dist-packages/django/core/management/__init__.py", line 419, in exe utility.execute() File "/usr/local/lib/python3.7/dist-packages/django/core/management/__init__.py", line 413, in exe self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.7/dist-packages/django/core/management/base.py", line 354, in run_fro self.execute(*args, **cmd_options) File "/usr/local/lib/python3.7/dist-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.7/dist-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.7/dist-packages/django/core/management/commands/makemigrations.py", l loader = MigrationLoader(None, ignore_no_migrations=True) File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/loader.py", line 53, in __init__ self.build_graph() File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/loader.py", line 259, in build_g self.graph.validate_consistency() File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/graph.py", line 195, in validate [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/graph.py", line 195, in <listcom [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/usr/local/lib/python3.7/dist-packages/django/db/migrations/graph.py", line 58, in raise_err raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration app.0172_auto_20220603_1746 dependencie _auto_20220601_2313') How to fix it? -
RelatedObjectDoesNotExist at /authentication/update-user-bio.html User has no user_bio
i have a userBio model class UserBio(models.Model): user=models.OneToOneField(User, verbose_name=("User's Bio"), on_delete=models.CASCADE,related_name='user_bio') user_profile_bio=models.TextField(max_length=200,null=True,default='This user has no Bio yet') def __str__(self): return self.user.username +"s' bio" When someone wants to update their bio; i want to create a userbio object and show it to them or pass to through the form. here's views.py def Userbio(request): form=form=UserBioForm(instance=request.user.user_bio) if not request.user.user_bio: txt='User Bio' a=UserBio.objects.create(user=request.user,user_profile_bio=txt) a.save() form=UserBioForm(instance=request.user.user_bio) if request.method == 'POST': form = UserBioForm(request.POST, instance=request.user.user_bio) if form.is_valid(): form.save() messages.success(request,'Change Saved succesfully!') return HttpResponseRedirect(reverse('profile')) return render(request, 'authentication/User_bio.html', context={'form':form}) but it says RelatedObjectDoesNotExist at /authentication/update-user-bio.html User has no user_bio. what's the problem here? Or you can help me in another way. How can i create an userbio object when someone signs up?if i can auto create an usebio object for everyone who signs up it would be better than this. -
Google oauth + django - cant authenticate from saved data
Okay, so i got the flow working, but it only works on the current session, if i try to load the data in, even with just a refresh the credentials dont hold up. So this works which is where oauth redirects to after user accepts prompts: def oauth_redir(request): u=Employee.objects.filter(dashboard_user=request.user) if not u: u=Employee.objects.create(dashboard_user=request.user) else: u=u[0] flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( CLIENT_SECRETS_FILE, scopes=SCOPES, state=request.GET.get("state")) flow.redirect_uri = REDIRECT_URL flow.fetch_token(authorization_response=request.build_absolute_uri().replace("http:","https:")) #saving credentials for future use credentials = flow.credentials if not Emp_google_creds.objects.filter(employee=u): Emp_google_creds.objects.create( token= credentials.token, refresh_token= credentials.refresh_token, token_uri = credentials.token_uri, client_id = credentials.client_id, client_secret= credentials.client_secret, scopes = " ".join(credentials.scopes), employee = u ) else: creds=Emp_google_creds.objects.get(employee=u) creds.token = credentials.token, creds.refresh_token = credentials.refresh_token, creds.token_uri = credentials.token_uri, creds.client_id = credentials.client_id, creds.client_secret = credentials.client_secret, creds.scopes = " ".join(credentials.scopes), creds.save() if not credentials or not credentials.valid: print(credentials, credentials.valid, credentials.expiry) # credentials.refresh(Request()) # return redirect("/calendar/cal_auth/") try: service = googleapiclient.discovery.build('calendar', 'v3', credentials=credentials) # Call the Calendar API now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time print('Getting the upcoming 10 events') events_result = service.events().list(calendarId='primary', timeMin=now, maxResults=10, singleEvents=True, orderBy='startTime').execute() events = events_result.get('items', []) if not events: print('No upcoming events found.') return # Prints the start and name of the next 10 events for event in events: start = event['start'].get('dateTime', event['start'].get('date')) print(start, event['summary']) except … -
Problem when deploying Django with apache when running the server
I'm currently working on deploying a Django app with apache (on Debian server). I configured apache with mod_wsgi. I added my server IP in allowed_hosts in settings.py. Migrations done correctly. When I run the server : python manage.py runserver 0.0.0.0:8000 I get an infinite loop with the following message : "GET / HTTP/1.0" 302 0 I can't find a solution, any idea plz ? enter image description here -
what Django request.META is
I read a lot of articles about request.META but I didn't understand anything about it and what it does. Can anyone explain it? -
Problem when sending dictionary with ajax ( POST ) to python ( django views ) -> always empty
So i call this in the head of the html : <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> then with a button i call a function : <div> <button class= "button" type="ajax-call" onclick="getValue();">Envoyer</button> </div> And the function is : <script type="text/javascript"> function getValue(){ .... $.ajax({ url: "{% url 'sondage' %}", type : 'POST', dataType: "json", data: {heure_reponse: heure, jour_reponse: jour,habitude_reponse: habit, faim_reponse : faim, soif_reponse: soif, estomac_reponse:estomac, miam_reponse: miam, quantite_reponse: quantite, but_reponse: but, adresse_reponse: adresse, identifiant_reponse:identifiant } }) } </script> The problem is : When i write in the views.py of my django site ( python ) with from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import csrf_exempt from django.shortcuts import render from csv import writer from csv import QUOTE_MINIMAL @csrf_exempt @login_required def sondage(request): #Récupération des données par ajax reponses = request.POST.items() reponses = list(reponses) if len(reponses) == 0: print(" AJAX PROBLEME ") reponses.append(request.user.get_filename().split('/')[1].split('.')[0]) name = request.user.get_filename().split('/')[1].split('.')[0] #Ecriture dans le csv write_csv(reponses,name) #Appel de la page que l'on est en train de traiter return render(request, 'sondage.html',{'data':reponses}) def write_csv(data,name): #Ouverture en mode APPEND with open('uploads/questionnaire/sondage.csv', 'a', newline='', encoding="utf-8") as csvfile: csv_writer = writer(csvfile, delimiter=',') csv_writer.writerow(data) csvfile.close() I always have "AJAX PROBLEME" ! Why ? And how do we fix this ? -
How to create a registration form in Django that will recognise when password and confirm password don't match
I am trying to build a registration form for a user on a webpage using python and the Django framework. The form works fine and registers a user if all the fields are valid and Django has built in error messages if fields are left blank etc which work fine. However, I am trying to add my own error for if the 'password' and 'confirm password' fields don't match. If they don't match I get an error stating: 'The view main.views.register didn't return an HttpResponse object. It returned None instead.' My question is how would I successfully return the registration page with the error displayed to the user? Here is my views.py code: def register(request): if request.method == "GET": register_form = RegisterForm() return render(request, "main/register.html", { 'form': register_form }) else: register_form = RegisterForm(request.POST) if register_form.is_valid(): register_form.save() return render(request, "main/login.html") Here is my form.py code: class RegisterForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) confirm_password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ['first_name', 'last_name', 'username', 'email', 'password'] def clean(self): cleaned_data = super(RegisterForm, self).clean() password = cleaned_data.get("password") confirm_password = cleaned_data.get("confirm_password") if password != confirm_password: self.add_error("confirm_password", "Password does not match") -
Django + Twilio 500 Error (Session issue?)
I forked this Tutorial https://github.com/TwilioDevEd/automated-survey-django and am trying to get it to run locally. The current behavior is that, I send a text to the Twilio number and then it correctly texts me the first question of the survey. However, then when I text back, I don't get a response (should be the 2nd question of the survey) and I see a 500 error in Django. I can see that the second text message is being received by Django and, from the following function, it prints HELLO. However, it doesn't make it to YEP, so it appears to be erroring on answering_question = request.session.get('answering_question_id'), which seems like it is a problem with the session. I can see that there is a new session in the Django_session table created from my first text. I'm stuck on what is going wrong. request.session['answering_question_id'] is being set elsewhere in the code, but, my understanding, is if wasn't set, then answering_question would just be false, not an error. I'm stuck - any thoughts? def redirects_twilio_request_to_proper_endpoint(request): print("HELLO") answering_question = request.session.get('answering_question_id') print("YEP") if not answering_question: print('1') first_survey = Survey.objects.first() redirect_url = reverse('survey', kwargs={'survey_id': first_survey.id}) else: print('2') question = Question.objects.get(id=answering_question) redirect_url = reverse('save_response', kwargs={'survey_id': question.survey.id, 'question_id': question.id}) return …