Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get the absolute path of a uploaded file in Django?
Hello django noob here, I am creating a form where user selects the path where he wants to store his results. And for that I am using FileField model to get the file path from user. But when using the following line of code I am not getting the absolute path of the file that user has uploaded. Please take a look at the code to understand better. models.py class UploadImageModel(models.Model): importPath = models.FileField() views.py def uploadImage(request): if request.method == 'POST': input1 = request.FILES.get('import_path') path = UploadImageModel(importPath=input1).importPath.path print(path) return render(request,'home.html') Now, my project is in directory: C:Users/admin/Desktop/MyProject And the output path variable gives is: C:Users/admin/Desktop/MyProject/filename But the original path of uploaded file is: C:Users/admin/Desktop/Data/filname So how do I get the original file path when user uploads a file? Please help me with this issue -
Stack overflow error when running tests in Django
When attempting to run a selenium test in django I am getting the following error: ConnectionResetError: [Errno 54] Connection reset by peer ---------------------------------------- Not found Fatal Python error: Cannot recover from stack overflow. Python runtime state: initialized Thread 0x000070000cc31000 (most recent call first): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/selectors.py", line 415 in select File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 232 in serve_forever File "/Users/nfishel/Documents/capstone-project-film-club/env/lib/python3.8/site-packages/django/test/testcases.py", line 1380 in run File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932 in _bootstrap_inner File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 890 in _bootstrap Current thread 0x00000001113b7dc0 (most recent call first): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/enum.py", line 561 in __new__ File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/enum.py", line 304 in __call__ File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socket.py", line 103 in _intenum_converter File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socket.py", line 920 in getaddrinfo /urllib3/connection.py", line 234 in request The test causing this issue was previously working, but I am trying to create a parent class with alot of the set up functions to cut down on code duplication for the tests. This is the parent class: class ParentTestCase(LiveServerTestCase): def setUp(self): self.selenium = webdriver.Chrome() self.signup() self.pick_genres() def tearDown(self): self.selenium.quit() super(LogoutTestCase, self).tearDown() def signup(self): selenium = self.selenium selenium.get(self.live_server_url + '/register') firstName = selenium.find_element_by_id('id_first_name') lastName = selenium.find_element_by_id('id_last_name') username = selenium.find_element_by_id('id_username') email = selenium.find_element_by_id('id_email') password1 = selenium.find_element_by_id('id_password1') password2 = selenium.find_element_by_id('id_password2') submit = selenium.find_element_by_id('id_register') firstName.send_keys('Test') lastName.send_keys('Tester') username.send_keys('Test123') email.send_keys('test123@test.com') password1.send_keys('moviepass') password2.send_keys('moviepass') submit.click() def pick_genres(self): selenium … -
displaying django custom validation
Hi I am a newbie in Django, so I want to show some error message in html, I have done methods in forms, def clean_FirstName(self): But I want to show that error message near the first name textbox, how I will do it? -
pip won't install channels_redis
for working with django channels i need to install "channels_redis". while installing "channels_redis" i face this error, any thought? by the way i'm on windows and it showed me an error of C++ first and after installing Microsoft visual studio build tools vanished and now this. ERROR: Command errored out with exit status 1: command: 'E:\Programming projects\Django\channels\chat_launch01\venv\Scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\KaNi\\AppData\\Local\\Temp\\pip-install-dt2d0_z3\\hiredis_a7d15f1044b343288a4bc87864c6418e\\setup.py'"'"'; __file__='"'"'C:\\ Users\\KaNi\\AppData\\Local\\Temp\\pip-install-dt2d0_z3\\hiredis_a7d15f1044b343288a4bc87864c6418e\\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 'C:\Users\KaNi\AppData\Local\Temp\pip-wheel-m0bnautd' cwd: C:\Users\KaNi\AppData\Local\Temp\pip-install-dt2d0_z3\hiredis_a7d15f1044b343288a4bc87864c6418e\ Complete output (23 lines): C:\Users\KaNi\AppData\Local\Temp\pip-install-dt2d0_z3\hiredis_a7d15f1044b343288a4bc87864c6418e\setup.py:7: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses import sys, imp, os, glob, io E:\Programming projects\Django\channels\chat_launch01\venv\lib\site-packages\setuptools\dist.py:642: UserWarning: Usage of dash-separated 'des cription-file' will not be supported in future versions. Please use the underscore name 'description_file' instead warnings.warn( running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.9 creating build\lib.win-amd64-3.9\hiredis copying hiredis\version.py -> build\lib.win-amd64-3.9\hiredis copying hiredis\__init__.py -> build\lib.win-amd64-3.9\hiredis running build_ext building 'hiredis.hiredis' extension creating build\temp.win-amd64-3.9 creating build\temp.win-amd64-3.9\Release creating build\temp.win-amd64-3.9\Release\src creating build\temp.win-amd64-3.9\Release\vendor creating build\temp.win-amd64-3.9\Release\vendor\hiredis d:\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.28.29910\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -Ivendor -IE:\ Programming projects\Django\channels\chat_launch01\venv\include -Ic:\users\kani\appdata\local\programs\python\python39\include -Ic:\users\kani\a ppdata\local\programs\python\python39\include -Id:\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.28.29910\include -IC:\Program Files (x86)\Windows Kits\10\include\10.0.10240.0\ucrt /Tcsrc\hiredis.c /Fobuild\temp.win-amd64-3.9\Release\src\hiredis.obj hiredis.c c:\users\kani\appdata\local\programs\python\python39\include\pyconfig.h(200): fatal error C1083: Cannot open include file: … -
Django problem connection after deployment postgres nginx
After deployment on my vps with ubuntu 18.0.4, ngix, gunicorn and postgresql, I can only connect into the admin area but when I try to connect as a simple user I got error 500 it seem like there is not connection between the application and postgres, even when I put wrong email and password I got error 500 but I can connect as I said into the admin Area. Any idea regarding my problem ? Thank you very much. -
no video with supported format and MIME type found in django
no video with supported format and MIME type found A huge screen for video is displayed and says the message above. How do I solve this? This happens to me only in Mozilla Firefox and not on Google Chrome. I am using webm videos and mp4 videos. I'm Uploading a video from the admin panel model.py class Video(models.Model): caption = models.CharField(max_length=70) video = models.FileField(upload_to='video') view.py from .models import Video def home(request): video = Video.objects.all() return render(request, 'video/index.html', {'videos':video}) url.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) home.html {% for video in videos %} <video width="320" height="240" controls> <source src="{{video.video.url}}" type="video/webm"> </video> {% endfor %} -
Hello, im trying to dislpay and image on the django administartion but its just showinig the image extention on the panel
models.py def admin_photo(self): return mark_safe('<img src="()" width="100" />'.format(self.car_image.url)) admin_photo.short_description ="image" admin_photo.allow_tags = True admin.py class CarsAdmin(admin.ModelAdmin): # fields = ('car_name', 'car_image', 'car_model_number', 'car_millage', 'car_description', 'car_price') fields = ('admin_photo',) readonly_fields = ('admin_photo',) list_display = [ 'car_image', 'car_name' ] Hello, im trying to dislpay and image on the django administartion but its just showinig the image extention on the panel -
Django serilizator object updating problem
i would like to ask where could be problem with my serilizator or calling of him. I want to update serializated data inside object personal info but it keep throwing me error: AttributeError: 'PersonalInfoSerializer' object has no attribute 'user' Here's my serilizator class: class PersonalInfoSerializer(serializers.Serializer): user = serializers.IntegerField(required=False) firstname = serializers.CharField(max_length=255) lastname = serializers.CharField(max_length=255) card_id = serializers.CharField(max_length=255) street = serializers.CharField(max_length=255) postal_code = serializers.IntegerField() city = serializers.CharField(max_length=255) debet_card_number = serializers.CharField(max_length=16) created_at = serializers.DateTimeField(required=False) last_update = serializers.DateTimeField(required=False) def create(self, validated_data): return PersonalInfo.objects.create(**validated_data) def update(self, instance, attrs): print("instance", attrs.get('user', instance.user)) instance.user = attrs.get('user', instance.user) instance.save() return instance And here is my view function thats updating serilizator object: json = BytesIO(request.body) data = JSONParser().parse(json) data.update({'created_at': datetime.datetime.now(tz=timezone.utc), 'last_update': datetime.datetime.now(tz=timezone.utc), 'last_login': datetime.datetime.now(tz=timezone.utc), 'token':generate_key()}) user = UserSerializer(data=data) personal_info = PersonalInfoSerializer(data=data) if user.is_valid() and personal_info.is_valid(): if user_exists(data["email"]): response = {'Failed': 'email is already used'} return JsonResponse(response) elif card_exists(data["card_id"]): response = {'Failed': 'card id is already used'} return JsonResponse(response) else: user.save() personal_info = PersonalInfoSerializer(personal_info, {'user':10}, partial=True) personal_info.is_valid() personal_info.save() I think main problem is calling serilizator update but i tried everything :/ Thank you for help :) -
App using Django runs server only once after cloning
I cloned a private GitHub repository that was created using Django into visual studio code and set it up the following way: Open project in visual studio code, there open the project's terminal Create a virtual environment using python -m venv .\venv Active that virtual environment using venv\scripts\activate Import all packages from requirements.txt individually. Since pip freeze -r requirements.txt was giving me an error, I installed each package using pip install packageName Check all models migrated to database with python manage.py makemigrations followed by python manage.py migrate Start server using python manage.py runserver At this point I clicked the local host link and it runs well but after I close the server and try to open it again I first get the error ModuleNotFoundError: No module named 'pymysql'. Then when I do pip install pymysql I get the errors: ModuleNotFoundError: No module named 'rest_framework' OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '<frozen importlib._bootstrap>' After I try and fix the first one by using pip to install rest_framework I only get the same error three times consecutively: Winerror [10061]: No connection could be made because the target machine actively refused it. At this point, I … -
How to solve "FileNotFoundError: [Errno 2] No such file or directory: '/code/static" when deploying a django app to heroku?
I was reading William S. Vincent's book Django for Professionals book, and I tried to deploy a django app to heroku, but static folder location fails while deploying this app, i am using Docker and whitenoise package for handling the static files, here important information in files. settings.py import dj_database_url import socket from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Este cambio es para el despliegue en heroku, ya que hay problemas con los archivos estáticos # para más información vea: https://devcenter.heroku.com/articles/django-assets #BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # El entorno, producción vs desarrollo ENVIRONMENT = os.environ.get('ENVIRONMENT', default='production') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! # por defecto 0, ya que el proyecto estará pronto en producción DEBUG = int(os.environ.get('DEBUG', default=0)) ALLOWED_HOSTS = ['aplicacion-de-ventas.herokuapp.com', 'localhost', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'django.contrib.sites', # 3rd party 'crispy_forms', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.github', 'allauth.socialaccount.providers.google', 'debug_toolbar', # local apps 'pages.apps.PagesConfig', 'ventas.apps.VentasConfig', 'perfiles.apps.PerfilesConfig', ] MIDDLEWARE = [ 'django.middleware.cache.UpdateCacheMiddleware', … -
docker-compose not creating app for django backend
I am not sure why im not able to serve my django app that i am building with Docker and React. So far I am only at the django level (backend) and its not working. I have the following structure: project (main folder) | |__ docker-compose.yml |__ .env (where i store all the custom database name, user and password) > backend > university | |__ Dockerfile |__ requirements.txt |__ manage.py > frontend I havent connected the front end yet. here my configuration of the Dockerfile of the backend FROM python:3.8 ENV PYTHONUNBUFFERED 1 WORKDIR /app/backend/ COPY requirements.txt /app/backend/ RUN pip install -r requirements.txt COPY . /app/backend and the docker-compose of the main project version: '3.7' services: web: build: ./back_end/university restart: unless-stopped command: python /app/backend/manage.py runserver 0.0.0.0:8000 volumes: - .:/app/backend ports: - 8000:8000 depends_on: - db db: image: postgres:11 restart: always environment: - POSTGRES_DB=${DB_NAME} - POSTGRES_USER=${DB_USER} - POSTGRES_PASSWORD=${DB_PASSWORD} volumes: - postgres_data:/var/lib/postgresql/data/ volumes: postgres_data: settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': '${DB_NAME}', 'USER': '${DB_USER}', 'PASSWORD': '${DB_PASSWORD}', 'HOST': 'db', 'PORT': 5432 } } so when i run docker-compose up -d --build it does build everything but im not able to serve runserver and see the regular django app on port 8000 … -
Static Files Not Loading Django
I am following a tutorial, and I copied the repo, Add for some reason, the static files will not load. This is my folder structure involves having my templates file in my main app and my static files are outside this folder. In the main folder (Django-ecommerce) sitting where my main app is. P.S I have tried moving my static folder into my main app folder but it still does not work. here is my settings.py import os ENVIRONMENT = os.getenv('ENVIRONMENT', 'development') DEBUG = False BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '-05sgp9!deq=q1nltm@^^2cc+v29i(tyybv3v2t77qi66czazj' ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'crispy_forms', 'django_countries', 'core' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware' ] ROOT_URLCONF = 'demo.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ 'templates' ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # static files (CSS, JS, Image) STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(BASE_DIR, '/static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root') DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": os.path.join(BASE_DIR, … -
Why am I having this Heroku deploying problem?
I have a Django app to be deployed using Heroku, but something went wrong: Processing /tmp/build/80754af9/asgiref_1594338739818/work ERROR: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: '/tmp/build/80754af9/asgiref_1594338739818/work' Below, my requirements.txt file: asgiref==3.2.10 astroid==2.4.2 certifi==2020.6.20 colorama==0.4.3 dj-database-url==0.5.0 Django==3.0.3 django-heroku==0.3.1 django-widget-tweaks==1.4.5 gunicorn==20.0.4 isort==4.3.21 lazy-object-proxy==1.4.3 mccabe==0.6.1 olefile==0.46 pillow==7.2.0 psycopg2==2.8.5 pylint==2.5.3 python-decouple==3.3 pytz==2020.1 six==1.15.0 sqlparse==0.3.1 toml==0.10.1 whitenoise==5.2.0 wincertstore==0.2 wrapt==1.11.2 I've connected Heroku to a Github repository. Do you have any idea what's happening ? -
I'm trying to build an app using Django framework
localhost showing 'TemplateDoesNotExist' especially when i add path('', include('proapp2.urls')), to the settings.py of the project folder. but as soon as i remove path('', include('proapp2.urls')), the Django homepage start showing. -
Django: annotate ranking from related objects
the models: class Competition(TimeStampedModel): name = models.CharField(max_length=255) class Playlist(TimeStampedModel): competition = models.OneToOneField(Competition, on_delete=models.CASCADE, related_name='playlist') class Entry(TimeStampedModel): title = models.CharField(max_length=255) by = models.CharField(max_length=255) class Vote(TimeStampedModel): entry = models.ForeignKey(Entry, on_delete=models.CASCADE, related_name="votes") score = models.IntegerField(validators=[validate_vote_value]) class PlaylistEntry(TimeStampedModel): playlist = models.ForeignKey(Playlist, on_delete=models.CASCADE, related_name='entries') entry = models.ForeignKey(Entry, on_delete=models.CASCADE, related_name='playlistentries') A Competition has one playlist. A Competition playlist has many PlaylistEntry. A PlaylistEntry is one Entry. One Entry can have multiple Vote. What I was able to achieve: Votes for entries counted. What I need to achieve: Ranking for each Playlist. The code I am using now: def get_context_data(self, **kwargs): ctx = super().get_context_data(**kwargs) ctx["compos"] = Playlist.objects \ .filter(competition__hidden_in_results=False) \ .prefetch_related( Prefetch( "entries", PlaylistEntry.objects .select_related("entry") .annotate(score=Sum("entry__votes__score")) .annotate(rank=Window(expression=Rank(), order_by=F('score').desc())) .annotate(overall_rank=Window(expression=Rank(), order_by=F('score').desc())) .all(), to_attr="compo_entries" )) \ .select_related("competition") \ .order_by("competition__results_play_order") return ctx This gives me Sum of votes for each Entry as I want. It also gives me a ranking as a total in all PlayList. I would need a ranking per Playlist Current output: Playlist Item 1 Rank Overall Score 113. 113. 196 124. 124. 178 Playlist Item 2 Rank Overall Score 56. 56. 336 62. 62. 323 What I would like: Playlist Item 1 Rank Overall Score 1. 113. 196 2. 124. 178 Playlist Item 2 Rank Overall … -
widget attrs with self.helper.layout
I'm trying to use in form this forms: class RequestCreateForm(forms.ModelForm): class Meta: model = Request fields = [ 'supplier', 'status', 'requester', 'Procurement', 'comments', ] widgets = { 'supplier': forms.Select(attrs={ 'class': 'form-group col-md-4 mb-0', }), 'Procurement': forms.Select(attrs={ 'class': 'form-group col-md-4 mb-0', }), 'status': forms.Select(attrs={ 'class': 'form-group col-md-4 mb-0', }), 'comments': forms.TextInput(attrs={ 'class': 'form-group col-md-4 mb-0', 'placeholder': 'Enter comment to be print with PO'}), } def __init__(self, *args, **kwargs): super(RequestCreateForm, self).__init__(*args, **kwargs) self.fields['comments', 'Procurement'].required = False self.fields['requester','status'].widget.attrs['readonly'] = True self.helper = FormHelper() self.helper.form_tag = False self.helper.layout = Layout( Row( Column('supplier', ), Column('status', ), ), Row( Column('Procurement', ), Column('comments', ), ), ) DetailRequestFormSet = inlineformset_factory( Request, RequestDetails, fields=('item', 'typeItem', 'skuinterne', 'skusupplier', 'uomm', 'qty', 'PU', ), extra=3, can_order=True ) but it seems that my template: {% extends "base.html" %} {% load crispy_forms_tags %} {% load tailwind_filters %} {% block content %} <div class="container mx-auto flex flex-wrap"> <div class="w-full mb-6 py-6 flex justify-between items-center border-b border-gray-200"> <div><h3 class="text-2xl text-gray-800">New Request</h3></div> <div><a class="hover:text-blue-500" href="{% url 'items:item_list' %}">Go back to request</a></div> </div> </div> <form method="post"> {% csrf_token %} {% crispy request %} {% for form in requestdetails %} <div class="link-formset"> {% crispy form %} </div> {% endfor %} </form> {% endblock content %} my views: def requestcreateview(request): … -
How can I create unique javascript variable names in a django template for loop?
I am using a django template to loop through hp_tracker objects. Each hp_tracker has its own js code which is used for changing the value via ajax. I'm almost certain I should have this code in the .js file but I was having trouble finding a way to uniquely select each hp_tracker without access to the django template variables in the .js file. So...I moved the js to the html template itself. I am aware this undoubtedly has massive security implications, and I'm open to discussing those as well. Anyway, on to my question. My js fails because I have global variables(!) declared that are not unique. They are being used to control some counters and a setTimeout and I don't see how to now use them to do what I want to do. So the for loop tries to re-declare the same variable over and over. Throughout the rest of the script I'm using JQuery which is perfectly happy to use the django variable {{ hp_tracker.id }}, but javascript is not because "-" characters, which are in the object IDs are not allowed in variable names. What the heck should I do here to fix this hot mess. Is … -
Django as socket.io client
I'm trying to setup a system composed by two servers. One remote express.js api with a socket.io server and a local django one as a socket.io client. For my purpose I want to exchange data frequently between the systems. The problem is that I can't figure out how to integrate a socket.io client with django. I can do it in plain python thanks to the python-socketio package with no problems but integrating it with the framework is tricky. Basically the socket.io client scripts needs to run at django startup and terminate with the server. From what I have understand celery isn't a solution in my case. The socket needs to have access to django database and models system Does anyone have a clean way to implement this? -
Django post operation "violates not-null constraint"
My forms.py: class ReviewForm(ModelForm): class Meta: model = Review fields = ['review_text'] My models.py: class Review(models.Model): reviewer = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user') review_text = models.TextField(max_length=100000) created_time = models.DateTimeField() def __str__(self): return self.question_text def was_published_recently(self): return self.created_time >= timezone.now() - datetime.timedelta(days=1) My views.py: class IndexView(generic.ListView): template_name = 'review/index.html' context_object_name = 'reviews' def get_queryset(self): return Review.objects.order_by('-created_time')[:5] def create(request): if request.method == 'POST': form = ReviewForm(request.POST) if user_form.is_valid(): form.save() return redirect('review:index') else: pass form = ReviewForm() context = { 'form': form, } return render(request,'review/create.html', context) When I create a post, the error message says I'm violating the non-null constraint for "created_time." The message show 1 for id, dfkjdslafd for review_text, and null for created_time and null for reviewer_id. The data is not saved in the database. When I add the following to the forms.py fields = ['id', 'review_text', 'created_time', 'reviewer_id'] The whole app doesn't run, saying 'django.core.exceptions.FieldError: Unknown field(s) (reviewer_id) specified for Review' in the terminal. I am new to django from rails. Finding simple CRUD much more cumbersome with django -- I must be doing something wrong. I'd appreciate any help. -
GroupConcat works in Django 2.x. In Django 3.1 throws "Cannot resolve expression type, unknown output_field"
I have this query to PostgreSQL working in Django 2.2.x and Python 3.5: qs = Things.objects.filter( id__in=distinct_ids ).values('thing_id').annotate( thing_names_concat=Coalesce(GroupConcat('name', '|'), Value('')), subthings_count=Coalesce(Count('subthing',), Value(0)), friends_count=Coalesce(Count('subthing__friends', distinct=True), Value(0)), friend_ids=ArrayAgg('subthing__friends__id'), ) return qs which references: class GroupConcat(Aggregate): function = 'GROUP_CONCAT' template = '%(function)s(%(expressions)s)' def __init__(self, expression, delimiter, **extra): output_field = extra.pop('output_field', CharField()) delimiter = Value(delimiter) super(GroupConcat, self).__init__( expression, delimiter, output_field=output_field, **extra) def as_postgresql(self, compiler, connection): self.function = 'STRING_AGG' return super(GroupConcat, self).as_sql(compiler, connection) Under Django 3.1 & python 3.8, I get this error on the GroupConcat: django.core.exceptions.FieldError: Cannot resolve expression type, unknown output_field Here's a full stack trace: File "/usr/local/lib/python3.8/dist-packages/rest_framework/test.py", line 288, in get response = super().get(path, data=data, **extra) File "/usr/local/lib/python3.8/dist-packages/rest_framework/test.py", line 205, in get return self.generic('GET', path, **r) File "/usr/local/lib/python3.8/dist-packages/rest_framework/test.py", line 233, in generic return super().generic( File "/usr/local/lib/python3.8/dist-packages/django/test/client.py", line 470, in generic return self.request(**r) File "/usr/local/lib/python3.8/dist-packages/rest_framework/test.py", line 285, in request return super().request(**kwargs) File "/usr/local/lib/python3.8/dist-packages/rest_framework/test.py", line 237, in request request = super().request(**kwargs) File "/usr/local/lib/python3.8/dist-packages/django/test/client.py", line 716, in request self.check_exception(response) File "/usr/local/lib/python3.8/dist-packages/django/test/client.py", line 577, in check_exception raise exc_value File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.8/dist-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.8/dist-packages/django/views/decorators/vary.py", line 20, in inner_func response = func(*args, **kwargs) File "/usr/local/lib/python3.8/dist-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return … -
ascending=True not working in django-mptt
Hi good day I'm currently following Django-MPTT documentation and I have a problem using ascending=True. Here's my code: views.py def show_genres(request): Try01 = Genre.objects.filter(name="Rock") context = {'genres': Genre.objects.all(), 'sample_ancestor': Try01.get_ancestors(ascending=True, include_self=True)} return render(request, "sampletemp/startup.html", context) when I'm using ascending=True an error occurs saying: Exception Value: get_queryset_ancestors() got an unexpected keyword argument 'ascending' How can I fix it. Thank you in advance! -
Django Admin OneToMany relationship with search field
I'm using Django 3.1.5. If I have a OneToMany relationship, into Django Admin I will have a select with all possible related models. Is there a way to have this select with a search or it's necessary to implement this from scratch? -
Context with filtering for daterange is not working
I am having a view that is working and properly returning results as long as I am not filtering for dates. As soon as I start to add a filter e.g. booking_time__range = (start_date, end_date) no results are returned in my template. I have no tried to find the error by myself for several days, now I need the wisdom of the crowd. My Model: from django.db import models from django.utils import timezone from users.models import Account from organization.models import Organization, Office class Booking(models.Model): LOCATION_OPTIONS = ( ('H', 'Home Office'), ('O', 'Office'), ('N', 'Not indicated'), ) account = models.ForeignKey(Account, on_delete=models.CASCADE) organization = models.ForeignKey(Organization, on_delete=models.CASCADE) office = models.ForeignKey(Office, on_delete=models.CASCADE) booking_time = models.DateTimeField(default=timezone.now) location = models.CharField(max_length=1, choices=LOCATION_OPTIONS) class Meta: unique_together = ('account', 'booking_time',) My View: def overview_view(request): context = {} if request.method == 'GET': start_date = None end_date = None if request.is_ajax(): booking_times = request.GET.get('day') start_date = datetime.strptime(booking_times, "%Y-%m-%d") end_date = start_date + timedelta(days=4) start_date = start_date.replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=pytz.utc) end_date = end_date.replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=pytz.utc) context['bookings']=Booking.objects.filter( Q(organization_id=request.user.organization_id), Q(booking_time__range = (start_date, end_date)) context['office'] = Office.objects.filter(organization_id__exact=request.user.organization_id) return render(request, 'overview/overview.html', context) return render(request, 'overview/overview.html', context) Both start_date and end_date are datetime.datetime format. As soon as I remove Q(booking_time__range = (start_date, end_date) results … -
Ajax For HTML Generated From Javascript
i have html being generated from javascript to create a list of items. I also need to call a jquery ajax call on each of those items but since it isn't in the html from the page ready i think that might be why the ajax isn't called. when i click the submit button it tries to refresh the page so this shows that the prevent default isn't being run. What am i doing wrong here? Javascript that generates html: buildCollectionList() function buildCollectionList(){ var url = 'http://localhost:8000/api/collection_items_list/' fetch(url) .then((resp) => resp.json()) .then(function(data){ for (var x in data){ var wrapper = document.getElementById(`collection_scroll${data[x].post}`) var product = wrapper.getAttribute('name') //console.log(product) wrapper.innerHTML = '' /*fetch(url) .then((resp) => resp.json()) .then(function(data){ console.log('Data:', data)*/ var list = data for (var i in list){ if ((list[i].saved == true) && (list[i].post == product)){ var item = ` <div class="collection_save_container"> <div class="collection_save_name">${list[i].parent_collection_name}</div> <form class="collection_save_form" action="" method="POST" id="${list[i].collection}" name="${list[i].post}"> <button type="submit" class="collection_save_btn saved" id="save_btn ${list[i].collection} ${list[i].post}"><div class="saved_text ${list[i].collection}">Saved</div></button> </form> </div> </div> ` wrapper.innerHTML += item } else if (list[i].post == product){ var item = ` <div class="collection_save_container"> <div class="collection_save_name">${list[i].parent_collection_name}</div> <form class="collection_save_form" action="" method="POST" id="${list[i].collection}" name="${list[i].post}"> <button type="submit" class="collection_save_btn" id="save_btn ${list[i].collection} ${list[i].post}"><div class="saved_text ${list[i].collection}">Save</div></button> </form> </div> </div> ` wrapper.innerHTML += item } } … -
AttributeError at /login/ 'UserProfile' object has no attribute 'find'
So I am getting this error every time I have created an account and try to login with that account. I am following this tutorial but with my custom template from w3layouts. When I run the code of the guy whose tutorial I am following, I receive the same error on his end. Below Is the ERROR I keep getting. File "C:\Django-E-Commerce\user\views.py", line 37, in login_form request.session[translation.LANGUAGE_SESSION_KEY] = userprofile.language.code AttributeError: 'NoneType' object has no attribute 'code' And here is the code I have on my Views.py @login_required(login_url='/login') # Check login def index(request): category = Category.objects.all() current_user = request.user # Access User Session information profile = UserProfile.objects.get(user_id=current_user.id) context = {'category': category, 'profile':profile} return render(request,'user_profile.html',context) def login_form(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) current_user =request.user userprofile=UserProfile.objects.get(user_id=current_user.id) request.session['userimage'] = userprofile.image.url #*** Multi Langugae request.session[translation.LANGUAGE_SESSION_KEY] = userprofile.language.code # request.session['currency'] = userprofile.currency.code translation.activate(userprofile.language.code) # Redirect to a success page. return HttpResponseRedirect('/'+userprofile.language.code) else: messages.warning(request,"Login Error !! Username or Password is incorrect") return HttpResponseRedirect('/login') # Return an 'invalid login' error message. category = Category.objects.all() context = {'category': category } return render(request, 'login_form.html',context) And Last bUT nOT LEAST. Here is my login.html …