Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Hi My problem is with the terminal VS app
PS E:\learning\project\django\env\scripts> activate activate : The term 'activate' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 activate + CategoryInfo : ObjectNotFound: (activate:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException -
Can we blindly trust Django ERROR "you may need to add xxx to ALLOWED_HOSTS"?
Regularly I receive from my server these kind of errors: Invalid HTTP_HOST header: '139.162.113.11'. You may need to add '139.162.113.11' to ALLOWED_HOSTS. The problem is that my server works fine and I don't know where do these IP addresses are comming from. If I try to localize the one in example, it appears to be in Tokyo, which is weird to me, having a server based in France for mainly european customers. Can it be a suspicious attempt to the server security? I'm not keen to allow this IP. What is the correct attitude toward this kind of error. -
Do we need to use runserver command in production to start our django project?
Do we need to use runserver command in production to start our project? If yes, then how to do it, and If No then how does out project server starts? -
How to add model with multiple services and prices for them in Python/Django
I've just started learning Python/Django and I have a question for you guys:) I want to create a model in Django that will allow me to create a service with prices for each user. For example, Users can open a form that will allow them to put there their services, and prices for each services. But I don't know how to create an appropriate model. Please help. -
getting error while parsing json ein django using SSE
Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data I am sending implement SSE using js , but some of my js code is throwing errors on JSON.parse wonder where I am going wrong about this def somefunc(): face_attributes = { "quality_issue": False, <----------- this is what I am sending to client "more_faces": False, "no_face": False, "face_absence": False } for face in faces: x1, y1 = face.left(), face.top() x2, y2 = face.right(), face.bottom() imgOriginal = cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2) moreFaceCount = 0 noFaceCount = 0 # cv2.imshow('frame', imgOriginal) if cv2.waitKey(1) & 0xFF == ord('q'): break time.sleep(3) yield "\ndata: {}\n\n".format([face_attributes]) error spot eventSource.onmessage = function(e) { console.log(e) final_data = e console.log(JSON.parse(final_data)) $('.toast').toast('show') } -
many2many to same model but not itself and not multiple times
hej! I have a model referring to the same model via "self", this does work in general but I want that it is not connected with 'itself'. So let's say topic1 can not be connected to topic1 (which wouldn't make any sense) and I don't want it to be possible to connect topic1 multiple times to topic2. It should just be once topic1-topic2 in the data base. # views.py related_topic = models.ManyToManyField( "self", # TODO: constraint in m2m! not with itself, not in both directions. verbose_name="Related Topic", blank=True, related_name="related_topic" ) I found symmetric=False to not have the connection in both directions which is helpfull but not enough. Does anyone knows how to achieve that? Many thanks! -
How to clear the table by signal in django?
I have the following temporary model: from django.db import models class TempModel(models.Model): backup = False operation_type = models.CharField(max_length=128, verbose_name='operation type') device_type = models.BigIntegerField(verbose_name='device type') operation_datetime = models.DateTimeField(verbose_name='date and time of the payment') transaction_sum = models.DecimalField(max_digits=12, decimal_places=2, verbose_name='sum of transactions') ... file = models.ForeignKey(to='core.RegistryFile', on_delete=models.CASCADE) reg_date = models.DateField(verbose_name='Date of register') operday = models.ForeignKey(to='OperDay', on_delete=models.SET_NULL, null=True) class Meta: app_label = 'core' I'd like to populate it with the temp data we need to compare with our internal table and truncate all the contents AFTER we use it every time we run the comparison. What Django signal can I use to trigger data removal after every comparison? How may it look like? -
Python Ternary Operations
I have the following code: from django_app.models import Model def func_name(): name = "name" if Model.objects.filter(name=name).count() > 1: raise ValidationError("This name already exists.") else: return name Now I want to turn it into a one-liner. This is what I did: from django_app.models import Model def func_name(): name = "name" raise ValidationError("This name already exists") if Model.objects.filter(name=name).count() > 1 else return name But this gives me a syntax error. Is such an implementation possible in Python? -
In CreateWithInlinesView save all 7 extra forms from database value as default (formset) Django
How to save all 7 extra forms which all of their's value are default? this inline formset class CompanySchedulePerDaysgraphInlineFormSetFactory(InlineFormSetFactory): model = models.CompanySchedulePerDaysgraph exclude = ('is_work_day',) form_class = CompanySchedulePerDaysgraphModelForm factory_kwargs = { 'can_delete': False, 'widgets': {'is_work_day': forms.CheckboxInput(attrs={'class': 'form-control'}), 'start_work': forms.TimeInput(attrs={'class': 'form-control', 'type': 'time'}), 'end_work': forms.TimeInput(attrs={'class': 'form-control', 'type': 'time'}), }, 'extra': 7 } *view.py* class CompanyScheduleCreateView(LoginRequiredMixin, CreateWithInlinesView): model = models.CompanyScheduleFreeGraph inlines = [forms.CompanySchedulePerDaysgraphInlineFormSetFactory] form_class = forms.CompanyScheduleFreeModelForm template_name = 'backoffice/pages/company-schedule/create.html' success_url = reverse_lazy('company_schedule') def forms_valid(self, form, inlines): response = self.form_valid(form) for formset in inlines: formset.instance = self.object formset.save() return response def form_valid(self, form): self.company = form.save(commit=False) self.company.company = self.request.user.company self.company.save() return super().form_valid(form) models.py class CompanySchedulePerDaysgraph(models.Model): import datetime days_graph = models.ForeignKey(CompanyScheduleFreeGraph, on_delete=models.CASCADE) is_work_day = models.BooleanField(default=True) start_work = models.TimeField(default=datetime.time(9, 00)) end_work = models.TimeField(default=datetime.time(18, 00)) created_at = models.DateTimeField(auto_now_add=True) -
How to filter list with Remaining days of date of birth in Django
I want to display an upcoming birthday list with the remaining days of 30 days. Example: Name Date Of Birth Remaining Days John Die 2050-10-25 4 Days Left John Snow 2050-10-26 5 Days Left I dont know how to calculate remaining days but i try this code but i got error "can't subtract offset-naive and offset-aware datetimes" customer=Customer.objects.filter()[:10] for i in customer: remaining = i.dateOfBirth - datetime.today() print(remaining) -
Django JQuery Autocomplete for two forms on one page
Found this autocomplete code on the web, but it works for one form on the page. How to make it work for two forms with different data for each one? views.py from django.http import JsonResponse from django.shortcuts import render # Create your views here. from core.models import Product def autocomplete(request): if 'term' in request.GET: qs = Product.objects.filter(title__icontains=request.GET.get('term')) titles = list() for product in qs: titles.append(product.title) return JsonResponse(titles, safe=False) return render(request, 'core/home.html') models.py class Product(models.Model): title = models.CharField(max_length=124) qty = models.IntegerField() def __str__(self): return self.title home.html <form> <label for="product">Product</label> <input type="text" name="product" id="product"> </form> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $(function () { $("#product").autocomplete({ source: '{% url 'autocomplete' %}', minLength: 2 }); }); </script> urls.py urlpatterns = [ path('', views.autocomplete, name='autocomplete'), ] -
django Create lazy queryset method
I want to create lazy method in QuerySet class: I want from this method to make extra filtering accordings to fileds in the querysets: class CustomQuerySet(Queryset): def extra_filter(self): fields = self._fields: lookup =getattr(self._query,"_lookup_joins",[]) #processing and return the custom queryset when I user the extra_filter before django filter then the the values of fields and lookups is empty. MyModel.objecs.extra_filter().filter(....) # doesn't workd the values of "fields" and "lookup" is empty MyModel.objects.filter(...).extra_filter() # it work So, how to extra_filter lazy to excute in all cases? -
Docker : Alpine : Django - Error installing python mysqlclient library
I am building an Alpine based image of a Django application to connect with a MySQL db. For connecting with the database, I am using mysqlclient. For building the image, I am using docker-compose. When I do docker-compose build I get the respective error: #15 7.366 Downloading mysqlclient-1.3.0.tar.gz (76 kB) #15 7.403 Preparing metadata (setup.py): started #15 7.545 Preparing metadata (setup.py): finished with status 'error' #15 7.545 ERROR: Command errored out with exit status 1: #15 7.545 command: /usr/local/bin/python -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-3fyj3dl9/mysqlclient_4a600f29b1334b47a39251a3f24d8315/setup.py'"'"'; __file__='"'"'/tmp/pip-install-3fyj3dl9/mysqlclient_4a600f29b1334b47a39251a3f24d8315/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-wh30qihi #15 7.545 cwd: /tmp/pip-install-3fyj3dl9/mysqlclient_4a600f29b1334b47a39251a3f24d8315/ #15 7.545 Complete output (10 lines): #15 7.545 /bin/sh: mysql_config: not found #15 7.545 Traceback (most recent call last): #15 7.545 File "<string>", line 1, in <module> #15 7.545 File "/tmp/pip-install-3fyj3dl9/mysqlclient_4a600f29b1334b47a39251a3f24d8315/setup.py", line 17, in <module> #15 7.545 metadata, options = get_config() #15 7.545 File "/tmp/pip-install-3fyj3dl9/mysqlclient_4a600f29b1334b47a39251a3f24d8315/setup_posix.py", line 47, in get_config #15 7.545 libs = mysql_config("libs_r") #15 7.545 File "/tmp/pip-install-3fyj3dl9/mysqlclient_4a600f29b1334b47a39251a3f24d8315/setup_posix.py", line 29, in mysql_config #15 7.545 raise EnvironmentError("%s not found" % (mysql_config.path,)) #15 7.545 OSError: mysql_config not found #15 7.545 ---------------------------------------- #15 7.545 WARNING: Discarding https://files.pythonhosted.org/packages/6a/91/bdfe808fb5dc99a5f65833b370818161b77ef6d1e19b488e4c146ab615aa/mysqlclient-1.3.0.tar.gz#sha256=06eb5664e3738b283ea2262ee60ed83192e898f019cc7ff251f4d05a564ab3b7 (from https://pypi.org/simple/mysqlclient/). … -
Django - Passing a json or an array in URL for an API call
I want to pass a number off variables (either as a JSON or Array) via an API, such as: {'age': 35, 'gender':'female', ...etc} I am not sure how to pass this information into the Djano URL. I could set up individual parameters in the URL, but I got quite a few to pass. there must be an easier way of doing it -
Django app on Heroku doesnt store users created wth admin panel
I have Django app deployed on Heroku. While building the app I have created only 2 superusers. After deployment on Heroku I can login to admin panel and I can create users, but they are not stored permanently. I see them created and I see them saved. If I log off and login again I can see them. But, after a while, they are removed. If I change the email of the 2nd superuser, It will be changed and saved, but also, after a while, this change is reversed or deleted. I am not sure if this make any sense and I am not sure if this is Django, Heroku or SQLite bug/feature. Any help would be much appreciated. Since I didn`t find similar issue, it is very interesting to me if this is something new or well known issue. -
Django - Remove duplicate from the API end point
I have designed a microservices where I'm getting the JSON from the end point and I'm able to display it in the API but I'm getting the repeated data again and again for each id. im getting json data from localhost:8000 and i want to display it with current localhost:7000.I have done some wrong but couldn't able to find where Im going wrong.I'm stuck here views.py class filterlistView(APIView): def get(self, request): filter_list = Userbase.objects.all() # serializer = UserSerializer(filter_list, many=True) # return Response(serializer.data) return Response([self.formatfilter(filter) for filter in filter_list]) def formatfilter(self, post): table_data= requests.get('http://127.0.0.1:1500/api/').json() # return render(request, 'home.html',{'table_data':table_data}) return { 'id':post.id, 'Payment_Term':post.Payment_Term, 'Netdue_Date':post.Netdue_Date, 'Predicted_Paid_days':post.Predicted_Paid_days, 'PBK_Desc':post.PBK_Desc, 'Vendor_Name':post.Vendor_Name, 'Reference':post.Reference, 'company_code':post.company_code, 'Area':post.Area, 'country':post.country, 'table_data':table_data, } output: { "id": 1, "Payment_Term": "demo2", "Netdue_Date": "2021-10-20", "Predicted_Paid_days": "2021-10-20", "PBK_Desc": "sf", "Vendor_Name": "AB", "Reference": "AB", "company_code": "1074", "Area": "GCR", "country": "CEE", "table_data": [ { "id": 1, "stage": "Stage3 Train/Stage4 Test", "region": "NORTH AMERICA", "area": "US", "country": "US", "VendorName": "FOXLINK INTERNATIONAL INC", "PBK_Desc": "Free for payment" }, { "id": 2, "stage": "Stage3 Train/Stage4 Test", "region": "NORTH AMERICA", "area": "US", "country": "US", "VendorName": "FOXLINK INTERNATIONAL INC", "PBK_Desc": "Free for payment" }, ] }, { "id": 2, "Payment_Term": "3434", "Netdue_Date": "2021-10-20", "Predicted_Paid_days": "34", "PBK_Desc": "sfsd", "Vendor_Name": "fdsdf", "Reference": "sdfsd", "company_code": "1154", … -
Deloying Django app Apach2: 403 Forbidden error. Permission denied: mod_wsgi
I am trying to deploy my Django app with my Digital Ocean droplet. There was a very useful YouTube tutorial that I followed; when he adjusted settings in Apache2, and then refreshes, he sees his Django app, whereas when I do the same, I get the following error: Forbidden You don't have permission to access this resource. Apache/2.4.46 (Ubuntu) Server at 159.223.6.157 Port 80 Here you see the setup of my /etc/apache2/sites-available/hbm_project.conf file: <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn … -
will my postgresql trigger execute even if I set the value from django model at save?
I have created a trigger on each row INSERT/UPDATE to set the created_at and updated_at respectively. Trigger: CREATE OR REPLACE FUNCTION insert_update_function() RETURNS trigger AS $BODY$ BEGIN -- CHECKING OPERATION TYPE AND DECIDE COLUMN IF TG_OP = 'INSERT' THEN NEW.created_at := current_timestamp; ELSE NEW.updated_at := current_timestamp; END IF; RETURN NEW; END; $BODY$ LANGUAGE plpgsql VOLATILE; Apply Trigger only those table where updated_at column exists DO $$ DECLARE t text; BEGIN FOR t IN SELECT table_name FROM information_schema.columns WHERE column_name = 'updated_at' LOOP EXECUTE format('CREATE TRIGGER insert_update_trigger BEFORE INSERT OR UPDATE ON %I FOR EACH ROW EXECUTE PROCEDURE insert_update_function()', t,t); END loop; END; $$ language plpgsql; So when I do INSERT/UPDATE from raw SQL I don't provide these two columns i.e created_at and updated_at, it is automatically trigged and added on my table which is expected and fine but now my query is when I try to INSERT/UPDATE row's of the table through the Django BaseModel where I am setting created_at and updated_at, the trigger will be again called? Django BaseModel with custom save() class AutoCreatedField(models.DateTimeField): """ A DateTimeField that automatically populates itself at object creation. By default, sets editable=False, default=datetime.now. """ def __init__(self, *args, **kwargs): kwargs.setdefault('editable', False) kwargs.setdefault('default', now) super().__init__(*args, … -
Nested annotation in Django View and serializers
I have a use case where I wanted to have data in the below format. { "total_discount_amount": 0, "total_paid": 0, "total_billed": 0, "visits": "string" "users_summary": [ { "id": "string", "date": "string", "total_discount_amount": 0, "total_paid": 0, "total_billed": 0, "visits": "string" } ] } The outer part of the data is the sum of users_summary list data. class Test(generics.ListAPIView): queryset = Model.objects.all() serializer_class = SummarySerializer def list(self, request, *args, **kwargs): data =Model.objects.values('user').annotate(visits=Count('user'),total_discount_amount=Sum('model__amount', total_paid = Sum('model__paid_amnt',total_billed = Sum('model__bill_amnt').filter() return data Here I am not getting the outer values. I tried to implement the serializer in a way that I can get users_summary aggregated data however couldn't achieve it. Any solution to it? -
'NoneType' object has no attribute 'add' (Django nested serializer)
I'm trying to update object but if main_photos_data.get('id', None): MainPhoto.objects.filter(id=main_photos_data.get( 'id')).update(**main_photos_data) else: id = instance.id project = Project.objects.get(id=id) new_main_photo = MainPhoto.objects.create(**main_photos_data) *project.main_photo.add(new_main_photo)* error in this line getting this error: File "/home/askar/work/tasnif-backend/portfolio/serializers.py", line 143, in update project.main_photo.add(new_main_photo) AttributeError: 'NoneType' object has no attribute 'add' I've tried: project.main_photo = new_main_photo But got this error: TypeError at /portfolio/edit-project/1/ Direct assignment to the forward side of a many-to-many set is prohibited. Use photo.set() instead. -
get the user email after deletation django
I was working with the settings.AUTH_USER_MODEL and I want the email of the user to remain( after the user deleted). the user is a foreign key in my model. here is the code class Text(models.Model): title = models.CharField(max_length=45) text = models.TextField() user= models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET(??) ) # TODO : should change( remain email from the deleted user) thanks for your help -
While working with django I am seeing warnings [duplicate]
This is the warning I get when I run and Django commands in the console. WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages) WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages) WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages) WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages) WARNING: Ignoring invalid distribution -ip (c:\python310\lib\site-packages) -
how to remove instruction labels in django-registration-redux registration form
I followed Django-registration-redux start guide and everything works fine but the registration form shows instruction label for username and password which is like in the picture below. I don't want it so how can I remove it? -
Django Search functionality: form returns None
i am trying to build a django search functionality for my app but the input form keeps returning a none views.py def search(request): if request.method == 'POST': query = request.POST.get('text') houses = Product.objects.filter(name__contains='query') context = { 'houses':houses, } return render (request, 'searchresult.html',context ) search.html <form> <input type='text' placeholder='search houses> <button type='submit'>Search</button> </form> -
how to write testcase of not adding a same number in 2 factor auth in django
how to write this testcase in correct way i have tried a lot times but it is failedmany times def test_same_number_add(self): device = self.user.totpdevice_set.create(name='default', key=random_hex()) response = self._post({'phone_setup-current_step': 'setup', 'setup-number': '+918362758326', 'setup-method': 'sms'}) print(response.content) self.assertContains(response, 'Token:',status_code=200) p = PhoneDevice(number="+918770109512", user=self.user) p.save() response = self._post({'token-otp_token': totp(device.bin_key), 'phone_setup-current_step': 'token'}) response = self._post({'phone_setup-current_step': 'setup', 'setup-number': '+918274610917', 'setup-method': 'sms'}) #print(response.status_code) print(response.content) self.assertContains(response, 'Same number cannot be added twice',status_code=200)