Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to handle user reports for content e.g. inappropriate posts and profiles?
My Django app will allow users to report inappropriate posts and profiles etc. I want to be able to store these reports so that they can be reviewed by an admin. The ways I'm thinking of doing it is to either create a table in the database and store it there or just store it in a CSV / text file. Is there a better way to handle this feature? -
Passing Javascript variables to python main.views in Django
I am trying to send a variable from javascript to a python function in main.views, and I am using the Django web framework. I am very new to web development and I would really appreciate it if you showed some code for how to do it. Here is my variable (in home.html): <script> var my_var = 10; </script> and I need to send this to a function in main.views. My main.views looks like this so far: from django.shortcuts import render def homepage(request): return render(request, "main/home.html") def get_var(request): my_var = # I WOULD LIKE TO RECEIVE THE VARAIBLE HERE print(my_var) and so far here is my main.urls: from django.urls import path from django.conf.urls import url from . import views urlpatterns = [ path("", views.homepage, name="homepage"), ] Thanks for the help! -
getting 'bytes' object has no attribute 'encode'
my task is : upload a CSV file in Django model my model.py is given below from django.db import models # Create your models here. class Chart(models.Model): date=models.DateTimeField(blank=True,null=True) open=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) high=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) low=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) close=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) def __str__(self): return self.str(date) class NSEBHAV(models.Model): symbol=models.CharField(max_length=20,null=True,blank=True) series=models.CharField(max_length=2,null=True,blank=True) open=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) high=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) low=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) close=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) last=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) prev_close=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) tottrdqty=models.IntegerField(null=True,blank=True) tottrdval=models.DecimalField(max_digits=10,decimal_places=3,null=True,blank=True) timestamp=models.DateTimeField(blank=True,null=True) totaltrades=models.CharField(max_length=20,null=True,blank=True) isin=models.CharField(max_length=20,null=True,blank=True) def __str__(self): return self.symbol my view.py is given below import csv,io from django.shortcuts import render from django.contrib import messages from .models import NSEBHAV,Chart # Create your views here. def upload_nse(request): template='upload.html' data=NSEBHAV.objects.all() prompt={ 'order': 'Order of the CSV should be (symbol,series,open,high,low,close,last,prevclose,tottrdqty,tottrdval,timestamp,totaltrades,isin', 'profiles': data } if request.method=='GET': return render(request,template,prompt) csv_file=request.FILES['file'] print(csv_file) # if not csv_file.name.endwith('.csv'): # messages.error(request,'This is not csv file') data_set=csv_file.read().encode('utf-8') io_string=io.StringIO(data_set) next(io_string) for column in csv.reader(io_string,delimiter=',',quotechar="|"): _, created = NSEBHAV.objects.update_or_create( symbol=column[0], series=column[1], open=column[2], high=column[3], low=column[4], close=column[5], last=column[6], prevclose=column[7], tottrdqty=column[8], tottrdval=column[9], timestamp=column[10], totaltrades=column[11], isin=column[12] ) context = {} return render(request, template, context) csv.file sample is error screenshot my html file is is given below: thanks in advance . if i use encode is is giving same error and also i want to check type of uploaded file is csv or not -
[Django][ModelForm] Objects from ModelForm are saved properly under debugger, but in normal mode some fields are not saved
I am giving up slowly, please help! I have three-step form to create two objects Pet and LostPet. Step1: Field1 - Pet.name Field2 - Pet.type Field 3 - LostPet.owner_name Field 4 -LostPet.event_date etc. Step2: additional info about Pet Field1 - Pet.chip_number Field2 - Pet.color Step3: Thank you page In Step1 I am just displaying form, In Step2 I am creating Pet object only with name, type and I save it: if request.method == 'POST': form = LostPetSteModel1a(request.POST, instance=pet) if form.is_valid(): pet.save() I also create LostPet object linked with brand new Pet: lostpet_form = LostPetStepModel1b(request.POST, request.FILES, instance=lostpet) lostpet.pet = pet lostpet.save() In the last step I am fetching Pet object from DB and update with additional fields from form2: pet = Pet() pet_form = AnimalLostPetStep2(request.POST, instance=pet) pet_db = get_object_or_404(Pet, id=request.session['pet']) pet.animal_id = pet_db.animal_id pet.pk = pet_db.pk pet.name = pet_db.name pet.save() Under debugger session, everything works ok, In the normal runserver mode I don't have few fields saved. Basically it is email address from LostPet model and all the additional fields from Step2. As I mentioned when I debug it step by step, it works ok. All the fields are properly filled and saved to the database. Do you know what is … -
Iterate over lists of form fields in a template
I am attempting to group my form fields so that I can iterate over each group separately within my template: # app/forms.py from django import forms class CustomForm(forms.Form): field1 = forms.FieldClass(label="Field 1") field2 = forms.FieldClass(label="Field 2") field3 = forms.FieldClass(label="Field 3") field4 = forms.FieldClass(label="Field 4") group1 = [field1, field2] group2 = [field3, field4] # app/templates/app/formTemplate.html <form method="POST"> <div> {% for field in form.group1 %} <p style="display: block"> {{ field.label }} <span style="float: right"> {{ field }} </span> </p> {% endfor %} </div> <div> {% for field in form.group2 %} <p style="display: block"> {{ field.label }} <span style="float: right"> {{ field }} </span> </p> {% endfor %} </div> </form> As far as I am aware, this ought to display as: Field 1 INPUT FIELD 1 HERE Field 2 INPUT FIELD 2 HERE Field 3 INPUT FIELD 3 HERE Field 4 INPUT FIELD 4 HERE But what I get instead is: Field 1 <django.forms.fields.CharField object at ...> Field 2 <django.forms.fields.CharField object at ...> Field 3 <django.forms.fields.CharField object at ...> Field 4 <django.forms.fields.CharField object at ...> Additionally, if I use {% for field in form %} instead of {% for field in form.groupX %} it will render as expected (except that it will have … -
Django 3.0.5 with mod_wsgi: AttributeError: 'HttpResponse' object has no attribute '_resource_closers'
I'm getting an error when I deploy Django 3.0.5 under mod_wsgi: AttributeError: 'HttpResponse' object has no attribute '_resource_closers'. I'm running: Python: 3.6.8 Django: 3.0.5 Apache: 2.4.6 mod_wsgi: 4.6.2 Here's the basics of the view causing the error; nothing too exotic (I've simplified the code around meetings_struct): class MeetingsAPIView(MeetingsBaseView): def get(self, request, *args, **kwargs): meetings = self.get_meetings() meetings_struct = [] for meeting in meetings: meetings_struct.append({ "id": meeting.id, "name": meeting.title, "slug": meeting.slug, }) return HttpResponse(meetings_struct, content_type="application/json") If I activate the venv and use runserver manually on the server on port 80, the same view does not give an error. When the same code and venv are running under Apache, here's the error from Apache's logs: [Sat Apr 18 16:11:30.683980 2020] [wsgi:error] [pid 4154] [remote 100.19.146.139:54397] mod_wsgi (pid=4154): Exception occurred processing WSGI script '/var/django/sites/mysite-prod/config/wsgi.py'. [Sat Apr 18 16:11:30.684834 2020] [wsgi:error] [pid 4154] [remote 100.19.146.139:54397] Traceback (most recent call last): [Sat Apr 18 16:11:30.684891 2020] [wsgi:error] [pid 4154] [remote 100.19.146.139:54397] File "/var/django/sites/mysite-prod/venv/lib64/python3.6/site-packages/django/core/handlers/wsgi.py", line 133, in __call__ [Sat Apr 18 16:11:30.684903 2020] [wsgi:error] [pid 4154] [remote 100.19.146.139:54397] response = self.get_response(request) [Sat Apr 18 16:11:30.684925 2020] [wsgi:error] [pid 4154] [remote 100.19.146.139:54397] File "/var/django/sites/mysite-prod/venv/lib64/python3.6/site-packages/django/core/handlers/base.py", line 76, in get_response [Sat Apr 18 16:11:30.684933 2020] [wsgi:error] [pid 4154] [remote … -
django redirecting http to https
I'm trying to redirect www.example.com and http://www.example.com to https://www.example.com. In the settings file, I've added : SECURE_SSL_REDIRECT = True SECURE_SSL_HOST = 'https://www.example.com' but it redirects toward https://true.com. I've added : SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True no to avail. -
django.db.utils.ProgrammingError: cannot cast type interval to date
I'm deploying a django app on heroku and this error keeps popping up when I run heroku run python3 manage.py migrate. django.db.utils.ProgrammingError: cannot cast type interval to date LINE 1: ...MN "coupon_validity" TYPE date USING "coupon_validity"::date My models.py is: coupon_title = models.CharField(max_length=100) coupon_summary = models.TextField(max_length=400) coupon_pubdate = models.DateTimeField(default=timezone.now) coupon_validity = models.DateTimeField(default=(timezone.now() + timezone.timedelta(days=1))) coupon_code = models.CharField(max_length=100, default = '-') coupon_user = models.ForeignKey(User, on_delete = models.CASCADE, null = True)) My views.py is : def create(request): coupons = Coupon.objects if request.method == "POST": if request.POST['title'] and request.POST['summary'] and request.POST['validity'] and request.POST['code']: coupon = Coupon() coupon.coupon_title = request.POST['title'] coupon.coupon_summary = request.POST['summary'] coupon.coupon_validity = request.POST['validity'] coupon.coupon_code = request.POST['code'] coupon.coupon_pubdate = timezone.datetime.now() coupon.coupon_user = request.user coupon.save() return redirect('homepage') else: return render(request, 'coupons/create.html', {'error': 'All fields are required.'}) return render(request, 'coupons/create.html', {'coupons': coupons}) And the create coupon page inputs it as datetime-local: <input class="text" type="datetime-local" name="validity" id="validity" placeholder="Validity" required=""> <div class="form-alert" id="validityalert" role="alert"> </div> This is supposed to be an error from Postgresql so heres my settings.py code as well: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } import dj_database_url db_from_env = dj_database_url.config() DATABASES['default'].update(db_from_env) I dont really know what to try. The code works fine on localhost:8000 but on heroku it gives … -
make ugettext/ugettext_lazy to mark messages for translation in a list
I have a lot (a Lot) of lists that should be marked for translation in django. Instead of wrapping each element of a list into _(...) I thought I could pass an entire list to a function that would loop over each element marking it for translation. Apparently something like this does not work due to lazy evaluation of the function (the items are not added to django.po after django-admin makemessages command). from django.utils.translation import ugettext as _ a = ['x','y'] b = [_(i) for i in a] Is there any way to bypass this limitation? -
django: I want that a Model named 'x' with pre-specified fields, be automatically created when a user inputs 'x' in a form
I am creating a djangowebsite for a society in my college. Suppose there is an event i need to advertise and take online registrations. I want to be able to create an event by typing its name, click a button and a new event is created. Now I want to provide the students, a model form captioned the same as the event name where they fill in their details so their details get saved in the event named model db. How to do the italic thing ? -
Django JsonResponse with context
Can I use function JsonResponse and return .json file with dict context? I have only one .html and if I click in href ajax will get .json file and switch div's. html: <form id='FormSite' method="POST"> {% csrf_token %} <div id='Bilboard'> <div id='Pic'> <video id='VideoStart' style="width: 100%; height: 100%;" autoplay preload="true" loop > <source src="static/video/mainVideo.mp4"poster="static/img/facebook.png" type='video/mp4'> Your browser does not support the video tag. </video> </div> <div id='Wpis'> <h1 id='HeaderWpis'>Aktualności:</h1> <div id='WpisChild'> {% for News in Messags %} <div id='NewsPapper'> <p style="font-size: 200% !important;">{{ News.title }}</p> <img src="static/img/line.png" style="width: 5%; height: 5%; position: relative !important; left: 50%; transform: translateX(-50%);"> <p style="font-size: 150% !important;">{{ News.text |linebreaksbr }}</p> <img src="static/img/line.png" style="width: 5%; height: 5%; position: relative !important; left: 50%; transform: translateX(-50%);"> <p style="font-size: 150% !important;">{{ News.Data }}</p> </div> {% endfor %} </div> </div> </div> </form> views.py def FirstStart(request): if request.method == 'POST': respone = {} UrlCut = request.GET.get('site','') if(len(UrlCut) > 0): File_read_to_div = open('templemates/'+UrlCut+'.txt','r') else: File_read_to_div = open('templemates/Main.txt','r') respone['Pic'] = str(File_read_to_div.readline()) respone['h1'] = str(File_read_to_div.readline()) respone['WpisChild'] = str(File_read_to_div.readline()) #r Messages = NewsMessage.objects.all().order_by('-Data') context = { "Messags" : Messages } return JsonResponse(respone, context) Messages = NewsMessage.objects.all().order_by('-Data') context = { "Messags" : Messages } return render(request, 'main.html', context) ajax $.ajax({ url: url, data: $('#FormSite').serialize(), type: "POST", … -
Python “SSLError(”Can't connect to HTTPS URL because the SSL module is not available.“)': /simple/docutils/”
PROBLEM Whatever I try to install from terminal with pip I get this error message I may have installed and fully deleted homebrew before but I am not sure how to solve this The Django 3.0 app runs perfectly well Installs I try to run (all cases same error message) pip install -r requirements.txt pip install django-storages pip install ssl ERROR MESSAGE WARNING: pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available. WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/django-storages/ WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/django-storages/ WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/django-storages/ WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/django-storages/ WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.")': /simple/django-storages/ … -
What is the >= operator mean in python?
I know what greater than equal to operator is? I am asking what does it mean here?What does the >= operator mean in the last line? I am sure it is not a lambda function import datetime from django.db import models from django.utils import timezone class Question(models.Model): # ... def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) It is in the Django docs here, https://docs.djangoproject.com/en/3.0/intro/tutorial02/, under the 'Playing with the API' section. -
How to get image and show image simultaneously on django
I'm using Django to upload an image and show it simultaneously on the webpage. How can I do this? Most of the tutorials available describe how to fetch it after the image has been uploaded on a separate url, but that's not what I want. (For example, https://www.geeksforgeeks.org/python-uploading-images-in-django/ ) {% load static %} <html> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link href="{% static 'styles.css'%}" rel="stylesheet"> </head> <body> <div class="container"> <div class="row justify-content-center"> <div class="col-xs-12 col-sm-12 col-md-6 text-center"> <h1>Sudoku Spoiler</h1> </div> </div> </div> <div class="container"> <div class="row justify-content-center"> <div class="col-12 text-center"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <button type="submit" class="btn btn-primary">Upload</button> </form> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> <script src="{% static 'main.js' %}"></script> </body> </html> from django.shortcuts import render,redirect from .forms import * from django.http import HttpResponse # Create your views here. def image_view(request): if request.method=='POST': form = hotelForm(request.POST,request.FILES) for element in request.FILES: print(element) if form.is_valid(): form.save() print("form is valid") return redirect('success') if request.method=='GET': #this line is referred later imgs = Hotel.objects.all() return render(request,'djangoform.html',{"images":imgs}) else: form = hotelForm() return render(request,'djangoform.html',{"form":form}) def success(request): return HttpResponse('successfully uploaded') What I tried to do is insert a line of code that checks if the request … -
How do I compare the current time with time saved in database using django?
I'm making a simple Timetable web app to display current lecture ad subject after fetching the device time and match it with django database time. My database is having columns for Day, Time and Subject. General Sql query be like SELECT * FROM tablename WHERE timecolumn >= '12:00' AND Daycolumn = 'Monday' I am very new to django I only figure out to display the data like that but unable to understand about comparing it and then only display. {% for subject in subjects %} {{ subject }} {% endfor %} -
the command "python manage.py tenant_command shell" is not working
I am using django-tenant-schemas and the following command is not working. Does anybody know how I can run shell command on a tenant? python manage.py tenant_command shell Error: TypeError: Unknown option(s) for shell command: skip_checks. Valid options are: command, force_color, help, interface, no_color, no_startup, pythonpath, settings, stderr, stdout, traceback, verbosity, version. -
Convert Django Views to rest services
I have an application created long back, now client want to expose its some of views as APIs without breaking existing functionality, so that they can directly consume APIs using REST Tools to see the reports. Is there any easier way, I can convert my function to a REST View. P.S - I kept code shorter here to keep question simple, but in fact, its much complex in the actual app. eg. URL : - `path('/users', views.show_user_details, name='users'),` VIEW def show_user_details(request, user_id): users = User.objects.all() return render(request, "Users.html", {"users":users}) In REST Views, I want it to convert its input and output so that it can be accessible with same urls(or with little modifications), without much updating the existing views. `path('rest/users', views.show_user_details, name='users'),` #-- I am ok to add new url like this, but without much change in existing view . def show_user_details(request, user_id): users = User.objects.all() return JsonResponse({"users":users}) -
too many values to unpack (expected 2) - Django SQL exception
I am writing basic sign up view code with the Django framework. I have the following code: def register(request): if request.method == 'POST': username = request.POST.get("username") password = request.POST.get("password") email = request.POST.get("email") firstname = request.POST.get("firstname") lastname = request.POST.get("lastname") userObj = User.objects.filter(username) if userObj.exists(): return HttpResponse("username already exists") emailObj = User.objects.filter(email) if emailObj.exists(): return HttpResponse("email already exists") newUser = User.objects.create_user(username, email, password, first_name=firstname, last_name=lastname) if newUser is not Null: newUser.save() # render main menu page return HttpResponse("user successfully registered") else: return HttpResponse("error creating newUser") the failure is because of the lines userObj = User.objects.filter(username) and emailObj = User.objects.filter(email) here is part of the trace: Traceback (most recent call last): File "G:\Program Files\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "G:\Program Files\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "G:\Program Files\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "G:\Programming\project3\orders\views.py", line 21, in register userObj = User.objects.filter(username) File "G:\Program Files\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "G:\Program Files\lib\site-packages\django\db\models\query.py", line 904, in filter return self._filter_or_exclude(False, *args, **kwargs) File "G:\Program Files\lib\site-packages\django\db\models\query.py", line 923, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "G:\Program Files\lib\site-packages\django\db\models\sql\query.py", line 1350, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "G:\Program Files\lib\site-packages\django\db\models\sql\query.py", line 1377, in _add_q … -
Django - Images won't upload and change in my profile page
I'm working on my website's profile page. Changing the username or the email works but not the profile picture and I don't understand why :( I added my profile app in "INSTALLED_APPS", set MEDIA_ROOT and MEDIA_URL and set urlspatterns : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home.apps.HomeConfig', 'inscription.apps.InscriptionConfig', 'profil.apps.ProfilConfig', ] [...] MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' urls.py : urlpatterns = [ path('profil/', p.profil, name='profil'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I linked the user to its profile and I set the default image in models.py from django.db import models from django.contrib.auth.models import User class Profil(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='defaut.png', upload_to='image_profil') def __str__(self): return f'{self.user.username} Profil' admin.py : from django.contrib import admin from .models import Profil admin.site.register(Profil) Then I created the profile modification form in forms.py : from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profil class FormulaireModifUtilisateur(forms.ModelForm): username = forms.CharField( label = 'Nom de compte', min_length = 4, max_length = 150, initial=User.username, ) email = forms.EmailField( label = 'Email', min_length = 4, max_length = 150, ) class Meta: model = User fields = ['username', 'email'] class FormulaireModifProfil(forms.ModelForm): image = forms.FileField( label = 'Image de profil' ) class Meta: … -
Django update selectize on new foreign key in admin template
Some back story: I have overridden Django admin templates completely. Everything works fine. In the change_form.html, I have initialized the selectize.js through the following script: <script> $('select').selectize({ create: false, sortField: 'text', }); </script> Now, everything looks and works fine but I'm having a little problem when I click the add button on in the related_field_wrapper for that foreign key. I press it, the pop-up opens and the object gets created for that model but it doesn't update selectize for that field. Like it doesn't show it in the selectize options list but if I don't change anything else on that select field, it actually doesn't show that the object is selected but upon saving, it saves the newly created object in that field. This means that the field is being set in the select field but selectize just doesn't update. I understand that this might be a very specific request and that it's less Django related and more JS/Selectize related but I'd really appreciate some help. A starting point, I think would be to know what functions are performed upon creating a new object or updating Selectize when a new object is created. I'm lost guys. Thank you for reading … -
a raw sql query is not working in django framework. I am getting "TypeError at / not all arguments converted during string formatting"
select *from table_name where name = %s",params={"name1","name2"} full_code: from django.shortcuts import render from . models import destination def index(request,params = None): dests1 = destination.objects.raw("select *from travello_destination where name = %s",params={'Bangalore','Mumbai'}) return render(request,'index.html', {"dests":dests1}) -
debugging selenium LiveServerTestCase in vscode
I run functional tests in django using the LiveServerTestCase class. When I want to write a new test, I put a breakpoint in vscode, then inspect the page to work out the selenium command which will activate the next step. I run it in the DEBUG CONSOLE, wait for the next page to load and repeat the process: inspect, write command in DEBUG CONSOLE, wait for next page to load. That's worked great for me in the past, but now it no longer works. I'm not sure if I inadvertently changed a setting, or if django or vscode updates have broken the process, but when I run the next selenium command in the debug window, the browser window just sits there with a status message "waiting for localhost..." ; sometimes 5 or 10 minutes later it will advance. Anyone else had experience with writing Selenium scripts this way who has an idea why the server thread in vscode seems no longer to respond when it is stopped at a breakpoint? My vscode's launch.json entry: { "name": "test particular functional test", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "console": "integratedTerminal", "args": [ "test", "functional_tests.tests.test_selenium.test_coach_with_no_students", ], "django": true }, I'm not supposed to … -
No Reverse Match - django.urls.exceptions.NoReverseMatch
django.urls.exceptions.NoReverseMatch: Reverse for 'update_cart' with arguments '('',)' not found. 1 pattern(s) tried: ['cart/(?P[^/]+)$'] [18/Apr/2020 14:05:02] "GET /checkout/ HTTP/1.1" 500 157543 <--- this is the error message I am getting in terminal when I try to go onto the checkout page. view.html {% for item in cart.products.all %} <tr><td> {{ item }} </td><td>{{item.price}}</td> <td><a href='{% url "update_cart" item.slug %}'> Remove</a></td></tr> {% endfor %} </table> <br/> <a href='{% url "checkout" %}'>Checkout</a> {% endif %} </div> </div> {% endblock content %} views.py for orders from django.urls import reverse from django.shortcuts import render, HttpResponseRedirect # Create your views here. from carts.models import Cart def checkout(request): try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: the_id = None return HttpResponseRedirect(reverse("fuisce-home")) context = {} template = "fuisce/home.html" return render(request, template, context) urls.py from django.urls import path from . import views from carts import views as cart_views from orders import views as order_views urlpatterns = [ path('', views.home, name='fuisce-home'), path('subscription/', views.subscription, name='fuisce-subscription'), path('oneoff/', views.oneoff, name='fuisce-oneoff'), path('about/', views.about, name='fuisce-about'), path('contact/', views.contact, name='fuisce-contact'), path('cart/', cart_views.view, name='cart'), path('cart/<slug>', cart_views.update_cart, name='update_cart'), path('checkout/', order_views.checkout, name='checkout'), ] the problem seems to arise when i move the HttpResponse from just below def checkout, to below cart = Cart.objects.get(id=the_id). (change in code attached below). anyone know … -
Does Full-Stack Web Development Violate DRY?
I'm planning on using Django with ReactJS to build a GUI for a complicated database. In order to have features such as auto-completing searching for particular fields, etc, I suppose that using JavaScript is necessary. Is there a way to reuse the models that I made in Python so I don't have to repeat a bunch of code in writing the Django serializers for a REST API and in the models in ReactJS? -
Watching for file changes with StatReloader
I try to use docker in order to make the process of launching my django app automatically. I built the image, then executed the command docker run <image>. But everything I see is the line Watching for file changes with StatReloader and nothing happens. What am I doing wrong?