Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Serving static files after deployment with django 2.2
I deployed my site at the level of my host, but the imgaes are not displayed. I did python manage.py collectstatic and it copied the files to my STATIC_ROOT myprojet/settings.py STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static') ] STATIC_URL = 'static/' STATIC_ROOT='/home/www/mySite.com/static/' index.html {% extends 'layout/base.html' %} {% load staticfiles %} {% block content %} <img src="{% static 'images/icone.png' %}" style="width:350px;height:100"> {% endblock content %} I used {% load staticfiles %} as i am using django 2.2 but the images are not showing I don't know where the problem is. -
Integrity eror not null constraint failed
Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: Cart.cart_id #mymodel: class Cart(models.Model): cart_id=models.CharField(max_length=250,blank=True) def _cart_id(request): cart=request.session.session_key if not cart: cart=request.session.create() def add_cart(request,product_id): product=Product.objects.get(id=product_id) try: cart=Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart=Cart.objects.create(cart_id=_cart_id(request)) cart.save() -
how to authenticate user using the Custom user table with the phone as username in Django
I'm using a Custom user in my django application and it works fine when i create the user , but the problem happens when i try to authenticate the user as am using phone as username it simply not working. here is my code : class CustomUserManager(BaseUserManager): def create_user(self, phone, password=None): if not phone: raise ValueError('Users must have a phone number') user = self.model( phone=phone, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, phone, password): user = self.create_user( phone, password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.user_type = 'admin' user.save(using=self._db) return user class CustomUser(AbstractUser): """ Extends Django AbstractUSer as a custom user model """ user_type_choices = ( ('client', 'Client'), ('supplier', 'Supplier'), ('admin', 'Admin'), ) username = None phone = models.CharField(max_length=200, unique=True, verbose_name=_( "Phone"), help_text=_("Phone number of the user")) user_type = models.CharField(max_length=200, choices=user_type_choices, verbose_name=_( "Type"), help_text=_("Type of the user"), default='client') company_name = models.CharField(max_length=200, verbose_name=_( "Company Name"), help_text=_("Company name of the supplier"), blank=True, null=True) email = models.EmailField(max_length=200, verbose_name=_( "Email"), help_text=_("Email of the supplier"), blank=True, null=True) establishment_date = models.DateField(verbose_name=_("Establishment Date"), help_text=_( "Establishment date of the supplier's company"), blank=True, null=True) # number_of_projects = models.IntegerField(verbose_name=_("Number of projects"), help_text=_( # "Number of projects the supplier has"), blank=True, null=True) # tax_id = models.FileField(upload_to='media/tax_id', verbose_name=_( … -
How to fetch related entries in Django through reverse foreign key
Django newbie here! I am coming from .NET background I am frustrated as to how to do the following simple thing: My simplified models are as follows class Circle(BaseClass): name = models.CharField("Name", max_length=2048, blank=False, null=False) active = models.BooleanField(default=False) ... class CircleParticipant(BaseClass): circle = models.ForeignKey(Circle, on_delete=models.CASCADE, null=True, blank=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) status = models.CharField("Status", max_length=256, blank=False, null=False) ... class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(verbose_name="Email", unique=True, max_length=255, validators=[email_validator]) first_name = models.CharField(verbose_name="First name", max_length=30, default="first") last_name = models.CharField(verbose_name="Last name", max_length=30, default="last") ... My goal is to get a single circle with participants that include the users as well. With the extra requirement to do all that in a single DB trip. in SQL terms I want to accomplish this: SELECT circle.name, circle.active, circle_participant.status, user.email. user.first_name. user.last_name FROM circle JOIN circle_participant on circle.id = circle_participant.id JOIN user on user.id = circle_participant.id WHERE circle.id = 43 I've tried the following: Circle.objects.filter(id=43) \ .prefetch_related(Prefetch('circleparticipant_set', queryset=CircleParticipant.objects.prefetch_related('user'))) This is supposed to be working but when I check the query property on that statement it returns SELECT "circle"."id", "circle"."created", "circle"."updated", "circle"."name", "circle"."active", FROM "circle" WHERE "circle"."id" = 43 (additional fields omitted for brevity.) Am I missing something or is the query property incorrect? More importantly how … -
How to make the error messages not appear below the fields, but on top of the table Django
I'm writing a Django site, I made a registration form, but I don't like the fact that error messages appear under the corresponding fields, thereby stretching the table I want these messages to be displayed somewhere above the form, is this possible? -
Django listings: django displays FK's object instead of value
I am using django_listing in order to create a table: class SpotTableView(ToolbarListingView): template_name = f'{templates_dir}tables/spot.html' update_success_redirect_url = LISTING_REDIRECT_NO_EDIT save_to_database = True def get_listing_instance_update_listing(self): return Listing(Spot, editable=True, editing=False, edit_on_demand_options={'has_paginator': False}, edit_on_demand=True, gender__input_type='radio', save_to_database=True, selection_position='left', selection_multiple=True, selectable=True, selection_initial=[3, 4], per_page=5, has_toolbar=True, toolbar_placement='top', toolbar=Toolbar( InsertToolbarItem(), EditToolbarItem(), DeleteToolbarItem(), SortSelectToolbarItem(), PerPageSelectToolbarItem(choices='5,10,25,50,100,-1:All'), ) ) When the data table loads the FK's object name is displayed instead of the integer representing the FK's model's index. table I am declaring the FK inside the model as following: mid = models.ForeignKey('Metadata', default=1, verbose_name="mid", on_delete=models.SET_DEFAULT, db_column="mid") How can i make it display the value of the FK, instead of the model? -
How to check current URL/endpoint in django if statement
I have a button on a base template that just takes you back (history.back()) on every page except for one specific page. I assume there's a simple one line like {% if URL == specificURL %} but for the life of me I can't figure out how to do it. Im trying to do it within the html, but I'll happily take any other suggestions if something else would work Its a light site and I could take the button off the base template and just put separate logic on every html page but that's obviously bad for scale should also probably preface that I'm definitely beginner for Django -
Open jquery modal with django
how can I open the modal with Django? my jquery modal is in signup.html and my modal open button is in base.html. -
How to call a python function with annotations?
I have a function in another annotated method and there is a problem. I call it through django and get all sorts of errors. like this. views.py: ` def callbot(): bot_activate = bot.Command.callBot() return render(request, bot_activate) def output(request, temlate_name='custom_change_form.html',): callbot() print('work') return render(request, temlate_name) **bot.py** @logerrors def do_echo(update: Update, context: CallbackContext,): print('HELLOOOOO') chat_id = update.message.chat.id text = update.message.text p, _ = Profile.objects.get_or_create( external_id=chat_id, defaults={ 'name': update.message.from_user.username, } ) MessagePanel( profile=p, text=text, ).save() reply_text = f"Your ID: {chat_id} \n{text} \n " update.message.reply_text(text=reply_text,) @logerrors def send_text(update: Update, context: CallbackContext,): chat_id = update.message.chat_id text = update.message.text commandname = CommandsForButtons.objects.filter(is_active=True) print('Its worked') for mess in commandname: mess_send = mess.command_text update.message.reply_text(text=f'It\'s test message: {mess_send}') do_echo(update, context) @logerrors def send_hand_message(update: Update, context: CallbackContext,): chat_id = update.message.chat_id text = update.message.text hand_message = HandMadeMessage.objects.all() update.message.reply_text(text=f'It\'s test message: {hand_message}') class Command(BaseCommand): help = 'Telegram-Bot' def handle(self, *args, **options): hand_message = HandMadeMessage.objects.all() request = Request( connect_timeout=0.5, read_timeout=1.0, ) bot = Bot( request=request, token=settings.TOKEN, base_url=getattr(settings, 'PROXY_URL', None), ) to_bot_panel, _ = BotsPanel.objects.get_or_create( bot_id = bot.get_me().id, bot_name = bot.get_me().first_name, bot_nickname= bot.get_me().username, bot_token= bot.token ) print(bot.get_me()) updater = Updater( bot=bot, use_context=True, ) #Commands def callBot(): return send_text(Update, CallbackContext) updater.dispatcher.add_handler(CommandHandler('get', send_text,)) updater.dispatcher.add_handler(MessageHandler(Filters.text, do_echo)) updater.start_polling() updater.idle() ` Maybe u guys know what i should to … -
How to make logical AND, NOT work properly in Postgres full text search with Django
I have a project with Django, DRF and PostgreSQL. And I need to make a search for some data in this project. In this search I need logical operators (AND, OR, NOT), searching by prefix (like manch*) and case insensitivity. So I decided to use PostgreSQL full text search like this class VariableSearch(generics.ListAPIView): serializer_class = VariableSerializer def get_queryset(self): q = self.request.query_params.get('query') if q: vector = SearchVector('name', 'label') query = SearchQuery(q, search_type='raw') queryset = Variable.objects.annotate(search=vector).filter(search=query) else: queryset = Variable.objects.none() return queryset So with this type of search I can do queries like this http://127.0.0.1:8000/search_var/?query=полит:* | инфо:* And operator OR and searching by prefix working good. But when I'm trying to use AND (&) on NOT (!) it's giving me results without this logical AND or just syntax error in tsquery: "word !not" for queries like this http://127.0.0.1:8000/search_var/?query=word !not So how to make AND and NOT work properly? -
Appenchild is throwing an error when trying to append a modal to a div
I am currently exploring and trying to create a Django application. The problem I am facing currently is, while trying to append a modal to a div element in the HTML file, the JavaScript threw an error saying : Uncaught (in promise) TypeError: modalContainer.appendChild is not a function at HTMLButtonElement.replyModal ((index):217:28) Here is the code throwing the problem: console.log("REPLY MODAL"); var modal = document.createElement('div'); modal.className = "modal fade"; modal.id = "reply-modal"; modal.tabIndex = "-1"; modal.setAttribute("aria-labelledby", "Reply to feedback"); modal.setAttribute("aria-hidden", "true"); var modalDialog = document.createElement('div'); modalDialog.className = "modal-dialog"; var modalContent = document.createElement('div'); modalContent.className = "modal-content"; var modalHeader = document.createElement('div'); modalHeader.className = "modal-header"; var modalTitle = document.createElement('h5'); modalTitle.className = "modal-title"; modalTitle.innerHTML = "Reply to feedback"; var modalCloseButton = document.createElement('button'); modalCloseButton.className = "btn-close"; var modalBody = document.createElement('div'); modalBody.className = "modal-body"; var modalForm = document.createElement('form'); modalForm.method = "POST"; modalForm.action = "/suggestionbox/reply/" + feedback.pk + "/"; modalForm.id = "reply-form"; var modalCsrfToken = document.createElement('input'); modalCsrfToken.type = "hidden"; modalCsrfToken.name = "csrfmiddlewaretoken"; var modalFormGroup = document.createElement('div'); modalFormGroup.className = "form-group"; var modalLabel = document.createElement('label'); modalLabel.for = "reply"; modalLabel.innerHTML = "Reply"; var modalTextArea = document.createElement('textarea'); modalTextArea.className = "form-control"; modalTextArea.id = "reply"; var modalSubmitButton = document.createElement('button'); modalSubmitButton.type = "submit"; modalSubmitButton.className = "btn btn-primary"; modalSubmitButton.innerHTML = "Submit"; modalFormGroup.appendChild(modalLabel); modalFormGroup.appendChild(modalTextArea); modalForm.appendChild(modalCsrfToken); modalForm.appendChild(modalFormGroup); modalForm.appendChild(modalSubmitButton); … -
Django Apache production page loading very slow
hi I have a simple 2 page web app. The page where it display database data to html is running verry slow, can't even load properly and the database is very little (3 objects). I dont what the problem I been trying to fix that for the last 3 day. models.py class photos(models.Model): # title field title = models.CharField(max_length=100) #image field image = CloudinaryField('image') views.py def index(request): photo = photos.objects.all() context = {'photo': photo} return render(request, 'main/index.html', context) index.html {% for pic in photo %} <h2>{{pic.title}}</h2> {% endfor %} I feel like the problem come from the apache configuration server. Here my config. <VirtualHost *:80> ServerName MY-SERVER-IP ErrorLog ${APACHE_LOG_DIR}/mysite-error.log CustomLog ${APACHE_LOG_DIR}/mysite-access.log combined WSGIDaemonProcess mysite processes=2 threads=25 python-home=/var/www/mysite/venv/ python-path=/var/www/mysite WSGIProcessGroup mysite WSGIScriptAlias / /var/www/mysite/mysite/wsgi.py Alias /robots.txt /var/www/mysite/static/robots.txt Alias /favicon.ico /var/www/mysite/static/favicon.ico Alias /static/ /var/www/mysite/static/ Alias /media/ /var/www/mysite/media/ <Directory /var/www/mysite/mysite> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /var/www/mysite/static> Require all granted </Directory> <Directory /var/www/mysite/media> Require all granted </Directory> </VirtualHost> I didnt run any database command on my apache server, I dont know if I should run a command regarding the database. -
Celery keeps trying to connect to localhost instead of Amazon SQS
So I'm trying to setup Celery in my Django project, and using Amazon SQS as my broker. However, Celery keeps trying to find SQS on localhost for some reason. This is my settings.py: CELERY_BROKER_TRANSPORT = "sqs" CELERY_BROKER_USER = env.str("DJANGO_AWS_ACCESS_KEY_ID") CELERY_BROKER_PASSWORD = env.str("DJANGO_AWS_SECRET_ACCESS_KEY") CELERY_BROKER_TRANSPORT_OPTIONS = { "region": env.str("DJANGO_AWS_SQS_REGION_NAME", default="us-east-2"), "polling_interval": 10, } CELERY_DEFAULT_QUEUE = "default" CELERY_ACCEPT_CONTENT = ["application/json"] CELERY_TASK_SERIALIZER = "json" CELERY_RESULT_SERIALIZER = "json" CELERY_CONTENT_ENCODING = "utf-8" CELERY_ENABLE_REMOTE_CONTROL = False CELERY_SEND_EVENTS = False CELERY_SQS_QUEUE_NAME = "default" This is my celery.py : import os from celery import Celery # set the default django settings module os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.production') app = Celery('consumers') # type: Celery app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() When I start the worker using celery -A src.consumers worker --loglevel=debug, the worker tries to start with the following output and then immediately stops: -------------- celery@aditya-PC v5.2.7 (dawn-chorus) --- ***** ----- -- ******* ---- Linux-5.15.0-52-generic-x86_64-with-glibc2.35 2022-10-27 13:56:01 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: consumers:0x7fd77051de40 - ** ---------- .> transport: sqs://AHJJHHFYTA3GHVJHB8:**@localhost:6379// - ** ---------- .> results: disabled:// - *** --- * --- .> concurrency: 12 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) … -
How can I upload my projects to my website? [closed]
So, I have a portfolio website and 'Projects' section. In the 'Projects' section there is information about my projects: their picture, name and "See More" button. I want to I want it to open its own project every time the button is clicked. I use Django framework for backend. -
Sort table in Django admin with a boolean field
I want to sort data by Boolean in Django admin, but it doesn't work with admin_order_field, below is my code : def get_is_active(self, obj): return obj.is_active get_is_active.allow_tags = True get_is_active.admin_order_field = 'is_active' get_is_active.short_description = _('Is Active') This is the image below : -
How can I subselect a value in django querySelector?
I will exlplain my question with an example: lets say I am able to extract an object with this form with my filter: { a, b, c : {x, y, z} } But what I am trying to do, is to get the object as following: { a, b, c : {x} } { a, b, c : {y} } { a, b, c : {z} } if my question isn't clear enough don't hesitate to ask for more details in the comments -
django queryset: How I can override values in django queryset before sending the response?
I am on something where I need to override the values according to the URL parameters. Model: Person Name Alias Alex {"Alex", "Jacob" Alias column is the Array type I get alias from the URL parameter like: example.com/?alias=Alex here alias = Alex and my query is queryset = Person.objects.filter(name=alias) and finally, I have to send the response to the frontend like <QuerySet [<Person: "Alex">] basically here I have to remove Jacob from the Alias I have tried for qs in list(queryset): if "Alex" in qs["alias"]: qs["alias"] = ["Alex"] it is working but I need to return response in the form of queryset object -
How to join different models with primary key in Django?
I am very new on Django. I wanna make patient storage system but i'm stuck. These things must be in project. 1-) In my project i want to add hundreds of patients and also some new patients can add their own infos via register. 2-) Every patients will answer more then 300 questions, so i wanna split the model for good user experience. Here is the my problem. I split the main models, and then i add some basic information from hastaekle.html and then when i looked the admin panel. I see this selection page on the image at below. How can it be automatically. Here is my models.py from django.db import models from django.shortcuts import render from django.urls import reverse # Create your models here. class HastaProfil(models.Model): #id = models.IntegerField(primary_key=True) hasta_ad = models.CharField(max_length=155) hasta_soyad = models.CharField(max_length=155) hasta_dogum_yeri = models.CharField(max_length=155) def __str__(self): return self.hasta_ad + ' ' + self.hasta_soyad def get_absolute_url(self): return reverse('hasta-aliskanlik') class HastaAliskanlik(models.Model): #id = models.IntegerField(primary_key=True) sigara = models.CharField(max_length=155) alkol = models.CharField(max_length=155) uyusturucu = models.CharField(max_length=155) def __str__(self): return self.sigara def get_absolute_url(self): return reverse('hasta-listele') class Hasta(models.Model): #id = models.IntegerField(primary_key=True) hastaprofil = models.ForeignKey(HastaProfil, on_delete=models.CASCADE, null=True) hastaaliskanlik = models.ForeignKey(HastaAliskanlik, on_delete=models.CASCADE, null=True) forms.py from .models import HastaAliskanlik, HastaProfil, Hasta from django import … -
Is there a simpler way check if the filter i am filtering by is NULL in django?
I am wondering whether there is a simpler way to ignore NULL values when filtering in django. I don't mean NULL values in the database but rather potential NULL values I am filtering by. This is my code so far: if data['grade'] is not None: posts = posts.filter(grade=data['grade']) if data['subject'] != '': posts = posts.filter(subject=data['subject']) Is there a way to avoid all the if clauses and write the filter in a single statement? Thanks in advance! -
Can I add images from an AWS S3 bucket to Wagtail/Django database from , without downloading and opening each file?
I have a pre-existing AWS S3 bucket that I want to use for Wagtail Images. I want to populate the gallery with the images held in the S3 bucket, so that they're accessible to image fields on page models and also to RichText embedded imagery. The issue is that there are 1500 images, so I think I want to avoid having the script actually download/open each of these files if I can help it; I'm worried it will make the script run a long time and might kill down a server with a small amount of memory. Is there a way to register the files in the database without actually opening each image? Where I'm up to Where I think I'm going with this is to manually pull down the file references using boto and then somehow plug those references into the database? s3_client = boto3.client('s3', aws_access_key_id=settings.AWS_S3_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_S3_SECRET_ACCESS_KEY) items = s3_client.list_objects_v2(Bucket='xxx') for item in items: image = CMSImage(...) But what next, I'm not sure of. I see solutions which involve downloading/opening the files, but is there a way to do this without that? -
What is the solution for DRF Social Oauth2 giving 401 (Unauthorized) Error from browser, but working fine on POSTMAN
I have an application which passes the client ID and secret along with username and password to http://127.0.0.1:8000/auth/token/ through a POST method. It is giving a 401 Error when I try to get the response in the console. I have tried multiples ways of submitting this but it is the same result. Also the same is working fine on POSTMAN. Please help if possible. I have tried multiple ways of submission, reformatting, checked everywhere on stackoverflow for similar errors, tried different browsers etc. -
Grouping dates in Django templates
im trying to group my objects by year only year in datetime field. {% regroup notificacoes by criados|date:"Y" as criados_list %} <ul> {% for x in criados_list %} <li> {{ x.grouper }} <ul> {% for y in x.list %} <li>{{ y.slug }} : {{ y.arquivo }}</li> {% endfor %} </ul> </li> {% endfor %} </ul> this was supposed to work, but is not working -
my static files like images are not displayed after deploying my django 2.2 app
when I deploy my django 2.2 app on OVH but the static files like the image is not displayed even though the path is correct myapp/settings STATICFILES_DIRS = [ os.path.join(BASE_DIR,'static'), ] STATIC_URL = '/static/' index.html {% extends 'layout/base.html' %} {% load static %} {% block content %} <img src="{% static 'images/fondu2.png' %}" style="width:500px;height:500px"> {% endblock content %} myapp/urls.py ....... from .import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.index, name='index'), ] where is the problem? -
How shall i add images in css using django?
how do i add image in css in django and flask i am not getting it I tried to used simple way of adding the images in css file but it is not showing, and I want it to be loaded and to be seen in my webpage. -
Django Rest Framework: TypeError: Object of type Facility is not JSON serializable
When i try to send a put request to my LeadUpdate Api Endpoint i receive the following error: Django Rest Framework: TypeError: Object of type Facility is not JSON serializable Can someone tell me why that is? This serializer is basically supposed to save assigned facilities within a lead when a lead gets updated and create a "LeadFacilityAssociation" object if any facility id's end up being sent with the IntegerField. serializer.py class LeadUpdateSerializer(serializers.ModelSerializer): is_owner = serializers.SerializerMethodField() assigned_facilities = serializers.IntegerField(required=False) scheduled_datetime = serializers.DateTimeField(required=False) class Meta: model = Lead fields = ( "id", "assigned_facilities", "scheduled_datetime", "is_owner", ) read_only_fields = ("id", "is_owner") def get_is_owner(self, obj): user = self.context["request"].user return obj.agent == user def create(self, validated_data): assigned_facilities = validated_data.pop("assigned_facilities") scheduled_datetime = validated_data.pop("scheduled_datetime") instance = Lead.objects.create(**validated_data) instance.LeadFacilityAssociation.create(assigned_facilities=assigned_facilities,scheduled_datetime=scheduled_datetime) return instance def to_representation(self, instance): representation = super().to_representation(instance) representation["scheduled_datetime"] = instance.LeadFacilityAssociation.first().scheduled_datetime representation["assigned_facilities"] = instance.LeadFacilityAssociation.first().assigned_facilities print(instance.LeadFacilityAssociation.first().assigned_facilities) return representation models.py class Facility(models.Model): name = models.CharField(max_length=150, null=True, blank=False) def __str__(self): return self.Name class Lead(models.Model): first_name = models.CharField(max_length=40, null=True, blank=True) last_name = models.CharField(max_length=40, null=True, blank=True) def __str__(self): return f"{self.first_name} {self.last_name}" class LeadFacilityAssociation(models.Model): assigned_facilities = models.ForeignKey(Facility, related_name='LeadFacilityAssociation') lead = models.ForeignKey(Lead, related_name='LeadFacilityAssociation') scheduled_datetime = models.DateTimeField(null=True, blank=True)