Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Crop Images in a Django Application *JavaScript Issue*
I am having issues with my JavaScript code, and I am trying to get the image crop (picture) below to pop up but when I click the Choose File button but nothing happens. I am following https://simpleisbetterthancomplex.com/tutorial/2017/03/02/how-to-crop-images-in-a-django-application.html and it is a little outdated so I was wondering if anyone could help point out what part of the code is out of date. If someone could help that would be much appreciated. {% block javascript %} <script> $(function () { /* SCRIPT TO OPEN THE MODAL WITH THE PREVIEW */ $("#id_file").change(function () { if (this.files && this.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $("#image").attr("src", e.target.result); $("#modalCrop").modal("show"); } reader.readAsDataURL(this.files[0]); } }); /* SCRIPTS TO HANDLE THE CROPPER BOX */ var $image = $("#image"); var cropBoxData; var canvasData; $("#modalCrop").on("shown.bs.modal", function () { $image.cropper({ viewMode: 1, aspectRatio: 1/1, minCropBoxWidth: 200, minCropBoxHeight: 200, ready: function () { $image.cropper("setCanvasData", canvasData); $image.cropper("setCropBoxData", cropBoxData); } }); }).on("hidden.bs.modal", function () { cropBoxData = $image.cropper("getCropBoxData"); canvasData = $image.cropper("getCanvasData"); $image.cropper("destroy"); }); $(".js-zoom-in").click(function () { $image.cropper("zoom", 0.1); }); $(".js-zoom-out").click(function () { $image.cropper("zoom", -0.1); }); /* SCRIPT TO COLLECT THE DATA AND POST TO THE SERVER */ $(".js-crop-and-upload").click(function () { var cropData = $image.cropper("getData"); $("#id_x").val(cropData["x"]); $("#id_y").val(cropData["y"]); $("#id_height").val(cropData["height"]); $("#id_width").val(cropData["width"]); … -
In my Django and DRF project, I get Server error for my right-working link, and 404 not found page for missing url after adding 404 page
Hi, I have Blog post project some functionalities made with DRF and some functionalities made with Django.I need to add 404 page for missing urls. But If I use right-working link, I will get server error, However, I will get 404 page for missing url. For example, urls such as '127.0.0.1:8000/en/me' or '127.0.0.1:8000/en/me/contact/' or '127.0.0.1:8000/en/book' will bring server error, but url '127.0.0.1:8000/en/men' return not found page in my django_project/urls.py: from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from rest_framework import permissions from drf_yasg.views import get_schema_view from drf_yasg import openapi from django.conf.urls.i18n import i18n_patterns # from django.conf.urls import handler404 from my_works import views as my_works_views schema_view = get_schema_view( openapi.Info( title="API Docs", default_version='v1', description="API urls description", terms_of_service="https://www.myblogs.com/policies/terms/", contact=openapi.Contact(email="aahmadov271101@gmail.com"), license=openapi.License(name="Test License"), ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), path('i18n/', include('django.conf.urls.i18n')), ] urlpatterns += i18n_patterns ( path('', include('my_works.urls')), path('me/', include('accounts.urls')), path('admin/', admin.site.urls), ) urlpatterns+= (static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)) urlpatterns+= (static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)) handler404 = 'accounts.views.error_404_view' admin.site.site_header = 'Alimardon Mustafoqulov Administration' admin.site.site_title = 'Administration' admin.site.index_title = 'Administration page' in my django_app/urls.py: from django.urls import path, include from django.conf.urls.i18n import i18n_patterns from .views import ( ArticlesViewList, BooksViewList, PresentationsViewList, ProjectsViewList, EventsViewList, VideosViewList, ) … -
Django programming: cannot cast time without time zone to timestamp
I am newbie to django and was using SQLite during development, when i moved to postgres when trying to deploy to production i get the below error Cannot cast type time without time zone to timestamp with time zone settings.py Django settings for todoBackend project. Generated by 'django-admin startproject' using Django 3.2.5. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path from django.core.management.utils import get_random_secret_key import os import sys import dj_database_url # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", get_random_secret_key()) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.getenv("DEBUG", "False") == "True" ALLOWED_HOSTS = os.getenv("DJANGO_ALLOWED_HOSTS", "127.0.0.1,localhost").split(",") # Application definition INSTALLED_APPS = [ "rest_framework", "corsheaders", "api.apps.ApiConfig", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] CORS_ALLOW_ALL_ORIGINS = True ROOT_URLCONF = "todoBackend.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "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", ], … -
Change django form fields based on a value from a dropdown
I am trying to make a form in django which needs to update itself based on a value from a dropdown. Here is my forms.py file. class LeadForm(forms.Form): CHOICES=[(0,'option A'), (1,'option B')] radio_button = forms.ChoiceField(choices=CHOICES, widget=forms.Select()) test_field_A = forms.CharField(widget=forms.TextInput()) test_field2A = forms.CharField(widget=forms.TextInput()) test_fieldB = forms.CharField(widget=forms.TextInput()) test_field2B = forms.IntegerField(min_value=0) If "option A" is selected from the drop down, I need only the fields containing "A" in the end. And I only need testfield_2A and test_field2B if 'option B' is selected. Can I achieve this with Django alone or do I need to write Javascript/Jquery? Also do I need to write separate forms for these two cases? Thanks in advance. -
No username attribute of model error, even already have objects = UserManager()?
Here is my model in the user app from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin class UserTable(AbstractBaseUser, PermissionsMixin): USERNAME_FIELD='email' objects = UserManager() email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) phone = models.CharField(max_length=255, default=None) is_active = models.BooleanField(default=False) Here is my admin.py inside the user app. from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import UserTable admin.site.register(UserTable, UserAdmin) I also included in my settings.py INSTALLED_APPS = [ .... 'user.apps.UserConfig', .... ] This is the error when I run python manage.py migrate (admin.E033) The value of 'ordering[0]' refers to 'username', which is not an attribute of 'user.UserTable'. The value of 'list_display[0]' refers to 'username', which is not a callable, an attribute of 'UserAdmin', or an attribute or method on 'user.UserTable'. I dont know why, I thought when I set objects = UserManager() fields like username, first_name, last_name is setted up. I also user USERNAME_FIELD to set email replacing the username primary key. -
Python code changes are not reflecting on the Django Web server (httpd with mod_wsgi package)
I have been hosting a django-based web server (httpd with mod_wsgi package) on Linux CentOS 7. I used to reflect the changes made in my code by restarting the web server using the following command: sudo systemctl stop httpd sudo systemctl start httpd and it would reflect the changes smoothly. Since few days back this strategy does not work at all. That is, whenever I make any change in my python code, even simply printing a message in log file, it is not reflected. I reboot the VM and only then the code changes were reflected. I tried the following things already which did not help at all: Clearing .pyc files Restarting/Reloading httpd server touch wsgi file All of the above mentioned tries did not appear to work. The changes are only reflected when the VM is rebooted. This problem has just started occurring 3-4 days ago and it was completely working before. Any help or suggestions are highly appreciated. Thanks. -
Javascript is Loading Page Too Soon - Django Edit Form
I'm trying to edit an existing post (form) on my site but when I click 'edit' I get this in the console: Fetch finished loading: POST "http://127.0.0.1:8000/edit_post/18". Status is 201 so I think the page is skipping over most of the javascript and directly posting it/saving to server. Also when I click 'edit' a text box is immediately supposed to appear with my post text already there. But this never opens, it just says fetch finished loading appropriately in the console. How can I make sure all the Javascript is run first? I tried using preventDefault and keep running into Uncaught type errors. I'm pretty new to Javascript so I'm still learning this. For example, one thing I tried within the event_handeler function was: document.querySelectorAll("#textarea").addEventListener("submit", function(event) { document.querySelector(`#post-edit-${id}`).innerHTML += "Sorry!"; event.preventDefault(); }) But I got uncaught type errors. function edit_handeler(element) { id = element.getAttribute("data-id"); document.querySelector(`#post-edit-${id}`).style.display = "block"; document.querySelector(`#post-content-${id}`).style.display = "none"; edit_btn = document.querySelector(`#edit-btn-${id}`); edit_btn.textContent = "Save"; edit_btn.setAttribute("class", "text-success edit"); if (edit_btn.textContent == "Save") { edit_post(id, document.querySelector(`#post-edit-${id}`).value); //here edit_btn.textContent = "Edit"; edit_btn.setAttribute("class", "text-primary edit"); }} function edit_post(id, post) { const body = document.querySelector(`#post-content-${id}`).value; fetch(`/edit_post/${id}`, { method: "POST", body: JSON.stringify({ body:body }) }).then((res) => { document.querySelector(`#post-content-${id}`).textContent = post; document.querySelector(`#post-content-${id}`).style.display = "block"; document.querySelector(`#post-edit-${id}`).style.display … -
How Can I Validate Two Fields from Two different models using Django forms
I have two Models (Product and Sales) and the two models have their respective django forms modeled accordingly. The Product Model has a field named price while the Sales Model has a field named sellingprice. In my Validation rule I want to validated these two fields from two different models (Product and Sales) during user submission on one Django form. I want to check if the Product price is not less than or equal to the sellingprice of the Sales Model. Below is what I am trying to do but getting errors. from django import forms from django.core.exceptions import ValidationError class SalesForm(forms.Form): class Meta: model = Product, Sales fiels = __all__ ... def clean(self): cleaned_data = super().clean() product_price= cleaned_data.get("product_price") selling_price= cleaned_data.get("selling_price") if selling_price > product_price: # Only do something if both fields are valid so far. else: raise ValidationError( "Selling Price can not be less than or equal to Product Price " ) -
ModuleNotFoundError: No module named 'rest_framework' when running celery -A backend worker -l info
I'm trying to run my tasks and I'm currently using Celery for this alongside Django and DjangoRestFramework This is how I've set things up, root directory is also called backend . ├── backend │ ├── asgi.py │ ├── celery.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── db.sqlite3 ├── manage.py └── save_to_db ├── admin.py ├── apps.py ├── dump.rdb ├── migrations │ ├── 0001_initial.py │ └── 0002_auto_20210728_0251.py ├── models.py ├── serializers.py ├── tasks.py ├── tests.py ├── urls.py └── views.py So I have all my configuration for Celery in celery.py which I followed from this on how to set up Celery for Django https://docs.celeryproject.org/en/stable/django/first-steps-with-django.html This is how my config looks like import os from celery import Celery # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings') app = Celery('backend') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django apps. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') I decided to run this command to get Celery started celery -A backend worker -l info But … -
Django: sql works well in mysql but gives error in cursor.execute
put sql sentence in sqlyog SELECT `v` ,`t` FROM `pm` WHERE `id`='12'; the true return is: v t ------- ------------- 13.32 23 13.319 23 13.319 23 but when I use cursor.execute() in django, it only returns one result and my code in django is: sql = "select v,t from pm where id = '12'" cursor = connection.cursor() cursor.execute(sql) V = cursor.fetchall() print(V) return result: ((13.319, 23.0),) if I use fetchone(),it will return one tuple ((13.319, 23.0)) This problem is really strange, and I hope that somebody can give me some hints. THANK YOU SOOOO MUCH! -
why django email message attach file use .file.name not .url?
In my django project: email.attach_file(self.object.pic.url) --> error no such file email.attach_file(self.object.pic.file.name) --> ok It make me confusing. -
Does a signal from a Parent model trigger when a child model is changed?
I've developed a custom library to sync some models. So, there is a Parent Model, called SyncModel on this library that has some child on my Django app. In this library, there is a receiver function to activate when someone makes a delete. Here is the function: @receiver(post_delete) def on_object_deletion(sender, instance, **kwargs): """Upload deleted object to cloud if it is part of synced model""" deletion_time = datetime.datetime.now() # Retrieve the metadata (app and model name) for the model contenttype = ContentType.objects.get_for_model(model=instance) # Skip unnecessary database lookup (never syncs its own models) if contenttype.app_label == "lakehouse_sync": return syncmodel = SyncModel.try_retrieve_model(contenttype.app_label, contenttype.model) if not syncmodel: return # Raise exception if the instance is not BaseSyncModel. # Should be caught during clean() though. if not isinstance(instance, BaseSyncModel): raise Exception("Cannot sync a model that does not inherit BaseSyncModel") # Manually update the timestamp so the lakehouse can merge data instance.updated_at = deletion_time # Write the serialized object to the cloud blacklist = syncmodel.get_blacklist() serialized = Serializer.serialize_object(instance, blacklist) CloudActions.write_delete_file( contenttype.app_label, contenttype.model, serialized.getvalue() ) And, in the apps.py file I added this receiver: def ready(self): """Import signals""" from lakehouse_sync.core import delete_action post_delete.connect(delete_action, sender=SyncModel, dispatch_uid=model.__name__) print('deleting') for model in SyncModel.__subclasses__(): post_delete.connect(delete_action, sender=model, dispatch_uid=model.__name__) My problem is related … -
No route matches the given query
I am having trouble loading my page as I am getting a 'Page Not Found' error that states 'no route matches the given query'. I believe this has to do with the first line in my views.py where I get the search variable. When I take out the search variable it says that it returns multiple routes (which I do have in my Django admin panel) but I am unsure how to change this so it could load the page and request? urls.py urlpatterns = [ path('', calc_distance, name='calc_distance') ] views.py def calc_distance(request): search = get_object_or_404(Route, id=1) form = DistanceMeasureForm(request.POST or None) geolocator = Nominatim(user_agent='distance') ip = '72.80.77.214' city, country, long_lat = use_ip(ip) latitude = long_lat.get('latitude') longitude = long_lat.get('longitude') city = long_lat.get('city') location = geolocator.geocode(city) print(location) l_lat = latitude l_long = longitude start = (l_lat, l_long) if form.is_valid(): lookup = form.save(commit=False) arrival_location = form.cleaned_data.get('arrival_location') arrival = geolocator.geocode(arrival_location) # print(arrival) end_latitude = arrival.latitude end_longitude = arrival.longitude end = (end_latitude, end_longitude) distance = geodesic(start, end).km lookup.location = location lookup.distance = distance lookup.save() context = { 'form': form, 'search': search } return render(request, 'home.html', context) Models.py class Route(models.Model): location = models.CharField(max_length=200) arrival_location = models.CharField(max_length=200) distance = models.DecimalField(max_digits=10, decimal_places=2) created = models.DateTimeField(auto_now_add=True) def __str__(self): … -
I want to create a counter that filters out uploaded videos into different categories with different time filters (daily/weekly/monthly) any idea how
So I am trying to develop a web app and there's this part of project where I need to provide a counter that displays the number of videos uploaded and its corresponding status of the videos uploaded such as (Succesfully uploaded,uploading, pending upload, failed upload etc.). I also need to filter it into dates such as (daily/weekly/monthly) stats. Im using python and django on ubuntu and Im kinda new on it any idea how? -
Database query not working for Heroku deployment of Django/Python Project
I am deploying a Django project on Heroku. The deployment is successful and most functions of my web app are running just fine. However, I am having an issue with a single database query that seems not to work correctly on Heroku but works just fine on localhost. I am using this url_pattern: path('category/<str:cats>/', CategoryView, name='category'), Then in my views, I am running this queryset filter in my CategoryView: def CategoryView(request, cats): category_articles = Article.objects.filter(category=cats.replace('-', ' ')) return render(request, 'category.html', {'cats': cats.title().replace('-', ' '), 'category_articles': category_articles}) I don't have a Category Model. Instead, I am using forms.py to run category choices as follows: CATEGORY_CHOICES = ( ('Politics', 'Politics'), ('Business', 'Business'), ('Updates', 'Updates'), ('Education', 'Education'), ) class ArticleForm(forms.ModelForm): class Meta: model = Article fields = ('article_image', 'author', 'title', 'category', 'body') widgets = { 'article_image': forms.ClearableFileInput(attrs={'class': 'form-control'}), 'author': forms.Select(attrs={'class': 'form-control'}), 'title':forms.TextInput(attrs={'class': 'form-control'}), 'category': forms.Select(choices=CATEGORY_CHOICES, attrs={'class':'form-control'}), 'body': forms.Textarea(attrs={'class':'form-control',}), The following is my Article Model: class Article(models.Model): article_image = models.ImageField(null=True, blank=True, upload_to="images/") author = models.ForeignKey(User, null=False, blank=False, on_delete=models.CASCADE) title = models.CharField(max_length=100) category = models.CharField(max_length=40) body = models.TextField() def __str__(self): return self.name The html form has the select option for the choices provided. Once selected, an option is stored in the database when the user … -
Issue with creating a new object with a form (Django)
I am using the Django framework to build a website. This website is user based and each user has a profile model. Right now, I am working on building a system where each user can input their job experience. I want it so that you can input a category, and then fill out points for each category. (For example, if you wrote for the New York Times, the category would be "New York Times" and then right under it would be the articles you wrote in bullet points). I am at the stage where I am simply trying to make it so that the user can create a new category. I have an edit profile page where the user can already edit some details from the models. I tried to add on a form that creates a new category. When you submit the category, a success message dispays but when I look at my admin panel it doesn't create the object under categories. Here is the code: (Note: this form lets you choose the user for the category, I have to change it later to make it so that the category gets set to the user thats currently logged in) … -
if object exists in custom tag Django
This is my custom tag to show facebook link @register.simple_tag def facebook_link(): if Facebook.objects.first(): return str(Facebook.objects.first().link) else: return '' I want to show a block of html if object exists, tried to do as follows but it still displays the block {% if facebook_link %} html goes here {% endif %} any idea how to do it -
uWSGI not detecting Pipenv virtual environment
I'm using uWSGI on a Ubuntu 20.04 to host my Django API. This is my uwsgi.ini file: [uwsgi] #socket = :5000 socket = /home/ubuntu/lyrics-chords/lyrics-chords.sock chown-socket = ubuntu:www-data uid=ubuntu gid=www-data chmod-socket=660 master=true chdir = /home/ubuntu/lyrics-chords module = backend.wsgi:application virtualenv = /home/ubuntu/.local/share/virtualenvs/lyrics-chords-xEtMg5XN vacuum = true When I run uwsgi --ini uwsgi.ini outside of the virtual environment, the logs indicate that the virtual environment is not activated (or at the very least, that the modules in the virtual environment are not available). Here are the logs: *** Starting uWSGI 2.0.19.1 (64bit) on [Tue Aug 17 23:30:58 2021] *** compiled with version: 9.3.0 on 08 August 2021 17:51:00 os: Linux-5.8.0-1037-oracle #38~20.04.1-Ubuntu SMP Fri Jul 16 00:56:44 UTC 2021 nodename: lyrics-chords machine: aarch64 clock source: unix detected number of CPU cores: 1 current working directory: /etc/uwsgi/sites detected binary path: /home/ubuntu/.local/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! chdir() to /home/ubuntu/lyrics-chords your processes number limit is 22953 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) uwsgi socket 0 bound to UNIX address /home/ubuntu/lyrics-chords/lyrics-chords.sock fd 3 Python version: 3.8.10 (default, Jun 2 2021, 10:49:15) [GCC … -
Model class robovise.models.RoboProcessedFiles doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS Celery
I am using celery in my django project. 2 issues, the autodiscover task doesn't discover my task under robovise/tasks.py so I had to explicitly pass the path of the tasks file in the include argument of Celery instance. Then when I try calling the task in my django shell I get this error in Celery: [2021-08-17 16:26:36,312: ERROR/MainProcess] Task robovise.tasks.process_new_users_resp[5763be00-77d4-4705-bb9a-6e06f2b03464] raised unexpected: RuntimeError("Model class robovise.models.RoboProcessedFiles doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.") Traceback (most recent call last): File "/Users/cyzanfar/Desktop/beagle/projects/financial_services/env/lib/python3.8/site-packages/celery/app/trace.py", line 450, in trace_task R = retval = fun(*args, **kwargs) File "/Users/cyzanfar/Desktop/beagle/projects/financial_services/env/lib/python3.8/site-packages/celery/app/trace.py", line 731, in __protected_call__ return self.run(*args, **kwargs) File "/Users/cyzanfar/Desktop/beagle/projects/financial_services/financial_services/robovise/tasks.py", line 5, in process_new_users_resp from robovise.models import RegisteredUser File "/Users/cyzanfar/Desktop/beagle/projects/financial_services/financial_services/robovise/models.py", line 12, in <module> class RoboProcessedFiles(models.Model): File "/Users/cyzanfar/Desktop/beagle/projects/financial_services/env/lib/python3.8/site-packages/django/db/models/base.py", line 113, in __new__ raise RuntimeError( RuntimeError: Model class robovise.models.RoboProcessedFiles doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I've seen many post talking about this issue but have not found any solution. It's really strange as I have the same setup in another project and it works fine. project structure: ├── financial_services │ ├── __init__.py │ ├── asgi.py │ ├── celery.py │ ├── settings │ │ ├── __init__.py │ │ ├── base.py │ … -
Django and React push rejected, failed to compile on Heroku
I have been trying to deploy my Django and React application on Heroku in vain. The Django and React integration have been done by following more or less this guide: https://www.fusionbox.com/blog/detail/create-react-app-and-django/624/ The React app setting in settings.py: STATIC_URL = '/static/' REACT_APP_DIR = os.path.join(BASE_DIR, 'frontend') STATICFILES_DIRS = ( os.path.join(REACT_APP_DIR, 'build', 'static'), ) STATIC_ROOT = 'static/' My urls.py: from django.urls import re_path, path from backend.views import FrontendAppView urlpatterns = [ re_path('', FrontendAppView.as_view(), name='home'), ] My view: class FrontendAppView(View): """ Serves the compiled frontend entry point (only works if you have run `yarn run build`). """ def get(self, request): print(os.path.join(settings.REACT_APP_DIR, 'build', 'index.html')) try: with open( os.path.join(settings.REACT_APP_DIR, 'build', 'index.html')) as f: return HttpResponse(f.read()) except FileNotFoundError: logging.exception('Production build of app not found') return HttpResponse( """ This URL is only used when you have built the production version of the app. Visit http://localhost:3000/ instead, or run `yarn run build` to test the production version. """, status=501, ) The error I am having. The Error is coming probably from this FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_79d83787/frontend/build/static' If yes then my question is why it is looking for '/tmp/build_79d83787/frontend/build/static'? if no, then what is the problem then. -----> Building on the Heroku-20 stack -----> Using … -
Django - Custom Cross Join fails due to expected join fields for on clause
I've created a custom class for implementing cross join's in Django using the following code class CrossJoinToFunction(Join): def __init__(self, table_name, parent_alias, table_alias, join_type, join_field, nullable, filtered_relation=None, table_function_params: List[Any] = None): super().__init__(table_name, parent_alias, table_alias, join_type, join_field, nullable, filtered_relation) self.table_function_params = table_function_params # type: List[Any] def as_sql(self, compiler, connection): sql, params = super().as_sql(compiler, connection) table_function_placeholders = [] table_function_params = [] for param in self.table_function_params: if hasattr(param, 'as_sql'): param_sql, param_params = param.as_sql(compiler, connection) else: param_sql = '%s' param_params = [param] table_function_placeholders.append(param_sql) table_function_params += param_params sql = '{} {}({}) {}'.format( self.join_type, compiler.quote_name_unless_alias(self.table_name), ', '.join(table_function_placeholders), self.table_alias ) return sql, table_function_params + params which can be used on custom Query as following self.alias_map[alias] = CrossJoinToFunction( join.table_name, join.parent_alias, join.table_alias, join.join_type, None, None, None, resolved_params ) The desired output in SQL from this is as follows select fb.id cf.some_returned_value from foobar fb cross join custom_function(params..) as cf The issue arrises with Django always expecting there to be a join_field for all joins. This conflicts with cross joins, as they do not have an on clause. Adding join.join_field throws to the CrossJoinToFunction raises the following django error self.alias_map[alias] = CrossJoinToFunction( join.table_name, join.parent_alias, join.table_alias, join.join_type, join.join_field, join.nullable, join.filtered_relation, resolved_params ) File "/Users/timmcgee/Documents/main-site/project/models.py", line 1493, in setup_joins join.table_name, join.parent_alias, join.table_alias, join.join_type, … -
Where should I set model fields derived from a form field?
Given a model with some fields which do not map directly to a ModelForm's fields, where should I set their value? In the following, form.blast_db should be assigned to either model.protein_db or model.nucleotide_db depending on what type of blast DB it is. They are mutually exclusive but required, so they must be set before model.full_clean() is called. from django.db import models class BlastQuery(models.Model): # Protein/nucleotide blast DB. Mutually exclusive, one must be provided protein_db = models.ForeignKey(ProteinDB, null=True, blank=True) nucleotide_db = models.ForeignKey(ProteinDB, null=True, blank=True) # Just 1 field to keep it terse but in reality there are many other fields foo = models.IntegerField() def clean(self): if self.protein_db and self.nucleotide_db: raise ValidationError('Protein/nucleotide DB are mutually exclusive') if not self.protein_db and not self.nucleotide_db: raise ValidationError('Protein/nucleotide DB are required') from django import forms class BlastForm(forms.ModelForm): # Magical field that's like a ModelChoiceField but can # hold both ProteinDB and NucleotideDB instances blast_db = BlastDBField() class Meta: model = BlastQuery fields = ('foo',) -
What is wrong with my upload CSV in Django?
I have created I think pretty standard code but the file seem not to get uploaded! My set up folder is empty plus no file displays after i click submit! When pressing submit I only see "GET /?csrfmiddlewaretoken=9JefYLkycrupVof72b1oujZ2DSi0o5BlfujkW27PhVDWBcoZyzc74aZ9yckOkJUz&myfile=file+.csv HTTP/1.1" 200 2844 and similar messages My code: Main project folder: In setting.py added MEDIA_URL = '/documents/' MEDIA_ROOT = os.path.join(BASE_DIR, 'documents') urlpatterns = [ ] if DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) url.py from django.contrib import admin from django.urls import path from django.conf.urls import include from mainsite import views as main urlpatterns = [ path('admin/', admin.site.urls), path('', main.model_form_upload, name= 'index'), path('contact/', include('contact.urls')), path('explanation/', include('modelexpl.urls')), path('uploads/', main.model_form_upload, name='model_form_upload') ] Then in my project folder: urls.py from django.shortcuts import render from django.http import HttpResponse from django.urls import path from mainsite import views # Create your views here. urlpatterns = [ path('', views.index, name='index') ] models.py from django.db import models # Create your models here. class Document(models.Model): description = models.CharField(max_length=200, blank= True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) views.py: initially I added following function: from django.shortcuts import render from django.http import HttpResponse from mainsite.models import Document from mainsite.forms import DocumentForm from django.core.files.storage import FileSystemStorage # Create your views here. def index (request): placeholder = {'test' : … -
Change instance values after capture change with Django Signals
I have a model Course that have a ManyToMany relation with my CustomUser model: class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('Email Address'), unique=True) user_name = models.CharField(_('User Name'), max_length=150, unique=True) # and a lot of other fields and stuff class Course(models.Model): enrolled_users = models.ManyToManyField(CustomUser, related_name="enrolls", blank=True) previous_enrolled_users = models.ManyToManyField(CustomUser, related_name="previous_enrolls", blank=True) course_name = models.CharField(_("Course Name"), max_length=200) What I'm trying to implement is that whenever a user finishes a course (and so the user is removed from enrolled_users), my application stores this user in previous_enrolled_users, so I can know the users that were previously enrolled at that course. I've implement a m2m_changed signal listening like this: def listen_m2mchange(sender, instance, model, pk_set, action, **kwargs): if action == 'pre_remove': # I'm trying to guess what to do m2m_changed.connect(listen_m2mchange, sender=Course.enrolled_users.through) With that, whenever I remove a user from a course, Django signals the m2m_changed and I capture that signal. I know that instance is the instance of the Course class and that model is the instance of that CustomUser class I'm removing. What I could not guess is how, using the instance of Course class, I can add the CustomUser in the previous_enrolled_users. Any help will be very appreciated. -
pipenv updates all dependencies bringing breaking changes
I'm having problems with an app that uses Django. Everything is in a docker container, there is a pipfile and a pipfile.lock. So far, so good. The problem is when I want to install a new depedency. I open the docker container shell, and I install the dependency with pipenv install <package-name>. After installing the package, pipenv runs a command to update the pipfile.lock file and doing so updates all packages to their last version, bringing whit these updates a lot of breaking changes. I don't understand why is this happening, I have all packages listed in my pipfile with ~=, this is suppose to avoid updating to versions that can break your app. I'll give you an example, I have this dependency in my pipfile: dj-stripe = "~=2.4". But, in the pipfile.lock file, after pipenv runs the command lock, that depedency is updated to its last version (2.5.1). What am I doing wrong?