Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
GeoDjango heroku 'DatabaseOperations' object has no attribute 'spatial_aggregate_name'
I'm trying to deploy my app on Heroku, which works locally but is throwing this error when deployed on heroku: AttributeError : 'DatabaseOperations' object has no attribute 'spatial_aggregate_name' For context I the api call that is triggering the error is trying to return all addresses from a table that are in a certain boundary. my DATABASE settings in settings.py: INSTALLED_APPS = [ 'map.apps.MapConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.postgres', 'rest_framework', 'django.contrib.gis', 'coreapi', 'listings', 'drf_yasg', ] DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'neighborhoods', 'USER': 'django', 'PASSWORD': db_pass, 'HOST':'bonfiredb.cyuiw6tqzaag.us-west-1.rds.amazonaws.com', 'PORT':'5432' } } # Heroku: Update database configurations from $DATABASE_URL. import dj_database_url db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) # Activate Django-Heroku. django_heroku.settings(locals(), staticfiles=False) I'm using the heroku goe buildpack. I just can't seem to figure out why it is working locally but not on heroku. Here is my traceback: > Django Version: 4.0.2 Python Version: 3.9.4 Installed Applications: > ['map.apps.MapConfig', 'django.contrib.admin', > 'django.contrib.auth', 'django.contrib.contenttypes', > 'django.contrib.sessions', 'django.contrib.messages', > 'django.contrib.staticfiles', 'django.contrib.postgres', > 'rest_framework', 'django.contrib.gis', 'coreapi', 'listings', > 'drf_yasg'] Installed Middleware: > ['django.middleware.security.SecurityMiddleware', > 'whitenoise.middleware.WhiteNoiseMiddleware', > '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'] > > > > Traceback (most recent call last): File > "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py", > line 47, in inner … -
Django Celery apply_async doesn't exexute all queries
I have used celery apply_async (also tried delay) with django. The task executes only 3 out of 10 queries where I am performing an update operation on mongo db database. -
How to debug Django tests in vscode
I've been searching a lot for this, no answer. Using StackOverFlow a long time, but this is my first question. How to debug tests with Django, using TestCase and no other frameworks ? I got configurations for debugging django test , but it doesn't even hit the breakpoints.configs Started to question is it even possible ? p.s. Searching for answer for two days. If there is an answer I haven't found, sorry for spam. -
Django filter OrderingFilter default choice
I have created an ordering filter with django filters and I have been wondering how I can set the default choice and remove the empty choice. class MyFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_expr='icontains') o = django_filters.OrderingFilter( choices=( ("created", _("Created, old to new")), ("-created", _("Created, new to old")) ), fields = ( "created", "created" ) ) When I render the filter form the empty choice "----" is being shown as default. I would like to set one the of filtering choices as default and remove the empty choice. -
Pafy Youtube Error 403 when converting video
I'm getting this error when converting a video using pafy GdataError at / Youtube Error 403: The request cannot be completed because you have exceeded your <a href="/youtube/v3/getting-started#quota">quota</a>. This is my code (views.py): def download_video(request): global context form = DownloadForm(request.POST or None) if form.is_valid(): video_url = form.cleaned_data.get("url") if 'm.' in video_url: video_url = video_url.replace(u'm.', u'') elif 'youtu.be' in video_url: video_id = video_url.split('/')[-1] video_url = 'https://www.youtube.com/watch?v=' + video_id if len(video_url.split("=")[-1]) != 11: return HttpResponse('Enter correct url.') video = pafy.new(video_url) stream = video.streams video_audio_streams = [] for s in stream: video_audio_streams.append({ 'resolution': s.resolution, 'extension': s.extension, 'file_size': filesizeformat(s.get_filesize()), 'video_url': s.url + "&title=" + video.title }) stream_video = video.videostreams video_streams = [] for s in stream_video: video_streams.append({ 'resolution': s.resolution, 'extension': s.extension, 'file_size': filesizeformat(s.get_filesize()), 'video_url': s.url + "&title=" + video.title }) stream_audio = video.audiostreams audio_streams = [] for s in stream_audio: audio_streams.append({ 'resolution': s.resolution, 'extension': s.extension, 'file_size': filesizeformat(s.get_filesize()), 'video_url': s.url + "&title=" + video.title }) context = { 'form': form, 'title': video.title, 'streams': video_audio_streams, 'description': video.description, 'likes': video.likes, 'thumb': video.bigthumbhd, 'duration': video.duration, 'views': video.viewcount, 'stream_video': video_streams, 'stream_audio': audio_streams } return render(request, 'home.html', context) return render(request, 'home.html', { 'form': form }) Maybe the error is triggered from another file and I have to change something in … -
Arbitrary Relationship to Another Django Model's Fields?
I'm trying to build a notification system that can trigger based on a user-defined threshold in any field in another model. Ideally this would be something like a ForeignKey relationship, except it saves the external model's field name rather than its instance. My idea is to make a model for storing the notification preference, but I don't know how to save the user's choice of the other field's model: class Report(models.model): a = models.FloatField() b = models.FloatField() c = models.FloatField() class Notification(models.model): report = models.ForeignKey(Report) threshold = models.FloatField() threshold_field = ??? # this has to be a relationship to any field available in Report model I know you can do ForeignKey relationships to pre-defined field with the to_field argument, but this option has to be any field in Report. My idea is to just save threshold_field as a CharField and then use Python's getattr function when retrieving the Report data, but this isn't clean and could break if the field names in Report were to change. There might be an option to override the save method, but I haven't found a way for that to work. -
URLs not matching when admin page set to root url in django app
I building a Django app with drf, the API urls not match correctly when I set admin site at root URL urlpatterns = [ path('', admin.site.urls), path('api/auth/', include("account.urls")), path('api/main/', include("main.urls")), ] when I hit the main API URLs it returns the admin login page, can't fix this yet please help me out. -
update field with number of row in another table django
I'm building a web crawler contain links blogs etc ... , I have field called number_of_crawled_Links and I want to make the value of that filed is the number of rows in another model Where Links Stored any idea how to do that -
Django: Display inline through direct relation
I have models: class CustomUser(AbstractUser): employee_number = models.CharField(max_length=255, blank=True, db_index=True) position = models.ForeignKey( 'orgunits.Position', on_delete=models.CASCADE, related_name='employees' ) class Position(models.Model): orgunit = models.ForeignKey( OrgUnit, on_delete=models.CASCADE, verbose_name=_('orgunit'), related_name='positions', ) name = models.CharField(_('name'), max_length=255) class OrgUnit(models.Model): name = models.CharField(_('name'), max_length=255) type = models.CharField(_('type'), max_length=55) address = models.TextField(_('address'), null=True, blank=True) I would like to display all CustomUser instances assigned to OrgUnit: class OrgUnitEmployeesInline(admin.TabularInline): model = CustomUser class OrgUnitAdmin(admin.ModelAdmin): model = OrgUnit inlines = OrgUnitEmployeesInline, But of course there is an error: <class 'orgunits.admin.OrgUnitEmployeesInline'>: (admin.E202) 'authentication.CustomUser' has no ForeignKey to 'orgunits.OrgUnit'. because Position has ForeignKey to 'orgunits.OrgUnit'. Also I tried this: class OrgUnitEmployeesInline(admin.TabularInline): model = CustomUser fk_name = 'position' but error: <class 'orgunits.admin.OrgUnitEmployeesInline'>: (admin.E202) fk_name 'position' is not a ForeignKey to 'orgunits.OrgUnit'. How can I display users in orgunits inline? -
How to Use --noreload in Django app with gunicorn on remoter server ( ubuntu VM )
What is the equivalent of Python3 manage.py runserver --noreload on remote Virtual machine with gunicorn,django and nginx. The problem is that i'm calling a function to download data using Apscheduler and if i run --norelaod command on local the files are downloaded perfectly, but on cloud i'm using gunicorn and the function is called twice or thrice hence a lot of extra files, so how do i use something like --noreload on gunicorn? -
Whenever i try this, i get a None
username = request.POST['username'] pwd = request.POST['pwd'] User = authenticate(username='jjmster301', password='123') if User is not None: login(request, User) return redirect('/') else: if users.objects.filter(username = username, password = pwd).exists(): messages.info(request, f"Responses >>> {User}") #messages.info(request, f"Response >>> {users.objects.all()}") return redirect('login') -
Django - automatically create User on Athlete create (tied together with a OneToOneField)
I have a model called Athlete that has a OneToOne relation to the User model which is an AbstractUser, I'm trying to create a user whenever I create an Athlete and automatically tie them together but I'm getting an error: Manager isn't available; 'auth.User' has been swapped for 'users.User' Here's my User Model: class User(AbstractUser): is_athlete = models.BooleanField(default=False) is_coach = models.BooleanField(default=False) is_owner = models.BooleanField(default=False) def save(self, *args, **kwargs): self.is_athlete = Athlete.objects.filter(user=self).exists() self.is_coach = Coach.objects.filter(user=self).exists() self.is_owner = Organization.objects.filter(owner=self).exists() super().save(*args, **kwargs) and the Athlete Models (so far): class Athlete(models.Model): user = models.OneToOneField(User, blank=True, null=True, on_delete=models.SET_NULL) coach = models.ForeignKey(Coach, blank=True, null=True, on_delete=models.SET_NULL, related_name='coach') def save(self, *args, **kwargs): try: User.objects.get(email=kwargs.get('email')) print('User with this mail already exists') except User.DoesNotExist: print('User with this mail does not exist') new_user = AuthUser.objects.create_user(email=email) self.user = new_user new_user.save() super().save(*args, **kwargs) -
Python paho MQTT stop execution if not connect
In my python project i use pahoMQTT for connect and pub/subscribe from an MQTT broket. I initialize my procedure like this: def run_sync_client(): #MQTT # Instantiate and check connection about MQTT instance client1 = mqtt.Client(getMacAddr()) client1.on_connect = on_connect # attach function to callback client1.message_callback_add(mqtt_sub_pol, on_message_poll) client1.on_message = on_message # attach function to callback client1.on_publish = on_publish # attach function to callback client1.on_subscribe =on_subscribe # attach function to callback client1.tls_set(mqtt_ca_crt, mqtt_cli_crt, mqtt_cli_key) client1.tls_insecure_set(True) time.sleep(1) try: client1.connected_flag = False client1.connect(mqtt_server, mqtt_port) # connect to broker except Exception: logging.error("Cannot connect MQTT Client1") # END MQTT ... # Rest of code my callback on_connect method is: def on_connect(client1, userdata, flags, rc): client1.connected_flag = True So my problem is when something whent wong in client1.connect() procedure because Exception is raised and the program execution stops, as the system remain in waiting for the connection. My question is, how can i stop the connection trying after a while anc continue with the rest of the code execution? So many thanks in advance -
Django model_to_dict but for a Queryset
I want to be able to essentially do what the dumpdata command does, but instead of showing up in a Django fixture format like with the "models" and "pk" fields, it shows up purely like the data in an instance put through the model_to_dict function. Is there a neat way to use this efficiently on a Queryset? Or does it have to be like this? import json from django.forms.models import model_to_dict from app.models import MyModel data = [model_to_dict(instance) for instance in MyModel.objects.all] json.dumps(data) -
django values_list() and image reverse foreign key
I have a problem with the images, they are not displayed in the template, can someone help me with some solution class Product(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) myshop = models.ForeignKey(MyShop, on_delete=models.CASCADE, related_name="shop_product") title = models.CharField(max_length=255) description = models.TextField(blank=True) class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="product_image") image = models.ImageField(upload_to='products/images', validators=[validate_image_file_extension, validate_file_size, FileExtensionValidator(['JPEG', 'JPG', 'PNG'])]) {% for product in products %} {% for image in product.product_image.all %} {% if image.is_feature %} <img src="{{ image.image.url }}" alt="" width="80" height="80"> {% endif %} {% endfor %} {% endfor %} products = Product.prod_obj.select_related( 'myshop' ).filter(id__in=product_ids).values_list('myshop', 'title', 'description', 'product_image', named=True) -
Create a Django detail def
well these are the codes: views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from . import models def detail(request, question_id): question = get_object_or_404(models.Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) detail.html <h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br /> {% endfor %} <input type="submit" value="Vote" /> </form> urls.py from django.urls import path from . import views from django.urls import path, re_path path(r'^(?P<pk>[0-9]+)/$', views.detail, name='detail'), but the result is an TypeError : detail() got an unexpected keyword argument 'pk' and if you add 'pk' argument to detail() like this : def detail(request, pk, question_id): question = get_object_or_404(models.Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) the resualt is another error : detail() needs an important argument 'question_id' where is the problem from? -
How to get the data from custom serializer.CharField() after update?
I've got 2 models. CollabDocument groups CollabVersions. Together they are like a document that tracks its changes. Binary field only because the content is encrypted. class CollabDocument(models.Model): name = models.CharField(max_length=4096, null=False, blank=False) class CollabVersion(EncryptedModelMixin, models.Model): document = models.ForeignKey(CollabDocument, related_name="versions", on_delete=models.CASCADE) content = models.BinaryField(blank=True) I've got this base serializer: class CollabDocumentSerializer(serializers.ModelSerializer): name = serializers.CharField(required=True) class Meta: model = CollabDocument fields = "__all__" The content field in the following serializer ist important. I call the patch -> update method of the collab document and then a new version is created. That way there is a history of all changes made. This serializer does not update the document itself btw. class CollabDocumentUpdateSerializer(CollabDocumentSerializer): content = serializers.CharField(write_only=True) # <-- without write_only=True I get a 500 error def update(self, instance, validated_data): version = CollabVersion(content=validated_data['content'], document=instance) version.encrypt(request=self.context['request']) version.save() return instance This my problem: I can't get the content in the response, if I remove write_only=True the request fails. What I want: { id: 1, content: '<h1>awesome document</h1>', name: 'My Document' } What I get instead: { id: 1, name: 'My Document' } In my retrieve serializer I've done the following: class CollabDocumentRetrieveSerializer(CollabDocumentSerializer): content = serializers.SerializerMethodField() quill = serializers.SerializerMethodField() def get_latest_version(self, obj): if not hasattr(self, 'latest_version'): self.latest_version = … -
Requesting for POST method but only GET is working
The Form in register.html request for POST method but GET method is working. Submit is calling register method in views.py using GET method, but this shouldn't be happening. Error : Request Method: POST Request URL: http://127.0.0.1:8000/Profile/register/register/ from django.http import HttpResponse from django.shortcuts import redirect, render from django.contrib.auth.models import User from django.contrib import messages def register(request): if request.method == 'POST': return redirect('/') else: return render(request, 'register.html') register.html <form action="register" method="post"> {% csrf_token %} <input type="Submit"> </form> urls.py of Project from re import template from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls')), path('Profile/', include('Profile.urls')), path('accounts/', include('django.contrib.auth.urls')), path('login/', auth_views.LoginView.as_view(template_name="login.html"), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('reset_password/', auth_views.PasswordResetView.as_view(), name = 'reset_password'), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete') ] urls.py of Profile app from django.urls import path from Profile import views urlpatterns = [ path('profile/', views.profile, name='profile'), path('register/', views.register, name='register'), ] -
How to get schema name of logged in Tenant in Django multi-tenant app?
I am using sqlalchemy to get the query result and then passing the result to pandas data frame. But it's enter image description heregenerating an error like "(psycopg2.errors.UndefinedTable) relation "identification_individual" does not exist". I figured out that schema name is required with the table to execute this statement successfully. "schemaName.identification_individual" works fine my question is how can I get the schema name of the logged-in tenant (i want this to be dynamic so that schema should be changed according to every tenant ) and how can the below query be updated. code is: engine = sqlalchemy.create_engine('postgresql://postgres:password@localhost:5432/dbname') df= pd.read_sql_query("""SELECT DISTINCT (customer_id),customer_id,customer_type,product_type,delivery_channel,diligence_type, customer_name,over_all_discount_status,risk_score,risk_category,pep_status,identification_individual.city FROM identification_individual LEFT JOIN discounting_individuldiscount ON identification_individual.customer_id = discounting_individuldiscount.individual_id WHERE over_all_discount_status='Pending' or over_all_discount_status='Rejected' or over_all_discount_status='Proceed';""",engine) -
How to merge two dependant models in django and get count of each type
I'm new to django, how to relate two model classes and extract total count of it class FoodBatch(models.Model): batch_code = models.CharField(max_length=200, blank=False, null=False) expiry = models.DateField() price = models.FloatField() class FoodItem(models.Model): seller_code = models.CharField(max_length=200, blank=False, null=False) brand = models.CharField(max_length=200, blank=False, null=False) quantity = models.IntegerField() batch = models.ManytoMany(FoodBatch) FoodBatch has to be unique for each FoodItem. FoodItem can map to multiple FoodBatch. Also, need to total count of quantity from all the FoodBatch for each FoodItem. Thanks in advance. -
Calling data from Django Admin via Frontend live search
I was hoping someone here could point me in the right direction; I don't know how best to phrase the question so I'm not even sure if this has already been asked, although a search does not reveal anything. I commissioned a new app in Django which has been registered in Admin view - what I am trying to do is add data from Django Admin within the app which has several fields, one field being a 'keyword' field which is comma separated. The current app view from Admin is like this: Django Admin View - App The fields within the entry: Django Admin View - Add Entry From front-end, I want to add an AJAX search that will check through the keywords in each entry within the app and return the corresponding fields dynamically below the search bar. The front end search will look something like this: Frontend Search Below the search bar, for each matching keyword, I want the metric name, metric URL and metric embed code to be presented. Hopefully the attached screenshots will help demonstrate things visually as I may not be describing this very accurately. Any help is highly appreciated :) -
Django 'http://localhost:8000' has been blocked by CORS policy
I have an error on the server http://95.216.155.54:8000/ (local host is OK) from origin 'http://localhost:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I tried the following (followed this page How can I enable CORS on Django REST Framework) pip install django-cors-headers # Added at the top of MIDDLEWARE MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', # Added after allowed hosts CORS_ORIGIN_ALLOW_ALL=True CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True After the changes below I have You can see the error in browser developer's mode VM87:5553 crbug/1173575, non-JS module files deprecated. How can I fix the error? -
Django: DRF relationship key issues
I am facing an issue while trying to create a model that another model has a foreign key to and each time an instance is created in the model the model that has a relationship to the model needs to update as well but I don't think this is a good way to create relationships class User(AbstractBaseUser, PermissionsMixin): .... #three fields pointing to one model owner = models.ManyToManyField(School, verbose_name=_( "Ownes"), related_name='owner', blank=True) workes_at = models.ForeignKey(School, verbose_name=_( "Workes at"), related_name='Workes_at', on_delete=models.PROTECT, blank=True, null=True) learns_at = models.ForeignKey(School, verbose_name=_( "Learns at"), related_name='learns_at', on_delete=models.PROTECT, blank=True, null=True) this way I have the issue I talked about above as when I want to create a school instance the owner would need to be set on the user model I also put the fields in the school model but that would mean when I want to filter users based on the schools they go to or own or work at, and also creating students or workers would be a hard task, I want to know what the recommended way to do this kind of stuff if maintaining 3 foreign key fields to the same model is not a good idea please recommend me another way, I have … -
Django Invalid credentials: User object check_password returns True, but authenticate function returns False
I've a user account in Django's default User model, where the account's check_password() is True, but the authenticate function doesn't return user the object with the same password, and it is happening only for this user. >>> from django.contrib.auth import authenticate >>> from django.contrib.auth.models import User >>> user = User.objects.get(username='user_1') >>> user.check_password('1234') // returns True >>> authenticate(username='user_1', password='1234') // returns False and most importantly it happens only to this user object [username: user_1] and not to any other users. I've tried resetting the password using set_password() >>> user.set_password('1234') >>> user.save() Even after resetting the password, the authenticate still doesn't returns the user object and it resets for other users properlly. The question is, why it is happening for a specific user and not for any other users. Django version: 2.2 -
Why Django form.save() returns object(None)?
from django.shortcuts import render from django.forms import forms from .models import Chart, ChartData from .forms import ChartForm, ChartDataForm import datetime def home(request): chart_form = ChartForm(request.POST) chart_data_form = ChartDataForm(request.POST) context = { 'chart_form': chart_form, 'chart_data_form': chart_data_form, } if chart_form.is_valid(): chart_obj = chart_form.save() chart = Chart.objects.get(pk=23) print(chart_obj) print(chart) return render(request, 'charts/home.html', context) chart_form.save() returns "Chart object (None) I have to eventually pass the chart_obj to another model for the foreign key, but right now it brakes there with error - save() prohibited to prevent data loss due to unsaved related object. In the admin site I see that the object is created.