Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django+Supervisor+NGINX on Ubuntu server 18.04. Attempt to write a read only database
I am trying to deploy my website in Django+Supervisor+NGINX on Ubuntu server 18.04. gunicorn.conf.py bind = '127.0.0.1:8000' workers = 3 user = "nobody" Here is my .conf (supervisor): [program:ako] command=/home/oleg/dj/venv/bin/gunicorn ako.wsgi:application -c /home/oleg/dj/ako/ako/gunicorn.conf.py directory=/home/oleg/dj/ako user=nobody autorestart=true redirect_stderr=true stdout_logfile=/home/oleg/dj/ako/ako_supervisor.log stderr_logfile=/home/oleg/dj/ako/ako_supervisor.log autostart=true autorestart=true startsecs=10 conf. NGINX server { listen 80; server_name 95.217.187.37; access_log /var/log/nginx/example.log; location /static/ { root /home/oleg/dj/ako/rsf/; expires 30d; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } When I try to launch gunicorn with a stopped supervisor: sudo service supervisor stop on the root of my project gunicorn ako.wsgi:application everything properly works : Welcome to Ubuntu 18.04.4 LTS (GNU/Linux 4.15.0-91-generic x86_64) (venv) root@t-20200417:~/dj/ako# gunicorn --bind 0.0.0.0:8000 ako.wsgi [2020-04-18 13:44:15 +0200] [1768] [INFO] Starting gunicorn 20.0.4 [2020-04-18 13:44:15 +0200] [1768] [INFO] Listening at: http://0.0.0.0:8000 (1768) [2020-04-18 13:44:15 +0200] [1768] [INFO] Using worker: sync [2020-04-18 13:44:15 +0200] [1771] [INFO] Booting worker with pid: 1771 The website normally runs under http://95.217.187.37/rsf/f_size_water/ and everything properly works. When I start supervisor sudo service supervisor start the website is still reachable, static links are still working, but the dynamic content does not work. When a user in his browser changes the language in the menu "homepage language … -
Can't install django using pip. I have tried many things but nothing worked
ERROR: Exception: Traceback (most recent call last): File "c:\program files\python38\lib\site-packages\pip_internal\cli\base_command.py", line 186, in _main status = self.run(options, args) File "c:\program files\python38\lib\site-packages\pip_internal\commands\install.py", line 253, in run options.use_user_site = decide_user_install( File "c:\program files\python38\lib\site-packages\pip_internal\commands\install.py", line 604, in decide_user_install if site_packages_writable(root=root_path, isolated=isolated_mode): File "c:\program files\python38\lib\site-packages\pip_internal\commands\install.py", line 548, in site_packages_writable return all( File "c:\program files\python38\lib\site-packages\pip_internal\commands\install.py", line 549, in test_writable_dir(d) for d in set(get_lib_location_guesses(**kwargs)) File "c:\program files\python38\lib\site-packages\pip_internal\utils\filesystem.py", line 140, in test_writable_dir return _test_writable_dir_win(path) File "c:\program files\python38\lib\site-packages\pip_internal\utils\filesystem.py", line 153, in _test_writable_dir_win fd = os.open(file, os.O_RDWR | os.O_CREAT | os.O_EXCL) PermissionError: [Errno 13] Permission denied: 'c:\program files\python38\Lib\site-packages\accesstest_deleteme_fishfingers_custard_zsocdh' -
How to access Pivot Table ahead in Django Models
I have 3 models as following class User(models.Model): name = models.CharField(max_length=20, unique=True) class Job(models.Model): name = models.CharField(max_length=20, unique=True) class Slot(models.Model): name = models.CharField(max_length=20, unique=True) jobs = models.ManyToManyField(Job, related_name = 'slots') As you can see I am able to create Pivot table for Job_slot, with the Primary key of that Table I need to create a table between User and job_slot, where I can have something like following Thanks in advance for solving this complex problem That I am trying to solve for more than 5 hours!! -
How do I create an API endpoint with django rest framework jwt for when user is logged_in?
I am trying to create an endpoint for when a user is logged in to check the status of user is logged in react js. For my backend, I use django rest-framework. Here is the backend code. serializers.py: from rest_framework import serializers; from rest_framework_jwt.settings import api_settings from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username',) # handle signups only class UserSerializerWithToken(serializers.ModelSerializer): token = serializers.SerializerMethodField() password = serializers.CharField(write_only=True) def get_token(self, obj): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(obj) token = jwt_encode_handler(payload) return token def create(self, validated_data): password = validated_data.pop('password', None) inst = self.Meta.model(**validated_data) if password is not None: inst.set_password(password) inst.save() return inst class Meta: fields = ('token', 'username', 'password') urls.py: The following code is where I would create the endpoint from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from rest_framework_jwt.views import obtain_jwt_token from rest_framework_jwt.views import verify_jwt_token urlpatterns = [ path('api-auth/', include('rest_framework.urls')), # path('rest-auth/', include('rest_auth.urls')), # path('rest-auth/registration/', include('rest_auth.registration.urls')), path('token-auth/', obtain_jwt_token), path('api-token-verify/', verify_jwt_token), path('login/', include('login.urls')), path('admin/', admin.site.urls), path('api/', include('menus.api.urls')), path('phlogapi/', include('phlogfeeder.phlogapi.urls')) ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I am confused on how to create a endpoint with jwt. -
django ORM annotate of sum of integers divide by sum of floats some how fail
class CSVFile(models.Model): installs = models.fields.IntegerField() spend = models.fields.FloatField() # this give me weird error! CSVFile.objects.annotate(metric=Sum('installs') / Sum('spend')) # but this will fix it! any idea why? CSVFile.objects.annotate(metric=Sum('installs', output_field=FloatField()) / Sum('spend')) sum of integers divide by sum of floats some how fail! database is SQLite django 3.05 -
Add data from request POST into a table template [Django, Python]
I create a table show book info from SQLite database and I'm trying to create an "Add New Book form" to make it add a new book into a table database. How can I add a book and then make it show into the table Book Info ? <div class="container-fluid"> <!-- Add Book --> <div class="add-book"> <h1>Add a Book</h1> <form action="/add_book" method="POST" class="add_more_book"> {% csrf_token %} <p> <label for="title" id="title">Title:</label> <input type="text" name="title" class="form-control" id="input-title" /> </p> <p> <label id="desc" for="desc">Description:</label> <textarea class="form-control" name="description" id="input-desc" rows="3"></textarea> </p> <button type="submit" class="btn shadow btn-primary" id="addbtn"> Add </button> </form> </div> <!-- End of Add Book --> <!-- Book info --> <div class="book-info"> <form action="/" method="POST"> {% csrf_token %} <table class="table table-bordered"> <thead> <tr> <th>ID</th> <th>Title</th> <th>Action</th> </tr> </thead> <tbody> {% for i in all_books_info %} <tr> <th scope="row">{{i.id}}</th> <td>{{i.title}}</td> <td><a href="/books/{{i.id}}">Views</a></td> </tr> {% endfor %} </tbody> </table> </form> </div> -
PyCharm Doesn't Recognize Installed Django App
I created a Django project and then started and app, but in project_name/project_name/urls.py, PyCharm doesn't recognize my app_name when I say from app_name import views. But running the project from the command line works. Ideas? I'm using a virtualenv and the Anaconda distribution of Python 3.7.3. Pycharm 2020.1 on Windows. -
multiline chart.js + Django graph does not rendering properly
i have spent the whole day trying to figure out what is going on with this graph not rendering in html. I can't find out what I am doing wrong here. the closest post that I found was this one Django and Chart.js Not Rendering Graph Correctly the help provided there does not do the trick. My underlying issue is that I am not sure how to pass my data inside of the graph. here is my js script function setChart(){ var ctx5 = document.getElementById('myChart5').getContext('2d'); var myChart5 = new Chart(ctx5, { type: 'line', data: { labels: ["days-15","days-14", "days-13","days-12","days-11","days-10","days-9","days-8","days-7","days-6","days-5","days-4","days-3","days-2","days-1"], datasets: [{ label: 'Number of orders placed', data: [ {% for dr in tableau1 %}{{ dr.number_of_orders_placed}}, {% endfor %}], backgroundColor: [ 'rgba(54, 162, 235, 0.2)', ], borderColor: [ 'rgba(54, 162, 235, 0.2)', ], borderWidth: 1 }, { label: 'purchased_quantity', data: [{% for dr in tableau1 %}{{ dr.purchased_quantity}},{% endfor %}], backgroundColor: [ 'rgba(54, 162, 235, 0.2)', ], borderColor: [ 'rgba(54, 162, 235, 0.2)', ], borderWidth: 1 }, { label: 'sold_quantity', data: [{% for dr in tableau1 %}{{ dr.sold_quantity}},{% endfor %}], backgroundColor: [ 'rgba(54, 162, 235, 0.2)', ], borderColor: [ 'rgba(54, 162, 235, 0.2)', ], borderWidth: 1 } ], options: { scales: { yAxes: … -
on Django, how can i pull data from database to a new html template from a html form, using a non logged in user input?
I have a form that is saving the data to the database and i want to open the template with the values from the database that I already calculated on models.py and saved to the database, this is the first tool I am developing on python so maybe I am asking the wrong question. So far the info that I want to pull is already saved on the Django Database. I want to pull the data from the "current user" form submission. so my question is how do I call current user DB info to the template when they click "get an estimate". This is what I have on views: class RackView(TemplateView): template_name = 'estimate/estimate_details.html' def get(self, request): form = RackForm() racks = Rack.objects.all() users = User.objects.all() args = {'form': form, 'racks': racks, 'users': users} return render(request, self.template_name, args) def post(self, request): form = RackForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user = request.user #try changing here to "pk" or "id" instead of user if it doesnt work or try dreating a user with name and email post.save() text = form.cleaned_data['post'] form = RackForm() args = {'form': form, 'text': text} return redirect('estimate_details: estimate_details') def estimate_details(request,pk=None): if pk: user = User.objects.get(pk=pk) else: … -
Django Admin Panel multiple choice all selected
I am adding a model to my admin panel in Django. It looks like this.. class Property(models.Model): event = models.ManyToManyField(Event) name = models.CharField(max_length=255) applicable_devices = models.ManyToManyField(Device) property_type = models.CharField(max_length=20, choices=TYPE_CHOICES) expected_value = models.CharField(max_length=255) For the field event it corresponds to another model of mine. In the admin panel it gives me a mutliple choice field to select the ones it applies to. I am trying to find a way to make it select all of them by default. When I going to be adding these properties, it will be applying to all events the majority of the time. I am just trying to save some clicks from selecting all. -
send list of object with data attr in django template
I built an image sharing website with django and jquery and I want when clicking on image rise comment of image with modal but for doing so we need to send list of my comment of image. If we want to send only one object we can use data-* attribute and jquery but for sending a list of objects this mehod doesn't work any more. Is this any way for sending list of object with data-* attribute? -
Django case when else in filter
I need a similar code to this SQL: SELECT * FROM tab WHERE a = CASE WHEN x IS NULL THEN b ELSE c END my attempt, but to no success: model.objects.filter(a=Q(Case(When(x__isnull=True, then='b'), default='c'))) when I try to run, I get this error: Traceback (most recent call last): File "<input>", line 2, in <module> File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\query.py", line 904, in filter return self._filter_or_exclude(False, *args, **kwargs) File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\query.py", line 923, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1340, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1371, in _add_q check_filterable=check_filterable, File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1249, in build_filter value = self.resolve_lookup_value(value, can_reuse, allow_joins, simple_col) File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1058, in resolve_lookup_value value = value.resolve_expression(self, **kwargs) File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\query_utils.py", line 95, in resolve_expression check_filterable=False, File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1371, in _add_q check_filterable=check_filterable, File "C:\projetos\xxx\venv\lib\site-packages\django\db\models\sql\query.py", line 1237, in build_filter arg, value = filter_expr TypeError: cannot unpack non-iterable Case object -
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.