Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cosine similarity query in elasticsearch
I have documents saved inside an index x which is inside another index y ie Maker/Ford and Maker/BMW, here documents are saved inside Ford which is inside Maker. Similarly for BMW. I need to find cosine similarity. I tried scripts, { "query": { "script_score": { "query": { "match_all": {} }, "script": { "source": "Ford['_vector'].size() == 0 ? 0 :cosineSimilarity(params.queryVector,'_vector')+1", "params": { "query_vector": [ 0,1,12,4 ] } } } } } { "script_score": { "query": {"match_all": {}}, "script": { "source": "cosineSimilarity(params.query_vector, '_vector') + 1.0", "params": {"query_vector": query_vector} } } } None of them really worked. What would be the solution? -
How to install django to the computer without internet connection (offline)
I am a beginner python programmer, I am trying to create django project (with PyCharm) on local computer without internet connection, but I am getting error from PyCharm that "install django failed" [Here you can see the error which shows PyCharm[][1]1 To my local computer I installed only PyCharm and Python 3.10.4 -
How to securely deploy a Django project on client machine server without code visibility?
I have a Django project which my Clients want to run on their server but I do not want them to have access or be able to read my code. I have looked at several blogs on internet but I could not find a solution to securely hide my code or encrypt them for non readability. I have tried creating binaries and also encrypting my .py files but it did not work. Is there a way to achieve this? -
How To Annotate Modified Related-Object Table In Django
I have a small business app which can be simplified as following models: class Client(..): name = CharField(...) class Sale(..): client = ForeignKey(Client, ...) item = CharField(...) time = DateTimeField(...) value = DecimalField(...) class Receive(..): client = ForeignKey(Client, ...) time = DateTimeField(...) value = DecimalField(...) Now I need a client-list-view displaying all clients with total sales, payments, receivable value and earliest date of sales unpaid ("edsu") that payment cannot cover. E.g. Client A 2022-01-01: bought Item X for $10, 2022-02-15: bought Item Y for $15, 2022-02-25: bought Item X for $10, and 2022-03-10: paid $12. Then Client A has a receivable of $23 and edsu of 2022-02-15. So far I use raw sql (as following) to do the query, and it works well. def client_list_view(request): ... clients = Client.objects.raw( raw_query = '''WITH app_balance AS ( SELECT id, client_id, item, time, val, SUM(sale) OVER wCN0 - SUM(receive) OVER wClt AS unpaid FROM ( SELECT id, client_id, item, time, val AS sale, 0 AS receive FROM app_sale UNION SELECT id, client_id, '' AS item, time, 0 AS sale, val AS receive FROM app_receive ) app_balance WHERE time < %(te)s::TIMESTAMPTZ WINDOW wClt (PARTITION BY client_id), wCN0 (wClt ORDER BY time ROWS BETWEEN UNBOUNDED … -
How to implement long polling with Django Apscheduler?
Really need help here. I'm trying to implement long polling with React as frontend and Django as backend. The plan right now is React will call the api endpoint, and wait till there result for it. The issue is, the function is trigger by apscheduler, but I have no idea on how to pass the return value out. I tried with apscheduler listener, but it only get the JobEvent itself, not the return value. I have think of put the value in request session, but same idea, since there no request passed in, how should I return or pass the value to session? I'm open to any solution, if there any other package allow me to schedule a weekly job and pass value as long polling. Much appreciate! -
i am creating my first project in django but i am getting error may i know the reason
may i know the reason why i am getting the yello mark or it is an error can yoou please rectify it -
How to pass two forms from one generic class in django
I want to pass two forms in one HTML template, I have two different models User and profile models.py: class Profile(models.Model): user = models.OneToOneField(User,null=True,on_delete=models.CASCADE) home_phone = models.CharField(max_length=20, blank=True, null=True) mobile_phone = models.CharField(unique=True, max_length=20,null=True) personal_id = models.CharField(max_length=30, blank=True, null=True) address_line_1 = models.CharField(db_column='address_Line_1', max_length=200,null=True) # Field name made lowercase. address_line_2 = models.CharField(db_column='address_Line_2', max_length=200, blank=True, null=True) # Field name made lowercase. city = models.CharField(max_length=50,null=True) country_fk = models.ForeignKey('Country', models.DO_NOTHING, db_column='country_FK',null=True) # Field name made lowercase. gender_fk = models.ForeignKey('Gender', models.DO_NOTHING, db_column='gender_FK',null=True) # Field name made lowercase. bdate = models.DateField(blank=True,null=True) def __str__(self): return str(self.user) members views.py class UserEditView(generic.UpdateView): form_class = EditProfileForm template_name = 'registration/edit_profile.html' success_url = reverse_lazy('home') def get_object(self): return self.request.user members forms.py class EditProfileForm(UserChangeForm): email = forms.EmailField(widget=forms.EmailInput(attrs={'class':'form-control'})) first_name = forms.CharField(max_length=100, required=True, widget=forms.TextInput(attrs={'class':'form-control'})) last_name = forms.CharField(max_length=100, required=False,widget=forms.TextInput(attrs={'class':'form-control'})) username = forms.CharField(max_length=100, required=False,widget=forms.TextInput(attrs={'class':'form-control'})) class Meta: model = User fields = ('username','first_name','last_name','email','password') class ProfileForm(ModelForm): Years = [x for x in range(1940,2021)] home_phone = forms.IntegerField(min_value=10000000,max_value=999999999,required=False,widget=forms.NumberInput(attrs={'class':'form-control'})) mobile_phone = forms.IntegerField(min_value=10000000,max_value=999999999,required=False,widget=forms.NumberInput(attrs={'class':'form-control'})) personal_id = forms.IntegerField(min_value=100000000000,max_value=9999999999999,required=False,widget=forms.NumberInput(attrs={'class':'form-control'})) address_line1 = forms.CharField(max_length=100, required=True, widget=forms.TextInput(attrs={'class':'form-control'})) address_line2 = forms.CharField(max_length=100, required=False,widget=forms.TextInput(attrs={'class':'form-control'})) city = forms.CharField(max_length=100, required=True,widget=forms.TextInput(attrs={'class':'form-control'})) Country = forms.ModelChoiceField(queryset=Country.objects,required=True,label=_('Country')) gender = forms.ModelChoiceField(queryset=Gender.objects,required=True,label=_('Gender')) bdate = forms.DateField(widget=forms.SelectDateWidget(years=Years)) class Meta: model = Profile fields = ('address_line_1','address_line_2','bdate','city','country_fk','gender_fk','home_phone','mobile_phone','personal_id') I want both forms show in my template to save the user information in User model and Profile model -
Django ModelChoiceField validation error using a custom query Manager
I am getting a validation error when trying to submit a form using a ModelChoiceField with a queryset using a custom Manager. The standard objects manager is also replaced with a custom manager that filters out archived objects. This is working well throughout the site My model (very simplified): # Use this as the default manager - filters out any records with an archivetype class ActiveManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(archive__isnull=True) # Alternative manager that returns non archived records and records archived with 'SYS' only class SysManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(models.Q(archive__isnull=True) | models.Q(archive='SYS')) class Inventory(models.Model): item = models.CharField(primary_key=True) description = models.CharField() archive = models.CharField(null=True, blank=True) objects = ActiveManager() objects_sys = SysManager() objects_all = models.Manager() # Default manager now objects_all class Building(models.Model): item = models.ForeignKey(Inventory, on_delete=models.PROTECT) I have a Building form that uses the Item field and adjusts the widget attributes (I need extra attributes in the HTML): class BuildingForm(forms.ModelForm): item = forms.ModelChoiceField(queryset=Inventory.objects_sys.all(), widget = forms.TextInput(attrs={ 'class': 'important', 'code': '1x1'})) Inventory.objects_sys.all() returns a queryset that includes an Inventory record with an item called 'INSPECT' while Inventory.objects.all() does not. This is expected and desired behavior in my case. The dropdown created shows the additional records returned by the custom manager (one of them … -
Why does my website work fine when tested locally, but the sessionid cannot be stored when using a domain name?
please help me!!! My project backend is django and frontend uses react. Local testing with localhost works fine. When I go online on the server and adjust the apache domain name, the sessionid cannot be automatically stored. I have tried many methods, but they are not available. But I found that if I don't use the apache proxy, it works fine if I use the ip directly, and the sessionid can also be stored. What is the reason for this? The code I put below. Django Settings INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django_crontab', 'command_app', 'djcelery', 'corsheaders' ] MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware' ] CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True # CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOWED_ORIGINS = [ 'http://react server ip:3000', 'https://react server ip:3000', 'http://localhost:3000', 'http://server ip:3000', 'https://server ip:3000', 'http://www.my domain name.com', 'https://www.my domain name.com', 'http://my domain name.com:3000', 'https://my domain name.com:3000', 'http://my domain name.com', 'https://my domain name.com', ] REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ("CustomAuthentication", ) } CORS_ALLOW_METHODS = ( 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', 'VIEW', ) CORS_ALLOW_HEADERS = ( 'XMLHttpRequest', 'X_FILENAME', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', 'Pragma', ) CACHES = { 'default': { 'BACKEND': "django_redis.cache.RedisCache", … -
I modify response.data in Django REST Framework view.py. Why am I getting an AttributeError during testing but not with actual API use?
My Django REST Framework API is working just as expected. In view.py, I modify OrderViewSet, def partial_update, to add another key/value pair to the response.data dict before it is saved to the db. It works without errors when I call the API with Postman. However, when I run tests for the same functionality it fails and returns: request.data["submission_date"] = datetime.now() AttributeError: This QueryDict instance is immutable Why would I get this error during testing if it is not occurring during actual API use? View.py class OrderViewSet(viewsets.ModelViewSet): """ Includes custom PATCH functionality """ queryset = Order.objects.all().order_by('-order_date') serializer_class = OrderSerializer authentication_classes = (authentication.TokenAuthentication,) permission_classes = [permissions.IsAuthenticated] def partial_update(self, request, *args, **kwargs): """ Update status and timestamp fields accordingly """ status = request.data['status'] if status == 'submitted': request.data["submission_date"] = datetime.now() if status == 'packaged': request.data["packaged_date"] = datetime.now() if status in ['sold', 'canceled', 'abandoned']: request.data["finished_date"] = datetime.now() return super().partial_update(request, *args, **kwargs) Test.py def test_patch_order_status_from_cart_to_submitted(self): """ test patching order status from cart to submitted """ order = sample_order(user=self.user) payload = { "status": "submitted" } res = self.client.patch(order_detail_url(order.id), payload) self.assertEqual(res.status_code, status.HTTP_200_OK) patched_order = Order.objects.get(id=order.id) self.assertEqual(patched_order.status, 'submitted') def test_submitted_timestamp(self): """ test that patching order status to submitted also leaves timestamp """ order = sample_order(user=self.user) payload = { … -
Unsupported operation error creating and saving json file
Ive been trying to save a json file created from a to a filefield, I got an unsuported operation error "not readable", this is my code from django.core.files.base import File @receiver(post_save,sender=ProyArq) def ifc_a_json(sender,instance,*args,**kwargs): if instance.arch_ifc: jsoon = ifc_2_json("path_to_file") json_file_nom = instance.nombre.replace(' ','')+'.json' with open(json_file_nom, 'w') as outfile: json.dump(jsoon, outfile, indent=2) json_fk = JsonIFC.objects.create(proy_fk=instance) json_fk.ifc_json.save(json_file_nom,File(outfile),True) im working with IFC files, and I want to store them also as json, I tried instead of saving the json as a JSONField, to save it as a foreign key file since the size of the json Im working are above 10mb, is this the best approach for this?? -
row data from axios in material-table only render after refreshing the page
Currently I am facing a problem that the data from axios POST request to material-table will not render immdiately. I need to refresh it in order to show it. I have a axios request structure like this: export default function DataWorker() { const [entries, setEntries] = useState({ data: [ { id: "", position: "", defect: "", tool: "" } ] }); const [state] = React.useState({ columns: [ { title: "Position", field: "position" }, { title: "Defect Type", field: "defect" }, { title: "Tool Decision", field: "tool" } ] }); const url = "http://127.0.0.1:8000/api/manual_ver_data/" useEffect(() => { axios.get(url) .then(response => { let data = []; response.data.forEach(el => { data.push({ id: el.id, position: el.position, defect: el.defect, tool: el.tool }); }); setEntries({ data: data }); }) }, []); return ( <MaterialTable columns={state.columns} data={entries.data} editable={{ onRowAdd: (newData) => new Promise(resolve => { setTimeout(() => { resolve(); const data = [...entries.data]; const populateData = (axiosResponse) => {data.push(axiosResponse)} axiosCallBack(populateData) console.log(data) function axiosCallBack (populateData) { axios.post(url, newData) .then(function(res){ populateData(res.data) }) }; setEntries({ ...entries, data }); }, 600) }) }} /> ) }; This is my view.py: @api_view(['GET', 'POST']) def TableViewList(request): if request.method == 'POST': serializer = TabelSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) After … -
I'd like to solve django webserver collectstatic error in ubuntu server
before i start my question, it is my first time to make a question in stackoverflow! I hope you all doing really really well for everything what you do. i try to get static file to using 'python manage.py collectstatic', but it's not working. I run my django project in Ubuntu 20.04.4, and using Nginx as a webserver, and Guicorn for WSGI server. Here is my error log, You have requested to collect static files at the destination location as specified in your settings. This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: yes Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/devadmin/venvs/bio_platform/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/devadmin/venvs/bio_platform/lib/python3.8/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/devadmin/venvs/bio_platform/lib/python3.8/site-packages/django/core/management/base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "/home/devadmin/venvs/bio_platform/lib/python3.8/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/home/devadmin/venvs/bio_platform/lib/python3.8/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 209, in handle collected = self.collect() File "/home/devadmin/venvs/bio_platform/lib/python3.8/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 135, in collect handler(path, prefixed_path, storage) File "/home/devadmin/venvs/bio_platform/lib/python3.8/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 368, in copy_file if not self.delete_file(path, prefixed_path, source_storage): File "/home/devadmin/venvs/bio_platform/lib/python3.8/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 278, in delete_file if self.storage.exists(prefixed_path): File "/home/devadmin/venvs/bio_platform/lib/python3.8/site-packages/django/core/files/storage.py", line 362, in exists … -
Django HTMX: How to Remove Search List Group Suggestion When User Clear the Input Keyword in the Search Field?
I've been working on a search function for Django project using HTMX. The search function can successfully generate list group suggestion based on the keyword that user input by using hx-trigger="keyup changed delay:500ms". However, when user clear the search field, the list group suggestion still displayed on the page. How can I possibly remove the list group suggestion? Here are some snippet from my code: search.html <div class="container-fluid p-2"> {% csrf_token %} <input type="text" hx-get="{% url 'search-obj' %}" hx-target="#result" hx-trigger="keyup changed delay:500ms" name="search" class="form-control" placeholder="Search Object Here..."/> </form> </div> <div id="result"></div> searchresult.html {% if results %} {% csrf_token %} <ul class="list-group"> {% for object in results %} <li class="list-group-item justify-content-between align-items-center"> {{object.name}} </li> {% endfor %} </ul> {% else %} <p>No result</p> {% endif %} views.py def searchobj(request): searchtxt = request.GET.get('search') results = Object.objects.filter(name__icontains=searchtxt) context = {'results' : results} return render(request, 'base/searchresult.html', context) urls.py urlpatterns = [ path('', views.home, name="home"), path('search-line/', views.searchobj, name="search-obj"), ] -
How to count a single field of a django queryset with multiple group by?
Let's say I have a queryset qs. I'm grouping by the queyset as follow: ( qs.annotate( catering_price_enabled=F("outlet__library__settings__sligro_catering_price_enabled"), ) .values("assortment_sync_id", "catering_price_enabled") .order_by("assortment_sync_id", "catering_price_enabled") .distinct("assortment_sync_id", "catering_price_enabled") ) And I'm getting something like: <QuerySet [ {'assortment_sync_id': '01234', 'catering_price_enabled': False}, {'assortment_sync_id': '01234', 'catering_price_enabled': None}, {'assortment_sync_id': '56789', 'catering_price_enabled': None}, ]> What I'm trying to do is to annotate this queryset so I can eventually filter for values > 1. In other words, each assortment_sync_id can have only value of catering_price_enabled. If I add .annotate(count=Count("assortment_sync_id")) django raises NotImplementedError: annotate() + distinct(fields) is not implemented. I tried this approach because it obviously works with just one field. How can I get the expected output below? <QuerySet [ {'assortment_sync_id': '01234', 'catering_price_enabled': False, 'count': 2}, {'assortment_sync_id': '01234', 'catering_price_enabled': None, 'count': 2}, {'assortment_sync_id': '56789', 'catering_price_enabled': None, 'count': 1}, ]> -
Change Header Key for rest_framework's TokenAuthorization
By default, rest_framework's TokenAuthentication uses the "Authorization" key in the header, and looks for the keyword "Token" when authenticating requests. Authorization: Token [value] How do I change it to use the "API-AUTH" key instead, and no keyword? API-AUTH: [value] -
How can I add a default value for DateField in a model?
Using Django/python. So I have a 'food' model that is taking multiple user inputs, one of which is 'type' and has the options of 'fresh' and 'pantry'. Another is a DateField that represents an expiration date. What i want is that when the user selects 'fresh' in the type field, I want the default date to be todays date + 3 days. If the user selects pantry then I want to use the date that is entered into my food model. exp = models.DateField('exp date', blank=True, null=True) Im not sure if more of my code will be needed or if what im asking is possible but any help would be appreciated. -
Reverse for 'department-detail' ....'{'department_id': 2}' not found. 1 pattern(s) tried: ['(?P<deraptment_id>[^/]+)\\Z']
) Подскажите, пожалуйста, что я сделал не так? При переходе на http://127.0.0.1:8000/deraptment/ получаю ошибку: Reverse for 'department-detail' with keyword arguments '{'department_id': 2}' not found. 1 pattern(s) tried: ['(?P<deraptment_id>[^/]+)\Z'] Вот все поля ошибки: image urls.py from main import views urlpatterns = [ path('<deraptment_id>', views.department_detail, name='department-detail'), path('deraptment/', views.departments, name='departments'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py def departments(request): departments = Department.objects.all() return render(request, 'departments.html', {'departments': departments}) def department_detail(request, department_id): department = get_object_or_404(Department, id=department_id) return render(request, 'department_detail.html', {'departments': departments}) base.html <span class="text-uppercase"></span> <a href="{% url 'departments' %}" class="list-group-item {% if request.path == department %} active {% endif %}">Departments</a> department_detail.html {% extends 'base.html' %} {% block title %} Department {{ department.name }} {% endblock%} {% block page %} <a href="{% url 'departments' %}">Departments</a> <div> <h2>{{ department.name }}</h2> <div>{{ department.description }}</div> </div> {% endblock %} department.html (В нём отдаёт ошибку) {% extends 'base.html' %} {% block title %} Departments {% endblock%} sd {% block page %} {% for department in departments %} <div> <h2>{{ department.name }}</h2> <a href="{% url 'department-detail' department_id=department.id %}">{{ department.name }}</a> <div>{{ department.description }}</div> </div> {% endfor %} {% endblock %} -
Django Rest Framework: Create List Model with custom data
Assume that I want to create multiple model objects and I want to add some generated unique data to all of them when saving. So if post something like this to an endpoint: [ { "createDate":"now" }, { "createDate":"now" } ] The response should be something like: [ { "createDate":"now", "uid":"1" }, { "createDate":"now", "uid":"2" } ] I have created a ViewSet for this and generate the necessary fields in the perform_create ovveride method: def perform_create(self, serializer): unique_ids = ReleModuleConfig.objects.values_list('uid', flat=True) uid = generate_random_id(unique_ids) serializer.save(added_by=self.request.user, updated_by=self.request.user, uid=uid) However when I save this, the same uid is set for all of the objects. So the response is: [ { "createDate":"now", "uid":"1" }, { "createDate":"now", "uid":"1" } ] How could I generate unique fields and inject it into the serializer if I have multiple objects? I know that there is already an ID unique field by default on most tables, but I have to generate QR codes and other things as well, I just removed that from this example to make it easier to understand. -
about movie ticket booking in django
from django.shortcuts import render from . models import Movie Create your views here. def index(request): movies=Movie.objects.all() return render(request,'index.html',{ "movies":movies }) from django.urls import path from . views import index app_name='movies' urlpatterns = [ path('',index,name="home") -
Retrieve list of employees in a company model in Django
I have set up the two following models: Model "User" class User(AbstractBaseUser, PermissionsMixin): username = models.CharField('username', max_length=30, blank=True) email = models.EmailField('Adresse mail', unique=True) first_name = models.CharField('Prénom', max_length=30, blank=True) last_name = models.CharField('Nom', max_length=30, blank=True) date_joined = models.DateTimeField('date joined', auto_now_add=True) company = models.OneToOneField(Customer, on_delete=models.CASCADE, blank=True, null=True) is_active = models.BooleanField('active', default=True) is_staff = models.BooleanField('staff status',default=False) is_superuser = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] class Meta: verbose_name = 'user' verbose_name_plural = 'users' def get_full_name(self): ''' Returns the first_name plus the last_name, with a space in between. ''' full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def get_short_name(self): ''' Returns the short name for the user. ''' return self.first_name def email_user(self, subject, message, from_email=None, **kwargs): ''' Sends an email to this User. ''' send_mail(subject, message, from_email, [self.email], **kwargs) Model "Customer" class Customer(models.Model): name = models.CharField(max_length=200, blank=False) transporters = models.ManyToManyField(Transporter, blank=True) def __str__(self): return self.name class Meta: verbose_name = "Company" verbose_name_plural = "Companies" I'm trying to get the list of all employees belonging to one company. I want to display this list in the django admin. My guess was to go with employees = models.ManyToManyField(User, blank=True). But it does not work because I have the following message: employees = models.ManyToManyField(User, blank=True) … -
Django template, send two arguments to template tag and return safe html value?
Is there a way to pass 2 arguments through django template tag and get a safe html value? -
Django: How to clean data when list_editable in admin page?
I have a model which has a field 'keywords'. When I use a form to create/modify records, I am able to clean this field and then save it. class ILProjectForm(forms.ModelForm): class Meta: models = ILProject fields = '__all__' def clean_keywords(self): k = self.cleaned_data.get('keywords') if k: k = ','.join([a.strip() for a in re.sub('\\s+', ' ', k).strip().split(',')]) return k However, I am not sure how to run clean() to update the data when I am using the list_editable option in the admin page. I tried something like this bit I get an error saying I cannot set an attribute. What is the correct way to update the data after it has been cleaned? class MyAdminFormSet(BaseModelFormSet): def clean(self): print(type(self.cleaned_data)) recs = [] for r in self.cleaned_data: if r['keywords']: r['keywords'] = ','.join([a.strip() for a in re.sub('\\s+', ' ', r['keywords']).strip().split(',')]) print(r['keywords']) recs.append(r) self.cleaned_data = recs <-- this part is problematic. class ILProjectAdmin(...) ... def get_changelist_formset(self, request, **kwargs): kwargs['formset'] = MyAdminFormSet return super().get_changelist_formset(request, **kwargs) -
Django Heroku collectstatic --noinput Not uploading all assets to S3 Bucket
I have a Django project I am deploying to Heroku. I am using AWS S3 to store and serve static assets. In my project assets folder, I have these folders and files: However, when python manage.py collectstatic --noinput gets run, only two folders (admin and rest_framework) and all other files are being copied to s3 (see screenshot below in s3) Can someone point out what could be the issue? Here are my settings.py STATIC_URL = config('AWS_URL') + '/staticfiles/' MEDIA_URL = config('AWS_URL') + '/media/' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3StaticStorage' AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY', 'default') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_KEY', 'default') AWS_STORAGE_BUCKET_NAME = config('AWS_S3_BUCKET') AWS_S3_BUCKET_CNAME = config('AWS_S3_BUCKET_CNAME') AWS_URL = config('AWS_URL') AWS_PRELOAD_METADATA = True AWS_DEFAULT_ACL = config('AWS_DEFAULT_ACL', 'public-read') AWS_S3_REGION_NAME = config('AWS_S3_REGION_NAME', 'eu-west-2') AWS_S3_SIGNATURE_VERSION = config('AWS_S3_SIGNATURE_VERSION', 's3v4') -
Gunicorn - [CRITICAL] WORKER TIMEOUT when hitting HttpResponseredirect view
I am building an api with Django Rest framework , Below is my view class UrlRedirectView(RetrieveAPIView): queryset = AwsConsoleAccess.objects.all() def get(self, request, *args, **kwargs): request_id = self.kwargs['request_id'] redirect_id = self.kwargs['redirect_id'] aws_console_access = get_object_or_404(AwsConsoleAccess,request_id=request_id, redirect_id=redirect_id) aws_console_access.increment_access_count() # Increment the click event for each clicks aws_console_access.save() return HttpResponseRedirect(redirect_to=aws_console_access.federated_link_url) I am running the app with gunicorn gunicorn chilli.wsgi gunicorn chilli.wsgi -t 0 Using above two commands it gives me the following error 2022-04-19 21:31:45 +0100] [6168] [INFO] Starting gunicorn 20.1.0 [2022-04-19 21:31:45 +0100] [6168] [INFO] Listening at: http://127.0.0.1:8000 (6168) [2022-04-19 21:31:45 +0100] [6168] [INFO] Using worker: sync [2022-04-19 21:31:45 +0100] [6169] [INFO] Booting worker with pid: 6169 [2022-04-19 21:33:19 +0100] [6168] [CRITICAL] WORKER TIMEOUT (pid:6169) [2022-04-19 20:33:19 +0000] [6169] [INFO] Worker exiting (pid: 6169) [2022-04-19 21:33:19 +0100] [6204] [INFO] Booting worker with pid: 6204 This issue happens only when I hit this endpoint all the other endpoint works fine.