Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I try to connect django with postgreSQL on ubuntu 18.04
I am newbie on django , and I am facing the following issue. I have search for solution on the web but I couldn't find any yet. File "/home/r00t/projects/mp/mp/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "/home/r00t/projects/mp/mp/lib/python3.6/site-packages/psycopg2/__init__.py", line 127, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: invalid port number: "<5432>" settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql' 'NAME': '<mpdb>', 'USER': '<admin>', 'PASSWORD': '<r00t>', 'HOST': '<127.0.0.1>', 'PORT': '<5432>', } } I have tried the following: port no: correct database name: correct user name: correct password: correct Could you please help me out with thanks -
DjangoCMS Plugin to list out specific staff from apphook model
I am new to DjangoCMS. So please bear with me if the question is too trivial. I have made an app hook for adding staff for a website with model.py from django.db import models from filer.fields.image import FilerImageField from djangocms_text_ckeditor.fields import HTMLField from django.urls import reverse from cms.models.fields import PlaceholderField # Create your models here. class Designations(models.Model): class Meta: app_label = 'voxstaff' verbose_name_plural = 'designations' desingation = models.CharField( blank=False, help_text="Please provide a label for the Designation", unique=True, max_length=100 ) def __str__(self): return self.desingation class Staffs(models.Model): class Meta: app_label = 'voxstaff' full_name = models.CharField( blank=False, unique=True, help_text="Please enter the full name of the staff", max_length=100 ) slug = models.SlugField( blank=False, default='', help_text='Provide a unique slug for this staff member', max_length=100, ) desingation = models.ForeignKey( Designations, on_delete=models.SET_NULL, blank=True, null=True ) photo = FilerImageField( blank=True, null=True, on_delete=models.SET_NULL, ) staff_intro = HTMLField(blank=True) bio = PlaceholderField("staff_bio") is_featured = models.BooleanField() def get_absolute_url(self): return reverse("voxstaff:staffs_detail", kwargs={"slug": self.slug}) def __str__(self): return self.full_name class LinkTypes(models.Model): link_type = models.CharField(max_length=100) def __str__(self): return self.link_type class Links(models.Model): staff = models.ForeignKey(Staffs,on_delete=models.CASCADE) link_type = models.ForeignKey(LinkTypes,on_delete=models.SET_NULL,null=True,blank=True) link_url = models.CharField(max_length=200) def __str__(self): return self.link_type.link_type And cms_apps.py as below from cms.app_base import CMSApp from cms.apphook_pool import apphook_pool from django.utils.translation import ugettext_lazy as _ from .menu import StaffSubMenu … -
Django Ordering Fields in django allauth
I am trying to order the fields to be in the order of 'full name', 'email' and then 'password' but right now it is 'email', 'full_name' and then 'password'. Here is the image I tried adding this to my signUp form but it didn't work: if 'keyOrder' in self.fields: self.fields.keyOrder = ['full_name', 'email', 'password'] Here are the rest of my files: forms.py from allauth.account.forms import SignupForm from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django import forms from .models import CustomUser class CustomSignupForm(SignupForm): full_name = forms.CharField(max_length=50, label='Full Name') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['full_name'].widget.attrs.update({'autofocus': 'autofocus'}) # Doesn't work if 'keyOrder' in self.fields: self.fields.keyOrder = ['full_name', 'email', 'password'] for fieldname in ['password1']: self.fields[fieldname].help_text = "Your password" adapters.py Here, I am saving the full name to customuser model from allauth.account.adapter import DefaultAccountAdapter from django import forms class UserAccountAdapter(DefaultAccountAdapter): def save_user(self, request, user, form, commit=True): """ This is called when saving user via allauth registration. We override this to set additional data on user object. """ user = super(UserAccountAdapter, self).save_user(request, user, form, commit=False) user.full_name = form.cleaned_data.get('full_name') user.save() in settings.py These are the django all-auth configuration I set at the bottom of my settings file AUTH_USER_MODEL = 'accounts.CustomUser' # django-allauth config LOGIN_REDIRECT_URL = 'home' ACCOUNT_LOGOUT_REDIRECT … -
How can I create a pdf from a django html with including text, images and graphs (result from an assessment)
I have a django web application generating an assessment result. The result page contains graphs, images and text. I created it using Chart.js I need to generate a pdf file from this same assessment result html. I tried it with pisa.pisaDocument (code bellow), it shows the text and images, but it lost the formating and doesn't show the graphs. I don't know if the problem is on chart.js or pisaDocument. I tried several different ways to generate the pdf file, that's why I'm asking myself if I should change the way I generate the graphs. def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None -
How to save url into django model
I have a model called Photo and looks like this... class Photo(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4) created_at = models.DateTimeField(auto_now_add=True) photo = models.FileField() title = models.CharField(max_length=30) kind = models.CharField(max_length=30) size = models.CharField(max_length=30) strength = models.CharField(max_length=30) combinations = models.CharField(max_length=30) favors = models.CharField(max_length=30) availability = models.BooleanField(default=True) iscarousel = models.BooleanField(default=False) def __str__(self): return "%s %s %s %s %s %s %s %s %s %s" % (self.created_at, self.photo, self.title, self.kind, self.size, self.strength, self.combinations, self.favors, self.availability, self.iscarousel) I am can save to my aws s3 bucket but I do not have a url path to it, or so I believe this is the case. How can I save my model where once I upload my photo the url gets saved in my model as well. So I am thinking that I will need a url field and I know there is a models.UrlField or something like that. I am just curious though how I tell django to extract that url and add it to some field so I can later access it. If I don't have it I don't know how I am suppose to retrieve it to later show it on my web application -
How to test Django JSON-ified ISO8601 Datetime
I'm testing with AjaxResponse with my request factory on a datetime. The problem is the string that Django gives is like this: 2020-08-27T22:46:07.354Z But when I have datetime object, and I use the isoformat() method, I don't get the same string: 2020-08-27T22:46:07.354734+00:00 How am I going to be able to assert? I'm looking to assert by comparing the JSON with my own Python list (The list is what I can customize). -
Django/HTML form input alignment
I'm trying to make something very simple. What I have is currently this: The current code is this: {% extends 'base.html' %} {% load static %} {% block content %} <style> .center { margin: auto; width: 50%; border: 3px solid green; padding: 10px; } </style> <div class='center'> <form action='.' method='POST'> {% csrf_token %} <div align="right"> <input type="text" name='title' placeholder='Food title'/> </div> <div align='left'> <input type="text" name='q' placeholder='Search Image'/> <input type="submit" value='Search!'> </div> {% for image in images %} <img src="{% static 'img/search/' %}{{ image }}", alt=""/> <input type="radio" name="imageRadio" value=" "> </br> {% endfor %} <input type="submit" value='Go!'> </form> </div> {% endblock content %} My issue is, no matter what I try, I can't get the Food title input and the search bar to line up. I would like to have them spaced apart but on the same horizontal line and not one slightly above the other. How can I achieve this? -
Fetch and XMLHttpRequest not working on IOS
Can someone please help me figure this out. Stack: Backend: Django Frontend: Vanilla Javascript/HML/CSS I have a simple web application that downloads a file that is dynamically created from user data. So I have a progress bar that is updated by polling the server to check the current download percentage. It works fine on desktop browsers and even on Android using google chrome, but it is not working on IOS (tested with Safari and Chrome on IOS 14 and IOS 13.3.1) Here is my attempt when using fetch: function updateProgressOld(token) { const statusURL = `/status/download-progress/${token}`; const progressBar = document.getElementById("progress-bar"); const progressMessageDisplay = document.getElementById("progress-message"); fetch(statusURL) .then((response) => response.json()) .then((data) => { let percentProgress = data.download_progress; let downloadToken = data.download_token; let downloadETA = data.download_eta; let progressMessage = data.progress_message; let downloadETADisplay = downloadETA ? `, ETA: ${downloadETA}` : ""; console.log(downloadETADisplay); if (downloadToken === token) { progressBar.style.width = percentProgress; progressMessageDisplay.innerText = `${progressMessage}${downloadETADisplay} ⏳`; if (progressMessage === "done") { progressMessageDisplay.innerText = "Done! File coming your way! 📥"; clearInterval(fetchStatus); } } }); const fetchStatus = setTimeout(updateProgress, 500, token); } I later tried XMLHttpRequest because I thought it might be a compatibility issue and I also tried to use a … -
Filter dates between two dates in Django Orm
I've have this model class Batch(models.Model): id = models.AutoField(primary_key=True); start_date = models.DateField(null=False, blank=False, default=date.today); end_date = models.DateField(null=False, blank=False, default=date.today); description = models.TextField(blank=True); name = models.CharField(max_length=22, null=False, blank=False, default=None); date_created = models.DateField(verbose_name='Date created', default=date.today, editable=False); school = models.ForeignKey(User,on_delete=models.CASCADE, default=None,blank=False,null=False); I need to filter "start_date" and "end_date" to check if a specified date is in between. Something like this SELECT * FROM philiri.group_batch where (Date("04-11-1997") BETWEEN start_date and end_date) Im try to use __range, __lte, __gte , __lt, __gt but it doesn't fit this problem. -
Django Channels 2.4 and Websockets giving 502 error on Elastic Beanstalk and ElastiCache
I have integrated a chat component into my django web app via django channels in a very similar way as documented here. I used elasticache to create my redis instance. My settings.py looks as follows: ASGI_APPLICATION = 'MyApp.routing.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('my-redis-instance.cache.amazonaws.com', 6379)], }, }, } In deploying my application to elastic beanstalk, I have tried following this tutorial and this tutorial with no luck. My django.config file currently looks as follows: container_commands: 01_collectstatic: command: "source /opt/python/run/venv/bin/activate && python manage.py collectstatic --noinput" 02_migrate: command: "django-admin.py migrate" leader_only: true 03_load-data: command: "python manage.py load_database" leader_only: true option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: MyApp.settings aws:elasticbeanstalk:container:python: WSGIPath: MyApp/wsgi.py "aws:elasticbeanstalk:container:python:staticfiles": /static/: "static/" aws:elbv2:listener:80: DefaultProcess: http ListenerEnabled: 'true' Protocol: HTTP Rules: ws aws:elbv2:listenerrule:ws: PathPatterns: /ws/* Process: websocket Priority: 1 aws:elasticbeanstalk:environment:process:http: Port: '80' Protocol: HTTP aws:elasticbeanstalk:environment:process:websocket: Port: '5000' Protocol: HTTP I also tried creating a Procfile to configure gunicorn and daphne. It looks like this: web: gunicorn --bind :8000 --workers 3 --threads 2 MyApp.wsgi:application websocket: daphne -b 0.0.0.0 -p 5000 MyApp.asgi:application The security groups that are attached to my ElastiCache redis instance have an inbound rule with Custom TCP set to port 6379 and the source set to Any. In trying all … -
Django check if queryset QUERIES are equal WITHOUT evaluation
How to check if two QuerySet objects will result into the same query without evaluation? > q1 = MyModel.objects.all() > q2 = MyModel.objects.all() > q1 == q2 False Please note, that I don't need to compare the results that the queryset will return. I need to identify when two non-evaluated queryset objects will result into the same query. If I try > q1.query == q2.query False it doesn't work, as the Query object doesn't have __hash__ defined properly inside. I can do > str(q1.query) == str(q2.query) True But this is still heavy operation as it will require Django to traverse models fields, validate the query, compile SQL code, etc. Is there any better way to do that? -
Django-Oscar - Forking nested applications
I'm having trouble forking Django-oscar apps that are a part of a sub-set of other Django-oscar apps. For the documentation/tutorial I am following along with, view here. I have gone though and successfully forked the applications that aren't nested in others and updated my installed apps accordingly. Heres a subset of the apps to demonstrate the general pattern of the nested applications 'dashboard_folder.dashboard.apps.DashboardConfig', 'oscar.apps.dashboard.reports.apps.ReportsDashboardConfig', 'oscar.apps.dashboard.offers.apps.OffersDashboardConfig', However, the docs (linked above) do not clearly outline how to call the nested applications. I thought they might be forked automatically with their "parents" however, a simple test (code below) proved other-wise: If I change 'oscar.apps.dashboard.reports.apps.ReportsDashboardConfig', to dashboard_folder.dashboard.reports.apps.ReportsDashboardConfig', I get the following error: ModuleNotFoundError: No module named 'dashboard_folder.dashboard.reports' I figured id try a few 'educated' guesses as to how to call the nested apps to fork them however all of the following unfortunately failed: manage.py oscar_fork_app offers offers_folder CommandError: There is no app with the label 'offers' manage.py oscar_fork_app dashboard.offers offers_folder CommandError: There is no app with the label 'dashboard.offers' manage.py oscar_fork_app ReportsDashboard ReportsDashboard_folder CommandError: There is no app with the label 'ReportsDashboard' manage.py oscar_fork_app reportsdashboard ReportsDashboard_folder CommandError: There is no app with the label 'reportsdashboard' manage.py oscar_fork_app dashboard/reportsdashboard ReportsDashboard_folder CommandError: There is no … -
relationships in django which one to use
I am having trouble trying to decide what kind of relationship I should use for my application. I want to have a database that shows something like... A Movie table with fields title, year, language, description, duration and so on. A User table with fields username, email (I am new to django and am not worrying about authentications or passwords or any of that for now) I want a user to be able to favorite a movie so I am trying to wrap my head around how it would actually work, for instance, would it be a user can favorite many movies and a movie can be favorited by many users (this makes sense to me) or is it a user can favorite many movies and a movie is favorited by a user. so If I pick the second option I guess it would be a one-to-many rather than the first option which is a many-to-many relationship. However, I am not sure which one is actually correct. After looking at the docs in django for many-to-one I see that a foreign key should be given to the Movie that references a user from User but they use an option that … -
Static files are not served but accessible directly. Django, docker, nginx
I am trying to dockerize a django project with postgres, gunicorn and nginx. My problem is that static files are not served. However in browser console I see all static files being loaded properly (code 200). Also I can easily access any static file directly i.e. 127.0.0.1:8080/static/admin/.../base.css. Nginx doesn't show any errors in console either. What makes it even more strange for me, my redoc.yaml is loaded properly. Here is part of my settings.py with static: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') Here is my main Dockerfile: FROM python:latest RUN mkdir /code COPY requirements.txt /code RUN pip install -r /code/requirements.txt COPY . /code WORKDIR /code CMD gunicorn api_yamdb.wsgi:application --bind 0.0.0.0:8000 Here is the Dockerfile for nginx: FROM nginx:latest COPY nginx/nginx.conf /etc/nginx/nginx.conf Here is the nginx.conf file: events {} http { server { location /static/ { root /etc/nginx/html/; } location / { proxy_pass http://web:8000; } } } And finally here is my docker-compose: version: '3.8' volumes: postgres_data: static: services: db: image: postgres:latest volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env web: build: . restart: always command: gunicorn api_yamdb.wsgi:application --bind 0.0.0.0:8000 volumes: - static:/static ports: - "8000:8000" depends_on: - db env_file: - ./.env nginx: build: context: . dockerfile: nginx/Dockerfile ports: - "8080:80" volumes: … -
Django Rest Framework serialized image returns absolute system url, and not amazon s3 url
I'm currently using django-storages with my application for hosting static and media files. I'm also using imagekit on image uploads to create multiple versions of an image needed across the application. The problem arises when trying to serialize the images urls. DRF returns a url such as http://127.0.0.1:8000/media/CACHE/images/categories/tilbeh%C3%B8r/tilbehor/2fbf015bd21dba581f5d306ed4248b47.jpg, and when opening this, its returns a completely blank page. What i really need is for it to return the "real" storage url, e.g. https://domain.s3.amazonaws.com/static/media/CACHE/images/categories/tilbeh%C3%B8r/tilbehor/2fbf015bd21dba581f5d306ed4248b47.jpg. S3 settings: # aws settings AWS_ACCESS_KEY_ID = 'secret' AWS_SECRET_ACCESS_KEY = 'secret' AWS_STORAGE_BUCKET_NAME = 'domain' AWS_DEFAULT_ACL = 'public-read' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} AWS_LOCATION = 'static' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), # os.path.join(BASE_DIR, 'frontend/dist'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' MEDIA_ROOT = 'static/media' MEDIA_URL = '/media/' models.py class Category(models.Model): def upload_content_file_name(instance, filename): """ Return the location of which to upload the file """ return os.path.join('categories/%s/' % instance.name.lower(), filename) name = models.CharField( _('category name'), max_length=255, unique=False ) ... image = models.ImageField( _('image'), upload_to=upload_content_file_name, help_text=_( 'Category image, should only be used on top level parents!' ), blank=True, null=True, ) image_default = ImageSpecField(source='image', processors=[ResizeToFill(375, 375)], format='JPEG', options={'quality': 90}) image_sm = ImageSpecField(source='image', processors=[ResizeToFill(640, 300)], format='JPEG', options={'quality': 90}) image_md = ImageSpecField(source='image', processors=[ResizeToFill(768, 366)], format='JPEG', options={'quality': … -
Django and ReactJS show how many visitor online now
I am trying to show how many visitors are on my website at this moment. i mean, I want to show many visitors are online at this moment, not how many users, Can anyone please suggest me what is the best way to do this? do i need to use WebSocket or there are any better option to do this? Can you please advise me regarding this? -
Searching query
I am searching for a query using python in Django, the terminal shows it is a success but the query does not show on the search result. I don't understand what to do please help. views.py functions we are to use to retrieve query templates page view -
How to run commands from docker-compose.yml to start couchdb
I have a webapp written in django which i need to connect with couchdb both are running on docker container. But i'm unable to figure out how to achieve this as there is no good material available for reference. I have tried the below codes but it is throwing the following error. docker-compose.yml version: '3' services: web: build: . command: python ./webapp/server.py volumes: - .:/code - ./webapp/static:/static networks: - couchserver_network depends_on: - couchserver couchserver: image: couchdb ports: - "5984:5984" command: curl -u rob:123456 -X PUT localhost:5984/_users environment: - COUCHDB_USER=rob - COUCHDB_PASSWORD=123456 volumes: - ./dbdata:/opt/couchdb/data networks: - couchserver_network networks: couchserver_network: driver: bridge Error thrown : 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0curl: (7) Failed to connect to localhost port 5984: Connection refused If i remove the line "command: curl -u rob:123456 -X PUT localhost:5984/_users" below error is thrown : couchserver_1 | {database_does_not_exist,[{mem3_shards,load_shards_from_db,"_users",[{file,"src/mem3_shards.erl"},{line,399}]},.... This is my Dockerfile : FROM python:3.6-slim-buster ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ Any sort of help is really appreciated One more query : what does the below lines do. I'm novice into docker and this is my first hands on … -
Django Weasyprint: Timeout error loading css while site is hosted on PythonAnywhere
I'm struggling to use Django WeasyPrint correctly while exporting a template to PDF. This issue only occurs on the PythonAnywhere version; using the view on localhost works as intended. Using any other view with the same stylesheets on PythonAnywhere also works fine. The errors occur when loading these two resources: <link rel="stylesheet" href="{% static 'css/boostrap4.5.2.css' %}"> <link rel="stylesheet" href="{% static 'css/blog.css' %}"> (note: I originally used a cdn for the bootstrap css but was finding a 403 forbidden error when WeasyPrint tried to get it instead, gave up on that one) Here's the error log when weasyprint tries to use it: Failed to load stylesheet at http://kirkmania.pythonanywhere.com/static/css/boostrap4.5.2.css : timeout: timed out Failed to load stylesheet at http://kirkmania.pythonanywhere.com/static/css/blog.css : timeout: timed out And here's the server log: SIGPIPE: writing to a closed pipe/socket/fd (probably the client disconnected) on request /cv/export (ip 10.0.0.52) !!! uwsgi_response_writev_headers_and_body_do(): Broken pipe [core/writer.c line 306] during GET /cv/export (10.0.0.52) SIGPIPE: writing to a closed pipe/socket/fd (probably the client disconnected) on request /static/css/boostrap4.5.2.css (ip 10.0.0.52) !!! uwsgi_response_write_headers_do(): Broken pipe [core/writer.c line 248] during GET /static/css/boostrap4.5.2.css (10.0.0.52) SIGPIPE: writing to a closed pipe/socket/fd (probably the client disconnected) on request /static/css/blog.css (ip 10.0.0.52) !!! uwsgi_response_write_headers_do(): Broken pipe [core/writer.c line 248] … -
Django : Iphone picture localisation
I hope you're well. I'm creating a Picture model and I was wondering if there is any way store automatically in DB the picture localisation when an Iphone user upload it? class Picture(models.Model): catego = models.ForeignKey(Catego,on_delete=models.CASCADE,related_name="catego_pictures") user = models.ForeignKey(User, blank=True, null=True,on_delete=models.CASCADE,related_name='user_pictures') image = models.ImageField(null=True,blank=True, upload_to='nutri/') localisation = models.CharField(null=True,blank=True,max_length=300) publishing_date = models.DateField(auto_now_add=True) def __str__(self): return self.catego.title Have a good day, -
Add custom users with a specific attribute to the 'friends' list
I have implemented the logic of adding users to the 'friend list' from the whole list of users. models.py class VendorList(models.Model): users = models.ManyToManyField(User) current_user = models.ForeignKey(User, related_name='owner', on_delete=models.SET_NULL, null=True) @classmethod def add_vendor(cls, current_user, new_vendor): vendor, created = cls.objects.get_or_create( current_user=current_user ) vendor.users.add(new_vendor) @classmethod def remove_vendor(cls, current_user, new_vendor): vendor, created = cls.objects.get_or_create( current_user=current_user ) vendor.users.remove(new_vendor) views.py class VendorListView(TemplateView): template_name = 'event/vendor_list.html' def get(self, request): #form = EventItemModelForm() users = User.objects.exclude(id=request.user.id) vendor = VendorList.objects.get(current_user=request.user) vendors = vendor.users.all() args = { #'form': form, 'users': users, 'vendors': vendors } return render(request, self.template_name, args) def change_vendor_list(request, operation, pk): vendor = User.objects.get(pk=pk) if operation == 'add': VendorList.add_vendor(request.user, vendor) elif operation == 'remove': VendorList.remove_vendor(request.user, vendor) return redirect('/vendors/') It works and provides the list of all users whom I can add to the list. However, I need to filter this 'whole' list and display only users who have is_vendor attribute (similar to is_staff). Where should I filter users, in models or views? I have tried vendors = vendor.users.filter(is_vendor=True) which doesn't work. -
How to install Pip on a new Ubuntu upgrade
At the suggestion of others working on what was a functional Django project, I upgraded to a more recent version of Ubuntu (18). However, when I first try to run it it blows up at line 3 of the initial script module when asked to import django as a package. I tried pip -r requirements.txt, but the system said pip was an unknown package. I dropped down and used apt to load pip onto my machine (sudo apt-get pip), then tried using pip itself (pip update pip) which failed.: I also tried "pip install django", and got this: I would have thought an OS upgrade would not require re-installing all currently installed packages (seems like a no-brainer to do the work of installing everything that had been installed). But right now I am terribly stuck...obviously, having 'pip' let's you (at least) have a basic CLI tool. Any advice? -
modelformset_factory alter data after form submit
I have a modelformset_factory with some fields, and I combine it with other data from the PartRelation in a CreateView (like name, price, color ...). forms.py: class PartRelationForm: form = modelformset_factory(PartRelation, fields=("part", "qty", ), widgets={'part': forms.Select(), 'qty': forms.NumberInput()}) views.py: class PartsMixin(object): def post(self, request, *args, **kwargs): inquiry_form = InquiryModelForm(request.POST) parts_form = PartRelationForm().form(request.POST, prefix='part2inq') if inquiry_form.is_valid() and parts_form.is_valid(): i = inquiry_form.save() for form in parts_form: p = form.save(commit=False) p.inquiry = i p.save() return redirect ... return render ... class PartCreateView(PartsMixin, CreateView): model = Part the corresponding model (relation): class Part2InqRelation(CommonFunctionalities, models.Model): part = models.ForeignKey(PartBase, on_delete=models.CASCADE) qty = models.PositiveIntegerField("Quantity") inquiry = models.ForeignKey(Inquiry, related_name='inq_part', on_delete=models.CASCADE) As soon as I have no qty or no part in my form, the is_valid() method always fails. How can I alter or delete the data in the PartRelationForm before the validation? I tried iterating through them and setting them None or an other approach with cleaned_data without success already. -
Django heroku connect read-write primary key issue
i am using djagno-heroku-connect library,salesforce and heroku connect link below for library https://github.com/Thermondo/django-heroku-connect So the problem that i am facing is i have one model that is marked as read-write, so which field should i make as primary key, I can't make sf_id as pk, because when i create one object it won't be there, as this is provided by salesforce As suggested in docs create external_id, but this won't be present if data from salesforce is synced back to my database let's say postgres There is one id field in postgres which is used by heroku connect and its suggested in docs on not to use that and i am not willing to user salesforce API for this, is there any approach to do this? Thanks in advance -
Form error message overrides model error message
I have a model: from django.contrib.postgres.fields import ArrayField class Profile(models.Model): phone = ArrayField(PhoneField(max_length=20, blank=True), verbose_name="Phone number", blank=True, error_messages={'item_invalid': 'Phone %(nth)s is invalid:'}) PhoneField is simple: class PhoneField(models.CharField): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.validators.append(validators.PhoneValidator()) And the PhoneValidator: class PhoneValidator(): def __call__(self, value): phone = self.clean(value) if not (10 <= len(phone) <= 15): raise ValidationError('The phone number must contain from 10 to 15 digits.') def clean(self, value): return ''.join([d for d in value if d.isdigit()]) Then I created a simple form: class ProfileForm(forms.ModelForm): class Meta: model = Profile And when I fill something like 111,222 to the Phone field I expect to get the following error: Phone 1 is invalid: The phone number must contain from 10 to 15 digits.. But instead I get a generic error Item 1 in the array did not validate: without any details. I found out why does this happen. BaseModelForm overrides model error messages with form error messages: # django.forms.models def _update_errors(self, errors): # Override any validation error messages defined at the model level # with those defined at the form level. opts = self._meta ... for field, messages in error_dict.items(): if (field == NON_FIELD_ERRORS and opts.error_messages and NON_FIELD_ERRORS in opts.error_messages): error_messages = opts.error_messages[NON_FIELD_ERRORS] elif …