Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django modelformset prefix does associate data with particular modelformset
In a budgeting app, modelformsets for two project types are displayed, two modelformsets for each project type for a total of 4 modelformsets. To distinguish the modelformsets for different projects, each modelformset has its project_type as prefix. In the post method, when I try to receive the modelformset instances for each project type, the prefix seems to be not working, so I am getting all the data from all the modelformses inside each modelformset! class AddProFormaRates(DevelopmentView): ''' Adds budget rates for the budget in the kwargs 1) Given the budget, find the project types for the budget 2) For each project type, create a modelformset from ServiceRate ''' template_name = 'project/budget.html' # Create modelformset for the_project_type: RateForms = modelformset_factory(ServiceRate, formset = BaseRateFormSet, form = RateForm, extra = 0) def dispatch(self, *args, **kwargs): return super(AddProFormaRates, self).dispatch(*args, **kwargs) ... def post(self, request, *args, **kwargs): context = super(AddProFormaRates, self).get(request, *args, **kwargs) # 1) Get the project types for the budget budget_id = kwargs.get('pk', None) if budget_id: the_budget = budget.objects.get(id = budget_id) else: the_budget = context.get('budget', None) the_project = request.user.project the_project_types = the_budget.budget_project_types.all() # 2) Create modelformsets for each project type rate_formsets = [] formsets_errors = {} the_forms = [] formsets_data = {} expense_rate_forms_errors … -
Django Models: Notfied on Datetimefield
I have an event model that has a datetime field. What are some suggestions on implementing notifications whenever that datetime arrives? I would like to notify related users that the event is about to happen, is currently happening, or has passed. -
How to use UDP to send data to client in Django?
I have read that Django uses HTTP request response architecture to process user requests. And we all know HTTP is an application layer protocol designed within the framework of the Internet protocol suite. Its definition presumes an underlying and reliable transport layer protocol, and Transmission Control Protocol (TCP). So my question is id django uses tcp to establish connection and suppose I want to serve videos or some other file using UDP. How can I achieve this? -
Filter nested query if no results in Django
I have three basic nested serializers that are currently returning a nested data structure (shown below) when I use this query: queryset = Regulation.objects.all() serializer_class = RegulationSerializer(queryset, many=True) data: [{ name: "2019-final" versions: { 0: { name: "2019-01", iterations: (25) [{…}, {…}, {…}] } 1: { name: "2019-02", iterations: [] } } { name: "2020-final" versions: { 0: { name: "2020-01", iterations: [] } 1: { name: "2020-02", iterations: [] } }] My question is how do I NOT return the versions which have no iterations/empty set, and also not return the regulations which do not have any versions/or nested iterations. In the above dataset, I would not want to return '2020-final', because none of its versions have iterations. I would also not want to return version '2019-02', because it has no iterations. // serializers.py class IterationSerializer(serializers.ModelSerializer): class Meta: model = Iteration list_serializer_class = FilteredIterationSerializer fields = ('id', 'team', 'version', 'name', 'date_created', 'created_by_user') class VersionSerializer(serializers.ModelSerializer): iterations = IterationSerializer(many=True, read_only=True) class Meta: model = RegulationVersion fields = ('name', 'iterations') class RegulationSerializer(serializers.ModelSerializer): versions = VersionSerializer(many=True, read_only=True) class Meta: model = Regulation fields = ('name', 'versions') depth = 2 -
'User' object has no attribute '_committed'
Im making a simple app that authenticates users and lets them upload files. Im having a problem where when i try to add a model with user as a foreign key to my database I get this error: 'User' object has no attribute '_committed' models.py fs = FileSystemStorage(location='/media/uploads') class FileInstance(models.Model): file = models.FileField(storage=fs) owner = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) views.py def upload_file(request): if request.method == 'POST': file = FileInstance(request.FILES['file'], request.user) file.save() else: form = UploadFileForm() return render(request, 'upload.html') upload.html {% extends 'commons/base.html' %} {% block title %} Dodaj plik {% endblock %} {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="file"> <button type="submit">Upload</button> </form> {% endblock %} Stacktrace: Internal Server Error: /storage/upload/ Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/jch/PycharmProjects/2019Z_PAMIW_git_gr4/pamw2/storage/views.py", line 36, in upload_file file.save() File "/usr/local/lib/python3.6/dist-packages/django/db/models/base.py", line 741, in save force_update=force_update, update_fields=update_fields) File "/usr/local/lib/python3.6/dist-packages/django/db/models/base.py", line 779, in save_base force_update, using, update_fields, File "/usr/local/lib/python3.6/dist-packages/django/db/models/base.py", line 848, in _save_table for f in non_pks] File "/usr/local/lib/python3.6/dist-packages/django/db/models/base.py", line 848, in <listcomp> for f in non_pks] File "/usr/local/lib/python3.6/dist-packages/django/db/models/fields/files.py", line 286, in pre_save … -
Django channels Error during WebSocket handshake: Unexpected response code: 500
I'm completely stumped and I have spent hours researching what is causing this error. I used the following tutorial (https://channels.readthedocs.io/en/latest/tutorial/part_1.html) to understand Django channels to swap out ajax short-polling in a current project. I have inserted everything into my project and it should run fine except the websocket disconnects. The browser says WebSocket connection to 'ws://localhost:8001/ws/members/vote/2/' failed: Error during WebSocket handshake: Unexpected response code: 500. Terminal output: 2019-12-02 19:44:23,543 ERROR Exception inside application: 'room_name' File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/channels/sessions.py", line 183, in __call__ return await self.inner(receive, self.send) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/channels/middleware.py", line 41, in coroutine_call await inner_instance(receive, send) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/channels/consumer.py", line 59, in __call__ [receive, self.channel_receive], self.dispatch File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/channels/utils.py", line 51, in await_many_dispatch await dispatch(result) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/asgiref/sync.py", line 244, in __call__ return await asyncio.wait_for(future, timeout=None) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/tasks.py", line 339, in wait_for return (yield from fut) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/concurrent/futures/thread.py", line 56, in run result = self.fn(*self.args, **self.kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/channels/db.py", line 14, in thread_handler return super().thread_handler(loop, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/asgiref/sync.py", line 277, in thread_handler return func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/channels/consumer.py", line 105, in dispatch handler(message) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/channels/generic/websocket.py", line 39, in websocket_connect self.connect() File "./vote/consumers.py", line 10, in connect self.room_name = self.scope['url_route']['kwargs']['room_name'] 'room_name' 127.0.0.1:54775 - - [02/Dec/2019:19:44:23] "WSDISCONNECT /ws/members/vote/2/" - - Here's my code snippets Vote.html <script> var questionID = … -
How to add task to asyncio loop inside of a django view?
I have middleware that sets up the get_response method as a coroutine so that another task can be run together: class AsyncMiddleware: def __init__(self, get_response): self.get_response = asyncio.coroutine(get_response) def __call__(self, request): tasks = [self.get_response(request), <OTHER_ASYNC>] response, *other_response = asyncio.run(self.gather(tasks)) return response async def gather(self, tasks): return await asyncio.gather(*tasks) Inside of my django view, I need to use django channels to send a task to a worker on a PATCH request. When I try to add the task to my loop, the response completes, my model is updated, but the task is never sent to my worker. loop = asyncio.get_event_loop() channel_layer = get_channel_layer() result = loop.create_task(channel_layer.send( 'model-update', { 'type': 'update', 'data': {} }, )) I've tried many different variations of this code. If I remove the async code from my middleware and use async_to_sync from asigref, everything works as expected (this is not a real option because async_to_sync cannot be used inside a run loop) -
How to set up sub-domains on Apache
I am trying to get a site I have to work with sub-domains but nothing seems to be working. A quick overview of what I am doing.. The stack: -Django (using django-tenants/django-tenant-schemas for multi-tenancy) -Apache2 -Postgresql -Linode (Cloud Hosting) DNS settings: A/AAAA Record Hostname: www IP Address: XXX.XXX.XXX.XXX CNAME Record Hostname: * Aliases to: mysite.com etc/hosts file: 127.0.0.1 localhost XXX.XXX.XXX.XXX myhostname According to the Django-tenant docs this is how my VirtualHost should be set up... VirtualHost config: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/david/my_project/static <Directory /home/david/my_project/static> Require all granted </Directory> Alias /media /home/david/my_project/media <Directory /home/david/my_project/media> Require all granted </Directory> <Directory /home/david/my_project/config> <Files wsgi.py> Require all granted </Files> </Directory> ServerName mysite.com ServerAlias *.mysite.com mysite.com WSGIScriptAlias / /home/david/my_project/config/wsgi.py WSGIDaemonProcess django_app python-path=/home/david/my_project python-home=/home/david/my_project/venv WSGIProcessGroup django_app </VirtualHost> When I ping www.mysite.com it returns a response. When I ping www.main.mysite.com it returns a response as well (which should be a tenant). When I visit www.main.mysite.com I get a Bad Request(400) error which I assume is a good thing as the server is being reached. But no other tenants will even return a response like that. I get a This site can't be reached error for others. What settings … -
Annotate count of multiple values by week with Django ORM or combine based on shared keys
I'm trying to annotate the count of values and group by week/year. Here's what I attempted: activity = Activity.objects.filter(user=request.user)\ .annotate(year=ExtractYear('date'), week=ExtractWeek('date'))\ .values('year', 'week', 'activity')\ .annotate(count=Count('pk'))\ .order_by('-year', '-week') Which groups based on year, week, and activity: <QuerySet [{'activity': 'a', 'year': 2019, 'week': 48, 'count': 2}, {'activity': 'ac', 'year': 2019, 'week': 48, 'count': 4}, ... ]> What's the best way to group based on the week/year so the outcome is something like: [{'year': 2019, 'week': 48, {'activity': 'a', 'count': 2}, {'activity': 'ac', 'count': 4}, ... }] Is there a way to combine based on the shared keys of each item? -
How can I capitalize the first letter of a string in Python, ignoring HTML tags?
I would like to capitalize the first letter of a string, ignoring HTML tags. For instance: <a href="google.com">hello world</a> should become: <a href="google.com">Hello world</a> I wrote the following, which works, but it seems inefficient, since every character of the string is being copied to the output. Is there a better way to do it? @register.filter def capinit(value): gotOne = False inTag = False outValue = '' for c in value: cc = c if c == '<': inTag = True if c == '>': inTag = False if not inTag: if c.isalpha() or c.isdigit(): if not gotOne: cc = c.upper() gotOne = True outValue = outValue + cc return outValue Note that this ignores initial punctuation. It will capitalize the first letter it finds, unless it finds a number first in which case it doesn't capitalize anything. -
django computed coloumn with lookup from same table and if class
I am new to programming.I am trying to create a project management site. I created a model as follows class boqmodel(models.Model): code = models.IntegerField() building = models.ForeignKey(building, on_delete=models.SET_NULL, null=True) level = models.ForeignKey(level, on_delete=models.SET_NULL, null=True) activity = models.ForeignKey(activity, on_delete=models.SET_NULL, null=True) subactivity = models.ForeignKey(sub_activity, on_delete=models.SET_NULL, null=True) duration = models.IntegerField() linkactivity = models.CharField(max_length=300) #contains code (same as code field) which this specific code is linked to linktype = models.CharField(max_length=300)# only two choices start or finish linkduration = models.IntegerField() plannedstart = models.DateField() plannedfinish = models.DateField() The problem is i need my palnned start as a computed coloumn The planned coloumn should be as follows if linkactivity is null then it should take a default value 01-01-2019 if else then it should look the linkactivity in code field and then if linktype is start then it should specify the start date of code activty +duration or if linktype is finish plannedfinish+duration Example say first entry code=1 building=A-1 Level=L-1 Activity=Activity-1 Subactivity-Subactivity-1 duration=2 linkactivity=null linktype=null linkduration=null planned start=01-01-2019(as linkactivity=null) plannedfinish=03-01-2019(planned start+duration) second entry code=2 building=A-1 Level=L-1 Activity=Activity-2 Subactivity-Subactivity-2 duration=3 linkactivity=1 linktype=start linkduration=1 planned start=02-01-2019(as linkactivity=1,it searches code1 ,as linktype=start,it searches startdate of code 1 it is 01-01-2019 ; finally 01-01-2019+link duration(1)=02-01-2019) plannedfinish=05-01-2019(planned start+duration) Any help would be … -
Django SmartFields 'ImageFieldFile' object has no attribute 'is_static'
We are currently using Django 1.11, Python2.7 & django-smartfields 1.0.9. It used to work perfect, but for any update (I suppose) we are now getting this error everytime we update a record using ModelForms. 'ImageFieldFile' object has no attribute 'is_static' We trace the bug and it happens when SmartFields tries to delete an image /home/herosuite/lib/python2.7/smartfields/fields/__init__.py in delete self._committed = True if save and instance_update: self.instance.save() save.alters_data = True def delete(self, save=True, instance_update=True): # prevent static files from being deleted if self.is_static or not self: ... return if hasattr(self, '_file'): self.close() del self.file self.storage.delete(self.name) self.name = None ▼ Local vars Variable Value instance_update False save True self <ImageFieldFile: company/images/products/TM_105_AZUL.jpg> Even sometimes we just edit other fields in the record (not the image field) Has anyone faced this situation also???? -
Getting the django rest auth token value from local storage after refresh the page once in reactjs django rest application
I have made a application using react redux & django rest frame work.when i get the token after successful login, I save the token into local storage and dispatch the action as "AUTH_SUCCESS". Now i want to make a page accessible when it gets the Authentication token. But when i login it gets the token value from local storage after refresh page once manually .I am using react hook. So i use useEffect method like componentDidMount. But the result is same.is there any efficient way to solve this problem?Thank. -
django.db.utils.ProgrammingError: relation "postgres_po_db_view" already exists
am developing an api based on database view and am trying to a create a model for a postgres database view with managed=False option in class meta of model, and am connecting my model to the same database view via db_table parameter in the same class meta, here my database view name is "postgres_po_db_view" and am getting an error when ever am trying to run migrations for the corresponding model, please don't bother about the view or the model code, everything is good and working but my concern is when ever am trying to connect my model with my database view through class meta configuration inside the model class,when i migrated the very first time it is running smooth, and then after trying to run one more migration for another model or again trying to run the same command migrate am getting relation postgres_po_db_view already exists error...any useful lead is much appreciable..am unable to apply further migrations due to this error... here is my model: class ProductionOrderView(models.Model): class Meta: managed = False, ordering = '-creation_time', db_table = 'postgres_po_db_view' DRAFT = 'draft' PLANNING = 'planning' NOT_STARTED = 'not_started' IN_PROGRESS = 'in_progress' CANCELLED = 'cancelled' DONE = 'done' FAILED = 'failed' STATUS_CHOICES … -
Having difficulties getting navigation to work in Django
I am trying to get my navigation to work in Django This is what my about.html looks like <ul class="dropdown-menu"> <li class="nav-item"><a class="nav-link" href="{% url 'courses' %}">Courses</a></li> urls.py from django.contrib import admin from catalog import views from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('', views.about, name='about'), path('', views.courses, name='courses') ] and views.py from django.shortcuts import render #home page view def index(request): return render(request, "index.html") #about page def about(request): return render(request,"about-us.html") #courses page def courses(request): return render(courses, "courses.html") -
Full JSON Isn't Receiving on Django REST Framework Registration
I have a Django REST Registration page with two additional boxes (first_name and last_name). The registration page works fine when I use the input boxes but when I try to do a POST to the Register page, I constantly get that the form is invalid. Upon inspection, it looks like only the first_name and last_name are in the cleaned_data, but the JSON I am posting through Postman looks like: { "email": "test@test.com", "first_name": "test", "last_name": "test", "password1": "testtest", "password2": "testtest" } and it's not just Postman, I have also been trying the same thing in an Android app via Volley. I can't figure out why some of the JSON isn't going through. Here is my views.py for the Register page: from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login, models from userauth.templates.registration.forms import RegistrationForm from rest_framework.authtoken.models import Token from django.views.decorators.csrf import csrf_exempt from rest_framework.response import Response from rest_framework.decorators import api_view, renderer_classes from django.http import * def index(request): return render(request, 'userauth/index.html') @csrf_exempt def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) print(form.data) if form.is_valid(): print('form valid') form.save() username = form.cleaned_data['email'] password = form.cleaned_data['password1'] user = authenticate(username=username, password=password) login(request, user) token = Token.objects.create(user=user) responseData = { 'token': … -
Celery cannot launch due to connections problem in Redis
when trying to launch a celery worker with this command celery worker --app=back I keep having this error and I have no clue about how to debug it, redis-cli is working fine but I can't find any solution. [2019-12-02 17:59:12,250: CRITICAL/MainProcess] Unrecoverable error: ResponseError("unknown command 'SREM'",) Traceback (most recent call last): File ".../site-packages/celery/worker/worker.py", line 205, in start self.blueprint.start(self) File ".../site-packages/celery/bootsteps.py", line 119, in start step.start(parent) File ".../site-packages/celery/bootsteps.py", line 369, in start return self.obj.start() File ".../site-packages/celery/worker/consumer/consumer.py", line 318, in start blueprint.start(self) File ".../site-packages/celery/bootsteps.py", line 119, in start step.start(parent) File ".../site-packages/celery/worker/consumer/mingle.py", line 40, in start self.sync(c) File ".../site-packages/celery/worker/consumer/mingle.py", line 44, in sync replies = self.send_hello(c) File ".../site-packages/celery/worker/consumer/mingle.py", line 57, in send_hello replies = inspect.hello(c.hostname, our_revoked._data) or {} File ".../site-packages/celery/app/control.py", line 154, in hello return self._request('hello', from_node=from_node, revoked=revoked) File ".../site-packages/celery/app/control.py", line 106, in _request pattern=self.pattern, matcher=self.matcher, File ".../site-packages/celery/app/control.py", line 477, in broadcast limit, callback, channel=channel, File ".../site-packages/kombu/pidbox.py", line 352, in _broadcast channel=chan) File ".../site-packages/kombu/pidbox.py", line 396, in _collect chan.after_reply_message_received(queue.name) File ".../site-packages/kombu/transport/virtual/base.py", line 546, in after_reply_message_received self.queue_delete(queue) File ".../site-packages/kombu/transport/virtual/base.py", line 542, in queue_delete self._delete(queue, exchange, *meta, **kwargs) File ".../site-packages/kombu/transport/redis.py", line 818, in _delete queue or ''])) File ".../site-packages/redis/client.py", line 2008, in srem return self.execute_command('SREM', name, *values) File ".../site-packages/redis/client.py", line 839, in execute_command return self.parse_response(conn, … -
Django templates don't show my all parameters
I have problem. I want create relationship in model Django. I would like every user to have a different product price. The product must be assigned to the user. It must is to display only after logging in. Unfortunately, the template does not show all parameters. offers/models.py class Product(models.Model): title = models.CharField(max_length=100) category = models.CharField(max_length=50) weight = models.FloatField() description = models.TextField(blank=True) photo = models.ImageField(upload_to='photos/%Y/%m/%d/') is_published = models.BooleanField(default=True) list_date = models.DateField(default=datetime.now, blank=True) def __str__(self): return self.title class UserProduct(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.ForeignKey(Product, on_delete=models.DO_NOTHING) price = models.FloatField() is_published = models.BooleanField(default=True) list_date = models.DateField(default=datetime.now, blank=True) def __str__(self): return str(self.user.username) if self.user.username else '' Products are to be displayed for logged in users. offers/views.py def index(request): context = { 'products': Product.objects.order_by('category').filter(is_published=True) } return render(request, 'offers/products.html', context) def userproduct(request): context = { 'userproduct': UserProduct.objects.filter(user_id=request.user.id), 'userproduct1': Product.objects.all() } return render(request, 'offers/userproducts.html', context) My template show only title, and price. template.html <!-- Offers --> <section class="text-center mb-4 py-4"> <div class="container"> <div class="row"> {% if user.is_authenticated %} {% if userproduct %} {% for product in userproduct %} <!--Grid column--> <div class="col-lg-3 col-md-6 mb-4"> <div class="card"> <div class="view overlay"> <img src="{{ product.photo.url }}" class="card-img-top" alt=""> <a href="{% url 'product' product.id %}"> <div class="mask rgba-white-slight"></div> </a> </div> … -
Populate MultipleChoiceField values from ManyToManyField
I'm wanting to use my ManyToManyField in a form. I read that you should use a MultipleChoiceField for this. How can I populate the choices from my ManyToManyField? models.py class BoatModel(models.Model): title = models.CharField(max_length=80) category = models.ManyToManyField(Category) model_slug = AutoSlugField(null=True, default=None, unique=True, populate_from='title') class Meta: verbose_name_plural = "Models" def __str__(self): return self.title class Category(models.Model): title = models.CharField(max_length=50) category_slug = AutoSlugField(null=True, default=None, unique=True, populate_from='title') class Meta: verbose_name_plural = "Categories" def __str__(self): return self.title forms.py class CreateModelForm(forms.ModelForm): class Meta: model = Model fields = ('title', 'category',) widgets = { 'title': forms.TextInput(attrs={'class': 'category-title-field', 'placeholder': 'Category title'}), 'category': forms.MultipleChoiceField(), } -
Pipenv shell fails to create virtual environment in Python 3.8
I'm new to Django, and I'm starting a tutorial for Django with React, and I'm struggling with creating the virtual environment by using pipenv shell as per the tutorial's instructions. I have seen similar questions, but they have been either with another python version or the error is just different, and the answers haven't helped me. The error says the following: Failed creating virtual environment [pipenv.exceptions.VirtualenvCreationException]: File "C:\Users\Iván\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\pipenv\cli\command.py", line 385, in shell [pipenv.exceptions.VirtualenvCreationException]: do_shell( [pipenv.exceptions.VirtualenvCreationException]: File "C:\Users\Iván\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\pipenv\core.py", line 2155, in do_shell [pipenv.exceptions.VirtualenvCreationException]: ensure_project( [pipenv.exceptions.VirtualenvCreationException]: File "C:\Users\Iván\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\pipenv\core.py", line 570, in ensure_project [pipenv.exceptions.VirtualenvCreationException]: ensure_virtualenv( [pipenv.exceptions.VirtualenvCreationException]: File "C:\Users\Iván\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\pipenv\core.py", line 505, in ensure_virtualenv [pipenv.exceptions.VirtualenvCreationException]: do_create_virtualenv( [pipenv.exceptions.VirtualenvCreationException]: File "C:\Users\Iván\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\pipenv\core.py", line 934, in do_create_virtualenv [pipenv.exceptions.VirtualenvCreationException]: raise exceptions.VirtualenvCreationException( [pipenv.exceptions.VirtualenvCreationException]: Traceb I reinstalled pip (19.3.1) and pipenv to be sure, with no change, and my environment variables are correct, I think, they are as follows: Variable (PYTHONPATH) -
Django model for unknown length list of integers
How can I model a list of integers in Django. The actual length of the list is not known. The maximal length should be validated. -
Call back a submit form in Django
I have this Form bellow: FORMS.PY class InsereIdioma(forms.ModelForm): class Meta: model = Idioma fields = '__all__' exclude = ['usuario'] and in my template i have TEMPLATE ... <div id="collapseFour" class="collapse" aria-labelledby="headingFour" data-parent="#accordion"> <div class="card-body"> {{ form.as_p }} </div> </div> ... I need to something like this <div id="collapseFour" class="collapse" aria-labelledby="headingFour" data-parent="#accordion"> <div class="card-body"> {{ form.as_p }} <input class="btn btn-primary" type="submit" name="add_idioma" value="New" /> #if add_idioma is activate, the same form is called again #form.as_p </div> </div> How I do this? Is there some documentation? -
MySQL-Python failed to installl
when I tried pip install MySQL-Python it shows me following error Collecting MySQL-Python Using cached https://files.pythonhosted.org/packages/a5/e9/51b544da85a36a68debe7a7091f068d802fc515a3a202652828c73453cad/MySQL-python-1.2.5.zip Building wheels for collected packages: MySQL-Python Building wheel for MySQL-Python (setup.py) ... error ERROR: Command errored out with exit status 1: command: /var/www/vhosts/midelivery-mmsc.com/httpdocs/venv/bin/python2 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-_SZ6Pz/MySQL-Python/setup.py'"'"'; file='"'"'/tmp/pip-install-_SZ6Pz/MySQL-Python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-qgLn8q --python-tag cp27 cwd: /tmp/pip-install-_SZ6Pz/MySQL-Python/ Complete output (34 lines): running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-2.7 copying _mysql_exceptions.py -> build/lib.linux-x86_64-2.7 creating build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/init.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-2.7/MySQLdb creating build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/init.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/REFRESH.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants running build_ext building '_mysql' extension creating build/temp.linux-x86_64-2.7 gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 -I/usr/include/mysql -I/usr/include/mysql/mysql -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o In file included from _mysql.c:44:0: /usr/include/mysql/my_config.h:3:2: warning: #warning This file should not be included by clients, … -
Migrate django project to new version
I have project build on django 1.8 and python 2.7 . i want to migrate to django 3.0 and python 3.6.8.Is there automatic tool to do so? Easy way to do so, for someone who has only java experience but no python? Thank You -
Javascript getElementbyId.value not returning any value
I've got a problem with my Django project when implementing Javascript to it. This is my HTML: <td> <h5 id="precioSinEnv">{{total}}</h5> </td> This is my JS: function calcular() { var radios = document.getElementsByName('envio'); var pTotal = parseInt(document.getElementById('precioSinEnv').value); console.log(pTotal) if (radios[0].checked) { document.getElementById("precioTotal").innerHTML = pTotal + " €"; } if (radios[1].checked) { document.getElementById("precioTotal").innerHTML = pTotal + 10 + " €"; } if (radios[2].checked) { document.getElementById("precioTotal").innerHTML = pTotal + 4 + " €"; } } The main problem is that {{total}} is obtained as a parameter in views.py, and the value shows up in screen, but at the time of parsint it to int, it doesn't work. Any ideas on how to solve it?