Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
FileNotFoundError: [Errno 2] No such file or directory: 'auto-restart'
Tried use watchdog to auto-restart celery worker/beat in docker container when code changed, and get error: # watchmedo auto-restart -d . -R -- celery -A main_app_name beat -l info Traceback (most recent call last): File "/usr/local/bin/watchmedo", line 8, in <module> sys.exit(main()) File "/usr/local/lib/python3.9/site-packages/watchdog/watchmedo.py", line 641, in main args.func(args) File "/usr/local/lib/python3.9/site-packages/watchdog/watchmedo.py", line 625, in auto_restart handler.start() File "/usr/local/lib/python3.9/site-packages/watchdog/tricks/__init__.py", line 174, in start self.process = subprocess.Popen(self.command, preexec_fn=getattr(os, 'setsid', None)) File "/usr/local/lib/python3.9/subprocess.py", line 951, in __init__ self._execute_child(args, executable, preexec_fn, close_fds, File "/usr/local/lib/python3.9/subprocess.py", line 1821, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: 'auto-restart' # all dependencies installed from requirements.txt: *** pyyaml~=6.0 watchdog~=2.1.6 auto-restart~=2.2 *** When search 'auro-restart' file in container, got: # find / -type f -name '*auto*restart*' /root/.cache/pip/wheels/40/11/c1/9e570f5aac7910cf701243cda8b5fc58e56b329a3d73b4840b/auto_restart-2.2-py3-none-any.whl /usr/local/bin/auto_restart /usr/local/bin/auto_restart_tool /usr/local/lib/python3.9/site-packages/auto_restart/auto_restart_when_git_changed.py /usr/local/lib/python3.9/site-packages/auto_restart/__pycache__/auto_restart_when_git_changed.cpython-39.pyc # Anybody knows the reason of this issue? -
why 'bool' object is not callable
here is my middleware file in django import re from django.conf import settings from django.shortcuts import redirect EXEMPT_URL = [re.compile(settings.LOGIN_URL.lstrip('/'))] if hasattr(settings, 'LOGIN_EXEMPT_URLS'): EXEMPT_URL += [re.compile(url)for url in settings.LOGIN_EXEMPT_URLS] class LoginRequiredMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self,request): response = self.get_response(request) return response def process_view(self,request, view_func, view_args, view_kwargs): assert hasattr(request,'user') path = request.path_info print(path) if not request.user.is_authenticated(): if not any (url.match(path) for url in EXEMPT_URL): return redirect(settings.LOGIN_URL) url_is_exempt = any (url.match(path) for url in EXEMPT_URL) if request.user.is_authenticated() and url_is_exempt: return redirect(settings.LOGIN_REDIRECT_URL) elif request.user.is_authenticated() or url_is_exempt: return None else: return redirect(settings.LOGIN_URL) here is my error : if not request.user.is_authenticated(): TypeError: 'bool' object is not callable please somebody help me with that -
How can generator a url link of text code
I want to make a project that we paste a code on a text field and after submit button, they generate a URL link for accessing this code it is similar to git gists. Can anyone tell me that how can I approach -
How to call a task asynchronously from react to django rest framework using celery
Here is the react frontend code: getStatus = (obj) => { axios.get(`/api/test_calc/${obj.data.task_id}/`, { headers: { 'accept': 'application/json', } }, ).then(resp => { (obj.data.task_status === 'PENDING') ? this.getStatus(obj) : this.getImageClass(resp) console.log("PENDING") }) .catch(err => { console.log(err.response) }) this.deactivateSpinner() Here is the view of the Django API @api_view(('GET',)) def get_status(request, task_id): task = current_app.AsyncResult(task_id) context = {'task_status': task.status, 'task_id': task.id} if task.status == 'SUCCESS': response_data = TestSerializer(Test.objects.get(pk=task.get())) return Response({**context, **response_data.data}, status=status.HTTP_201_CREATED) else: time.sleep(1) return Response({**context}, status=status.HTTP_201_CREATED) Here are my URLS: router = routers.DefaultRouter() router.register(r'test_calc', ImageViewSet) urlpatterns = [ path('', include(router.urls)), path('task/<task_id>/', get_status, name="get_status"), ] All it shows is pending, although when I check Flower (Celery UI), it shows the task is successful. Can someone tell me how to get and send the success to the react frontend? -
when I create super user for custom user model, its dont provide me username, firstname, lastname filed then its show error
when I create super user for custom user model, its dont provide me username, firstname, lastname filed then its show this error: MyAccountManager.create_superuser() missing 3 required positional arguments: 'first_name', 'last_name', and 'username' Here My Code: class MyAccountManager(BaseUserManager): def create_user(self,first_name,last_name, username, email, password=None): email = self.normalize_email(email) if email is None: raise ValueError('User Must have a email') first_name = first_name.title() last_name = last_name.title() username = username.title() user = self.model( email=email, first_name= first_name, last_name=last_name, username=username ) user.set_password(password) user.save(using = self._db) return user def create_superuser(self, email,first_name,last_name, username, password=None): user = self.create_user(email=email, password=password,first_name= first_name, last_name=last_name, username=username), user.is_staff = True user.save(using = self._db) class Account(AbstractBaseUser): first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) username = models.CharField( max_length=50, default='test', unique=True, blank=True, null=True) email = models.EmailField(max_length=100, unique=True) phone_number = models.CharField(max_length=50) # required date_joined = models.DateTimeField(auto_now_add=True) last_login = models.DateTimeField(auto_now_add=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) objects = MyAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELD = ['username', 'first_name','last_name'] -
How to prefix a foreign key object to a model field in Wagtail admin?
In this case, each feature has one Epic (models.Model) epic = models.ForeignKey(Epic, on_delete=models.CASCADE, default='') In the admin drop-down (and only there) I would like to show each item as: epic.name - feature.name Because some of my features have a similar name but different epics. I can't change the __ str __ function of the Feature model or it will affect the whole app. How can I achieve that? -
Error when deploy Django Project on Heroku
I tried to deploy django app on heroku but got this error.I followed every steps from heroku and this website: https://studygyaan.com/django/django-everywhere-host-your-django-app-for-free-on-heroku.This is my error: error: command '/usr/bin/gcc' failed with exit code 1 ERROR: Command errored out with exit status 1: /app/.heroku/python/bin/python -u -c 'import io, os, sys, setuptools, tokenize; Please help me with this problems. -
How to enforce validation in django forms
I have a form that takes in start_time and end_time, both of which are DateTimeFields in my model.py. However, I want to make sure that the start_time is less than the end_time. I have created a function in my forms.py but it does not seem to be taking any effect. How I can enforce this validation? my forms.py class EventForm(ModelForm): class Meta: model = Event # datetime-local is a HTML5 input type, format to make date time show on fields widgets = { "start_time": DateInput( attrs={"type": "datetime-local"}, format="%Y-%m-%dT%H:%M" ), "end_time": DateInput( attrs={"type": "datetime-local"}, format="%Y-%m-%dT%H:%M" ), "title": TextInput(attrs={"placeholder": "Title"}), "description": TextInput(attrs={"placeholder": "Description"}), "author": forms.HiddenInput(), } fields = ["title", "description", "start_time", "end_time", "author"] def clean_time(self): start_time = self.cleaned_data.get('start_time') end_time = self.cleaned_data.get('end_time') if start_time > end_time: raise forms.ValidationError("Start time cannot be greater than end time") return self.cleaned_data def __init__(self, *args, **kwargs): super(EventForm, self).__init__(*args, **kwargs) # input_formats parses HTML5 datetime-local input to datetime field self.fields["start_time"].input_formats = ("%Y-%m-%dT%H:%M",) self.fields["end_time"].input_formats = ("%Y-%m-%dT%H:%M",) my views.py for creating event: def event_create(request): instance = Event() data = request.POST.copy() data["author"] = request.user form = EventForm(data or None, instance=instance) if request.POST and form.is_valid(): form.save() return HttpResponseRedirect(reverse("cal:calendar")) return render(request, "cal/create_event.html", {"event": form}) -
django.db.utils.ProgrammingError: multiple default values specified for column "id" of table "products_customer"
After make migrations , i tried to do migrate, but i am getting the django.db.utils.ProgrammingError: multiple default values specified for column "id" of table "products_customer" But iam remove this customer table from models.py how i solve this ? models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class product(models.Model): product_id = models.IntegerField(primary_key=True) product_name = models.CharField(max_length=255) product_price = models.FloatField() product_stock = models.IntegerField() product_image = models.CharField(max_length=2500) class order(models.Model): order_id = models.IntegerField(primary_key=True) product_id = models.ForeignKey(product,on_delete=models.CASCADE) user = models.ForeignKey(User,on_delete=models.CASCADE) order_quantity = models.IntegerField() order_total = models.IntegerField() order_shipped = models.BooleanField() class address(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) house_name = models.CharField(max_length=255, blank=True) town = models.CharField(max_length=255, blank=True) post_office = models.CharField(max_length=255, blank=True) pincode = models.CharField(max_length=255) district = models.CharField(max_length=255, blank=True) land_mark = models.CharField(max_length=255, blank=True) phone = models.CharField(max_length=15, blank=True) @receiver(post_save, sender=User) def create_user_address(sender, instance, created, **kwargs): if created: address.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_address(sender, instance, **kwargs): instance.address.save() -
Why does django show me existing rows error?
You are trying to add the field 'created' with 'auto_now_add=True' to user without a default; the database needs something to populate existing rows. Provide a one-off default now (will be set on all existing rows) Quit, and let me add a default in models.py -
how use super in django tables2 render_*
i create new Column and add customize render as below class PriceColumn(django_tables2.Column): def render(self, value): if isinstance(value, int) or isinstance(value, float): self.attrs['td']['title'] = f'{round(value, 2):,}' return number_convertor_to_milion(value) return '--- then i used it for field weekly_returns = PriceColumn(verbose_name=_('Weekly Returns')) def render_weekly_returns(self, value,**kwargs): final_result = value*100 // i want to call super().render() like below return super().render(final_result,**kwargs) i want to call super as in code writed but gives error how can do this? -
How to get access token and refresh token ( rest_framework_jwt ) in a single API in Django
I need to get access token and refresh token in a single API, Currently I have 2 API's for both access and refresh tokens url(r'^token-auth', view.ObtainJWTView.as_view(), name='token-auth'), url(r'^token-refresh', refresh_jwt_token), I need one more API for both -
How to remove first brackets from list in django?
I write a query to get the list like this: tStartEnd = APIHistory.objects.values('status_start','status_end') codereview = list(tStartEnd) expected output is: ['start', 'end'] but I'm getting : [('START', 'END')] using django query how get the output like this ['start', 'end'] -
serving media files in django with a small size
I'm building a Django app (call it Drive) to upload photos (2MB or higher) and use its links in another project. the problem is when uploading all photos on the drive and adding their links in the other project the photos take a lot of time to load, I found a solution to server these photos on the drive itself and compress them when uploading, but still takes a long time to load. this is the serve function: def serve(request, path, document_root=None): file_link = path file = File.objects.get(privacy__link=file_link) rendered_file = FileResponse(file.file) return rendered_file it returns the file as a FileResponse and then it will be returned in its full size and I think that is the problem, and I don't want something like this to happen, I just want to preview the photos with small sizes to load faster on the site. any help? -
Django : GET / HTTP/1.1" 404 2029
I'm a beginner Django. I get his 404 error, couldn't find why. Followed all the instructions step by step. Using Django version 3.1.1. Trying to find solution on google, no help. When I execute python manage.py runserver - I get the following message Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). November 16, 2021 - 06:17:59 Django version 3.1.1, using settings 'lecture3.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Not Found: / [16/Nov/2021 06:18:02] "GET / HTTP/1.1" 404 2029 Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). November 16, 2021 - 06:25:43 Django version 3.1.1, using settings 'lecture3.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Not Found: / [16/Nov/2021 06:25:46] "GET / HTTP/1.1" 404 2029 Error on the page is : Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in lecture3.urls, Django tried these URL patterns, in this order: admin/ hello/ The empty path didn't match any of these. Hello/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name="index") ] hello/views.py from django.http import HttpResponse from django.shortcuts … -
'OperationalError ' when I insert : owner = models.ForeignKey(User,on_delete=models.CASCADE)
I'm very new in django, when I put this code : ''' owner = models.ForeignKey(User,on_delete=models.CASCADE) ''' the page gives ' OperationalError ' in a position . Is this code wrong, or it needs something ? I need a good new book in django to free download . -
django-admin start project returns command not found on mac with django version 3.10
I just started learning django and to start my first project, I have installed Python version 3.10.0 on mac. created a virtual environment and installed django but when trying to run django-admin startproject myproject in virtual environment, it returns command not found. could this be a bug on the latest version of python or there is something else I should try ? -
How to display rest api using AJAX in Django?
I want to be able to use the REST API below and display data on a single HTML page. This is the API (response) from a database connection function in my Django project. URL: http://127.0.0.1:8000/api/v1/test/ API output: { "message": "Success !", "server": "Connection established from ('PostgreSQL 12.7, compiled by Visual C++ build 1914, 64-bit',)" } I tried to display the data using AJAX. However, the data does not appear on the page. This is my attempt: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>API Calls Demo</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> </head> <body> <div class="container-fluid"> <h3>Test Output</h3> <br></br> <table class="table table-sm"> <tr> <th>Output</th> </tr> <tbody id="divBody"></tbody> </table> </div> </body> <script> $(document).ready(function () { BindConnection(); }); function BindConnection(){ $.ajax({ type:"GET", dataType: "JSON", url: "http://127.0.0.1:8000/api/v1/test", success: function(data){ console.log(data); var str = ""; var totalLength = data.length; for (let i=0; i < totalLength; i++){ str += "<tr>" + "<td>" + data[i].server + "</td>" "</tr>" } $("#divBody").append(str) } }); } </script> Note: The result can be displayed on the console and there is no error. Sorry for my poor attempt, cause I am still new with Django, REST API, and Javascript (AJAX). I have tried several attempts … -
How to download a file from S3 in django view?
The django view function downloads the files: def download(request): with open('path','rb') as fh: response = HttpResponse(fh.read()) response['Content-Disposition'] = 'inline; filename='+base_name_edi return response This function downloads the files. But I want to download the files from S3. How to find the path of the S3 File so that this function works? -
How to create dynamic database per tenant for multitenant application in Django
I building an app which need to have separate database per customer using Django . In my backend , I want to develop this. I will access my database through API. but I can not find any good solution for it. I can not find yet any Django package for it. -
How to preview image before uploading in django
I am trying to preview image before uploading it to the html page. I am using django. This is my model class Product(models.Model): image = models.ImageField(upload_to='uploads/') thumbnail = models.ImageField(upload_to='uploads/') class Meta: ordering = ['-date_added'] this is my form.py class ProductForm(ModelForm): class Meta: model = Product fields = ['image'] and this is my html page <form method="post" action="." enctype="multipart/form-data"> {% csrf_token %} {{ form.non_field_errors }} <div class="fieldWrapper"> {{ form.image.errors }} <br> <label for="{{ form.image.id_for_label }}"><br>&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;Image: &nbsp;</label> {{ form.image }} </div> <div class="field"> <div class="control" style="margin-bottom: 3%"> <button class="btn btn-theme" style="float:right;">SUBMIT</button> </div> </div> </form> I am able to upload and display the image in the html page but i want it so that before i upload i can see the image i am trying to upload. How can i do that? -
ProgrammingError at / not enough arguments for format string
I'm a Django beginner I'm trying to access a table which is already present in mysql database. for that I used - "python manage.py inspectdb" to get the model info as shown below` from django.db import models class Datatable(models.Model): def str(self): return self.ssid family = models.TextField(blank=True, null=True) validcopies = models.BigIntegerField(blank=True, null=True) location = models.TextField(blank=True, null=True) pool = models.TextField(blank=True, null=True) volume = models.TextField(blank=True, null=True) ssid = models.BigIntegerField(blank=True, null=True) cloneid = models.BigIntegerField(blank=True, null=True) savetime = models.DateTimeField(blank=True, null=True) clonetime = models.DateTimeField(blank=True, null=True) clretent = models.DateTimeField(blank=True, null=True) sumflags = models.TextField(blank=True, null=True) clflags = models.FloatField(blank=True, null=True) totalsize = models.BigIntegerField(blank=True, null=True) sumsize = models.TextField(blank=True, null=True) level = models.TextField(blank=True, null=True) name = models.TextField(blank=True, null=True) client = models.TextField(blank=True, null=True) vmname = models.TextField(blank=True, null=True) nfiles = models.BigIntegerField(blank=True, null=True) group = models.TextField(blank=True, null=True) backup_copy_cloneid = models.BigIntegerField(db_column='backup-copy-cloneid', blank=True, null=True) # Field renamed to remove unsuitable characters. scanned_size_bytes1 = models.BigIntegerField(db_column='scanned-size-bytes1', blank=True, null=True) # Field renamed to remove unsuitable characters. post_seg_bytes1 = models.BigIntegerField(db_column='post-seg-bytes1', blank=True, null=True) # Field renamed to remove unsuitable characters. transferred_size_bytes1 = models.BigIntegerField(db_column='transferred-size-bytes1', blank=True, null=True) # Field renamed to remove unsuitable characters. clone_copy_cloneid = models.BigIntegerField(db_column='clone-copy-cloneid', blank=True, null=True) # Field renamed to remove unsuitable characters. scanned_size_bytes2 = models.BigIntegerField(db_column='scanned-size-bytes2', blank=True, null=True) # Field renamed to remove unsuitable characters. post_seg_bytes2 = models.BigIntegerField(db_column='post-seg-bytes2', blank=True, null=True) … -
django views can't access webkitformboundary
i'm trying to send data with ajax to django views here's my js code messageSENDER.onsubmit = () => { formdata = new FormData(messageSENDER); $.ajax({ headers: {"X-CSRFToken": document.querySelector('[name=csrfmiddlewaretoken]').value,}, method: 'POST', processData: false, ContentType: false, data: formdata, url : '/send/message/', success: function(m){ messageSENDER.reset() } }) } in the view function this is the data i get <QueryDict: {'------WebKitFormBoundaryvME3ZcSodJ0Wyw6a\r\nContent-Disposition: form-data; name': ['"csrfmiddlewaretoken"\r\n\r\n7bsMDcWw2yme8P4FC7cEVnkrOuYLR22HFiyrxv9yTOE8rZzZkLta8DvKuf4SNMjt\r\n------WebKitFormBoundaryvME3ZcSodJ0Wyw6a\r\nContent-Disposition: form-data; name="partnerPK"\r\n\r\n2\r\n------WebKitFormBoundaryvME3ZcSodJ0Wyw6a\r\nContent-Disposition: form-data; name="content"\r\n\r\nmessage content\r\n------WebKitFormBoundaryvME3ZcSodJ0Wyw6a\r\nContent-Disposition: form-data; name="files"; filename=""\r\nContent-Type: application/octet-stream\r\n\r\n\r\n------WebKitFormBoundaryvME3ZcSodJ0Wyw6a--\r\n']}> so how to access it's data the view is working just fine with normal html form and postman but not with ajax def CreateMessage(request): pk = request.POST.get('partnerPK') text = request.POST.get('content') partner = User.objects.get(pk=pk) m = Message.objects.create(content=text, receiver = partner, sender=request.user) when i try to print any of the data it says either None or gives empty array -
Rejecting form post after is_valid
I'm attempting to overwrite the RegistrationView that is part of django registration redux. https://github.com/macropin/django-registration/blob/master/registration/backends/default/views.py Essentially, I want to implement logic that prevents the registration from happening if some condition is present. Checking for this condition requires access to the request. I'm thinking that I might be able to subclass the register function within this Class based view. def register(self, form): #START OF MY CODE result = test_for_condition(self.request) if result == False: messages.error(self.request, "Registration cannot be completed.", extra_tags='errortag') return redirect('/access/register') #END OF MY CODE site = get_current_site(self.request) if hasattr(form, 'save'): new_user_instance = form.save(commit=False) else: new_user_instance = (UserModel().objects .create_user(**form.cleaned_data)) new_user = self.registration_profile.objects.create_inactive_user( new_user=new_user_instance, site=site, send_email=self.SEND_ACTIVATION_EMAIL, request=self.request, ) signals.user_registered.send(sender=self.__class__, user=new_user, request=self.request) return new_user What is the correct way to do this using class based views? I've worked almost exclusively with function based views so far. Thanks! -
Problems getting while hosting django app on heroku
Hey there i have just hosted my Django app on Heroku and i faced theses two problem : "Failed to detect app matching no buildpack" Procfile declares types -> (none) and when i run heroku logs --tail i get this 2013-08-31T21:00:25.085053+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path=/favicon.ico host=cristowip.herokuapp.com fwd="189.137.81.39" dyno= connect= service= status=503 bytes=