Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Override django's foreignkey on_delete SET_NULL function
So, I have a Comment model in a django project I am trying to make, what I want to do is to override the on_delete function of the ForeignKey COMMENT_TYPES = ( (1, "Comment"), (2, "Reply to a comment")) class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) comment_text = models.CharField(max_length=80, blank=False, null=False) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True,editable=False) date_created = models.DateTimeField(auto_now_add=True) date_edited = models.DateTimeField(auto_now=True) post = models.ForeignKey(Post, on_delete=models.CASCADE) parent_comment = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL) comment_type = models.IntegerField(choices=COMMENT_TYPES, default=1) What I want is that when I delete a comment, then all the comments that were linked to the deleted comment, their comment_type should change from 2('reply to a comment') to 1('comment'), so is there a way to override the on_delete function, SET_NULL so that I can change the value in the comment_type field? -
channels get consumer without import
when working with models, to avoid cyclical import: from articles.models import Ariticle # switch to from django.apps import apps Article = apps.get_model('articles.Article') is there a similar way with consumer: from chat.consumers import ChatConsumer # switch to ChatConsumer = I am trying to access to another consumer from one inside: class NoteConsumer(AsyncJsonWebsocketConsumer): @database_sync_to_async def noteOffline(self): from chat.consumers import ChatConsumer user = User.objects.get(pk=int(self.scope['user'].pk)) user.chatProfile.online = False user.save() for cp in user.chatProfile.getRecentContact(): ChatConsumer.send_offline(user.pk, cp.pk) I will be more than glad if you can give me a hand. -
Mutiple user's manger is not found
Hey everybody I bulid I simple website for techers reservations and when I want to signup as techers or student I have that errors Manger isn't available auth.user has swapped for account's.user -
Django Channels send message to another channel layer
let me simplify my question in one sentence: in one consumer, how can I access to another consumer to send message? basically, I have two consumers in seprated apps: note consumer in note app to manage system and crud notifications. chat consumer in chat app to manage social messaging application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( SessionMiddlewareStack( AuthMiddlewareStack( URLRouter( [ path('ws/chat/<int:pk>/', ChatConsumer.as_asgi()), path('ws/note/<int:pk>/', NoteConsumer.as_asgi()), ] ) ) ) ), }) I am implementing online status function. it works like this: note ws connection establishes in every page, as long as you are on our site, you have a notification ws to receive notification. this correspond to the idea of online, therefore, we can save online record to True in db on note ws connection, and False when disconnect, to indicate online status. class NoteConsumer(AsyncJsonWebsocketConsumer): @database_sync_to_async def noteOnline(self): user = User.objects.get(pk=int(self.scope['user'].pk)) user.chatProfile.online = True user.save() @database_sync_to_async def noteOffline(self): user = User.objects.get(pk=int(self.scope['user'].pk)) user.chatProfile.online = False user.save() async def connect(self): # ... await self.noteOnline() async def disconnect(self): # ... await self.noteOffline() in chat friends view, user may want to know if the target he/she is talking to logged off or not, without ws implementation, the information will not be updated immediately, they need … -
Django errors after fake migrations
someone can help me with these errors! I get these errors after replacing my postgresql database and doing the migration all this happened after replacing a postgres backup in execute return self._execute_with_wrappers( File "C:\Users\Facu\Desktop\proyecto_biblioteca\entorno\ibro\lib\site-packages\django\db\backends\utils.py", line 80, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\Facu\Desktop\proyecto_biblioteca\entorno\ibro\lib\site-packages\django\db\backends\utils.py", line 84, in _execute with self.db.wrap_database_errors: File "C:\Users\Facu\Desktop\proyecto_biblioteca\entorno\ibro\lib\site-packages\django\db\utils.py", line 91, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\Facu\Desktop\proyecto_biblioteca\entorno\ibro\lib\site-packages\django\db\backends\utils.py", line 89, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: no existe la relación «django_content_type» LINE 1: ..."."app_label", "django_content_type"."model" FROM "django_co... -
Django conditional required fields - in both DRF and Model.save
My model has a type attribute and get_required_fields method. get_required_fields returns a list of required fields based on self.type which I then use in full_clean method to validate the model before saved for field in self.get_required_fields(): if getattr(self, field, None) is None: missing_fields.append(field) # todo append verbose_name if missing_fields: raise ValidationError({x: "Povinné pole pre daný druh" for x in missing_fields}) The problem is that this doesn't work for DRF model serializers. I've overriden validate method this way: def validate(self, attrs): Income(**attrs).full_clean() return super().validate(attrs) But then I realized this will not work for PATCH method and probably also not for POST with missing fields How can I make it work for both model and DRF ModelSerializer while using the same code to keep it DRY? -
Having trobles Django + Telethon
I am going to make a Django applicaton that gets telegram username as input and sends message to that username. Currently using Telethon, and creating some account in Telegram to make this possible. But my telethon threads not gonna work. Account connected and working properly (session 'anon'). Here is the views.py: from django.shortcuts import render from telethon.sync import TelegramClient from django_telethon.sessions import DjangoSession from django_telethon.models import App, ClientSession from telethon.errors import SessionPasswordNeededError API_ID = '12345678' API_HASH = '123465789456123asdas' def index(request): if request.method == "POST": app, is_created = App.objects.update_or_create( api_id=API_ID, api_hash=API_HASH ) cs = ClientSession.objects.get( name='anon' ) telegram_client = TelegramClient(DjangoSession(client_session=cs), app.api_id, app.api_hash) target_user = request.POST['username_telegram'] target_user = str(target_user) async def send(): try: await telegram_client.send_message(f'@{target_user}', 'Hello from django!') except ValueError: print(f'Sorry no {target_user} user was found') with telegram_client: telegram_client.loop.run_until_complete(send()) return render(request, 'index.html') Output: enter image description here -
Struclog events are misaligned in the console when executing Celery tasks
I use structlog and celery in my Django application and I'm having hard time when logging tasks with structlog in the console. Indeed, events are not properly aligned when printed in the console during a Celery task is being executed. When more tasks are executed logs are barely readable. clear_contextvars and reset_contextvars at the top of the tasks doesn't change the issue. What could be the reason for this misalignment ? Console celery_worker-1 | 2022-10-09T12:25:57.251196Z [info ] Fetch orders complete [account.tasks] account=Anna celery_worker-1 | 2022-10-09T12:25:57.934244Z [info ] Fetch trades [account.tasks] account=Anna length=0 symbol=BBB celery_worker-1 | 2022-10-09T12:25:58.896769Z [info ] Fetch trades [account.tasks] account=Anna length=1 symbol=BBB celery_worker-1 | 2022-10-09T12:25:58.911502Z [info ] Fetch trades complete [account.tasks] account=Anna celery_worker-1 | 2022-10-09T12:25:58.974451Z [info ] Update assets inventory [2022-10-09T12:25:58.976925Zpnl.tasks] account=Anna celery_worker-1 | [info ] Fetch orders [account.tasks] account=Nico celery_worker-1 | 2022-10-09T12:25:58.989326Z2022-10-09T12:25:58.990257Z [info ] Update contracts inventory [pnl.tasks] account=Anna celery_worker-1 | [info ] Update assets inventory no required [pnl.tasks] account=Anna celery_worker-1 | 2022-10-09T12:25:59.011112Z [info ] Update contracts inventory no required [pnl.tasks] account=Anna celery_worker-1 | 2022-10-09T12:26:00.380746Z [info ] Fetch orders complete [account.tasks] account=Nico celery_worker-1 | 2022-10-09T12:26:01.222383Z [info ] Fetch trades [account.tasks] account=Nico length=0 symbol=ABC celery_worker-1 | 2022-10-09T12:26:01.570339Z [info ] Fetch trades [account.tasks] account=Nico length=1 symbol=ABC celery_worker-1 | 2022-10-09T12:26:01.588788Z … -
how to skip showing to be deleted objects when deleting an item on the Django admin
in my Django application, there are some items that are related to 5k or more objects, so when the user performs a delete from the Django admin site .. the delete confirmation page keeps loading and it crashes at the end with an error ( out of memory ) So what I need to do is to skip showing the related - to be deleted - objects when confirming on deleting the object. please check the screenshot to get a better clew on what I need to hide or skip showing when doing a delete -
Expecting value: line 1 column 1 (char 0) Django form
I am getting error Expecting value: line 1 column 1 (char 0) when trying to add new company with Django form. I could not find duplicate questions on google so i want to ask for any help. My files are below model.py class Company(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=300, unique=True, blank=False, null=False) domains = ArrayField(models.CharField(max_length=100)) licence_type = models.CharField(max_length=20, default='Demo') status = models.CharField(max_length=20, default='Passive') sector = models.CharField(max_length=100) security_score = models.IntegerField(default=0) licence_start_date = models.DateTimeField() licence_end_date = models.DateTimeField() insert_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.name forms.py class AddCompanyForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(AddCompanyForm, self).__init__(*args, **kwargs) class Meta: model = Company exclude = ['security_score', 'insert_date', 'licence_start_date', 'licence_end_date'] name = forms.CharField( required=True, widget=forms.TextInput( attrs={ "class": "form-control", "id": "name", "placeholder": "Company Name" } )) sector = forms.CharField( required=False, widget=forms.TextInput( attrs={ "class": "form-control", "id": "sector", "placeholder": "Company Sector" } )) domains = forms.CharField( required=True, widget=forms.Textarea( attrs={ "class": "form-control", "id": "domains", "rows": "4", "placehoder":"Separate domains with comma (,)" } )) licence_date = forms.CharField( required=True, widget=forms.TextInput( attrs={ "class": "form-control", "id": "licence_date", } )) licence_type = forms.ChoiceField( choices = [ ('Demo', 'Demo'), ('Basic', 'Basic'), ('Pro', 'Pro'), ('Enterprise', 'Enterprise')], required=True, widget=forms.Select( attrs={ "class":"form-control select2", "id":"licence_type" } )) status = forms.ChoiceField( choices = [ ('Passive', 'Passive'), ('Active', 'Active')], required=True, widget=forms.Select( attrs={ … -
argument of type 'function' is not iterable
def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_users: return view_func(request, *args, **kwargs) else: return HttpResponse('You are not authorized to view this Page') return wrapper_func return decorator . . . . . . -
Heroku buildpack triggered only in staging pipeline, not in prod. Feature? Or misconfiguration?
I have specifically included heroku/python in the build pack section for my two Heroku Django projects but the build pack is triggered only when I deploy by pushing my changes in my main git branch to the staging pipeline, not when I promote the changes to production. Why is that? My builds are not stateful (as Heroku addresses in their doc on design considerations). By that I mean that I can handle all my configuration variables in the Heroku dashboard with one set of variables for staging and a separate set for production. There are no variables that are hard coded. All my configurations are dynamic. The problem I see is that when I update my requirements.txt with newer versions of Python modules/libraries, how do I instruct Heroku to trigger the build back in prod to rebuild the slug? Have I misconfigured my Heroku production pipeline? Or is it somehow unnecessary to rebuild slugs in prod but only in staging? When I typed the title for my question here, Stack Overflow recommended the following questions and answers from other users which didn't seem to answer my question: Maintaining staging+prod environments from single repo, 2 remotes with revel buildpack on heroku … -
Secondary Domain Static Files in Cpanel with a django application
I am deploying a django app in cpanel this application isnt on the main domain it is on a secondary one i tried copyaing the static files into the domain name inside the public html but the webapp doesnt read them all styles and js files are not loading on the front-end i applied collect static before deploying from github and copied the static file into a file of the secondary domain name in the file manager at first but didnt work, and tried copaying it into the public html but didnt work too i think there is a problem with the method i am following in this link https://parmarnaitik0909.medium.com/deploying-hosting-a-django-website-on-cpanel-with-git-version-control-6e8dce70a316 -
Search form in django using function
I'm trying to create a search form in view.py using a function , I have Course model which has a name attribute , a "Course matching query does not exist " error occurs when I click on the search button , here's my view : view.py here's where I'm keeping my form : form my app namespace is "uni" and the name of the search url view is "search" where is the error ? -
Uploading Data From Django SQL Database Into Google Sheets
I have an offline django webapp that works on localhost. The database contains daily attendance sheet, that needs to be viewed by teachers online through google sheets. How to transfer the data from Django SQL into Google Sheets? Any help would be appreciated.. -
Digitalocean and Django droplet very slow after upgrade
How best can I solve the issue of the server being very slow, I upgraded my droplet from : Basic - Premium AMD Shared CPU 1 vCPU 1 GB 25 GB 1 TB to this : Basic - Premium AMD Shared CPU 2 vCPUs 4 GB 50 GB 4 TB My endpoints are all cached, but the issue is still there. But the site is still very slow, what other things I should consider for the better performance ? -
Reusing JSON response after Fetch request
I try to use a JSON response from server and print for the user error message. I receive JSON response successfully and alert function works as I expect, but what I actually need is to insert element to the DOM, but when fetch.then construction ends I'm being redirected to the root '/' and Django server wipes out the template that I try to work with. On Django side I use JsonRequest function with status code=400. What I'm doing wrong? Please give me a clue. My JS code looks like this: document.addEventListener('DOMContentLoaded', function() { // Use buttons to toggle between views document.querySelector('#inbox').addEventListener('click', () => load_mailbox('inbox')); document.querySelector('#sent').addEventListener('click', () => load_mailbox('sent')); document.querySelector('#archived').addEventListener('click', () => load_mailbox('archive')); document.querySelector('#compose').addEventListener('click', compose_email); // By default, load the inbox load_mailbox('inbox'); }); function compose_email() { // Show compose view and hide other views document.querySelector('#emails-view').style.display = 'none'; document.querySelector('#compose-view').style.display = 'block'; // Clear out composition fields document.querySelector('#compose-recipients').value = ''; document.querySelector('#compose-subject').value = ''; document.querySelector('#compose-body').value = ''; // Send email document.querySelector("#compose-form").onsubmit = function() { let composeView = document.querySelector("#emails-view"); fetch('/emails', { method: 'POST', body: JSON.stringify({ recipients: document.querySelector("#compose-recipients").value, subject: document.querySelector("#compose-subject").value, body: document.querySelector("#compose-body").value }) }) .then(response => response.json()) .then(result => { let p = `<p>${result.error}</p>`; composeView.append(p); alert(result.error); }) } } function load_mailbox(mailbox) { // Show the mailbox … -
Django POST request data from Javascript fetch is displayed, but i get an error "Expecting value: line 1 column 1 (char 0)"
I am trying to send data with Javascript fetch and I keep getting error: "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)". inside index.js: fetch('save_user_post/', { method: 'POST', credentials: 'same-origin', headers:{ 'Accept': 'application/json', 'X-CSRFToken': user_post_form_csrf.value, }, body: JSON.stringify({ 'input_user_post_value': input_user_post.value, }) }) .then(response => { return response.json() }) .then(user_post_save_result => { console.log(user_post_save_result ) }) and than in views.py: def save_user_post(request): if request.method != "POST": return JsonResponse({"error": "no POST method"}, status=400) if request.user.is_authenticated: print(request.body) #here I checked if I can receive this data data_of_post = json.loads(request.body) input_user_post_value = data_of_post.get('input_user_post_value', '') print(f'input_user_post_value is {input_user_post_value}') #here I checked if I can get exactly this value post_save_result = {'post_saved_or_not': 'saved'} return JsonResponse(description_save_result) Although both print() commands display valid fetch data, the error that relates to the line data_of_post = json.loads (request.body) is also displayed. How to get rid of this error? -
How to dynamically create upload path for media files django-ckeditor?
I am using RichTextUploadingField in my model. I have set upload path to CKEDITOR_UPLOAD_PATH = "uploads/" I use this field when I am on path: path("<slug:p_slug>/<slug:m_slug>/<slug:slug>/edit_feature/", views.EditFeature.as_view(), name="edit_feature"), I want the path of the file looks like this, after adding a file:<slug:p_slug>/<slug:m_slug>/<slug:slug>/<file_name>/ How to achieve this? -
Generate python script on backend and pass it to user
I'm new to Django, and I have a question. How can I pass a JSON, made in the frontend by the user interacting with the UI in the frontend, to Django, run a python script that takes that JSON, converts it into another python script with the instructions that the user gave, and then downloading that script in the user's page? I already have the script that converts the JSON to the python file, but the part I don't know about is how I can connect the JSON that the user gave to the python script that converts it and then gives the result back. -
Django Rest API from Database
I have 2 APIs from my existing project. Where One provides the latest blog posts and another one provides sorting details. The 2nd API (sorting) gives blog posts ID and an ordering number, which should be in the 1st,2nd,3rd...n position. If I filter in the first API with that given ID I can get the blog post details. How can I create a Django REST API from Database? or an API merging from that 2 APIs? Any tutorial or reference which might help me? Frist API Response: { "count": 74, "next": "https://cms.example.com/api/v2/stories/?page=2", "previous": null, "results": [ { "id": 111, "meta": { "type": "blog.CreateStory", "seo_title": "", "search_description": "", "first_published_at": "2022-10-09T07:29:17.029746Z" }, "title": "A Test Blog Post" }, { "id": 105, "meta": { "type": "blog.CreateStory", "seo_title": "", "search_description": "", "first_published_at": "2022-10-08T04:45:32.165072Z" }, "title": "Blog Story 2" }, 2nd API Response [ { "featured_item": 1, "sort_order": 0, "featured_page": 105 }, { "featured_item": 1, "sort_order": 1, "featured_page": 90 }, Here I want to create another API that will provide more details about sorting for example it will sort like this https://cms.example.com/api/v2/stories/105 and catch Title, Image & Excerpt and If there is no data from Sorting details it will show the first API's response by … -
Django database migrations are gives no "No migrations to apply." error
Hi I am having issues trying to migrate my django database. I have a database that definitely cant be cleared/removed, which is what most solutions recommend. I have tried all the following command-sets: python manage.py makemigrations python manage.py migrate --run-syncdb python manage.py makemigrations django_project python manage.py migrate django_project python manage.py migrate python manage.py makemigrations && python manage.py migrate python manage.py makemigrations django_project python manage.py migrate --fake-initial python manage.py migrate I cleared the migrations folder everytime. Every set resulted in the same response: 08:59 ~/GluoApi $ python manage.py makemigrations && python manage.py migrate Migrations for 'django_project': django_project/migrations/0001_initial.py - Create model Blacklist - Create model Like - Create model Post - Create model PostReaction - Create model Profile - Create model Token - Create model ReportUser - Create model ReportPost - Add field reports to profile - Add field requests to profile - Add field user to profile - Create model PostReactionReport - Create model PostReactionLike - Add field likes to postreaction - Add field post to postreaction - Add field poster to postreaction - Add field reports to postreaction - Add field likes to post - Add field poster to post - Add field reports to post - Add field post … -
Django TemplateDoesNotExist - can not render the template
I am new to django and I am using version 4.1.2. I have created an app with the following structure I have configured the app ( 'home') template in the primary setting file like the following. but still, I am getting the error TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR/'home', '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', ], }, }, ] here is my view code from django.shortcuts import render from django.http import HttpResponse # Create your views here. def home(request): return render(request, ' home/welcome.html' , {}) -
In Django, How i can search robotics course by entering only robot or robo?
please help me to solve this. i am trying to search object from url by it's keyword [api.py][1] [api.py][2] [result][3] [error][4] [1]: https://i.stack.imgur.com/v2aHS.png [2]: https://i.stack.imgur.com/oyc44.png [3]: https://i.stack.imgur.com/ZI3yJ.png [4]: https://i.stack.imgur.com/8amG9.png -
How to make boolean editable as checkboxes in djano-admin change_list panel?
One of my model as a boolean field (name of the field = deactivated). This field is displayed with "green checked" or "red unchecked" icon in tha change list admin panel. I would like to have this boolean field editable with checkboxes in the change list panel I've read documentation and google my question but could not find solution... the best I found is define an action that make selected row checked/unchecked...