Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
gunicorn active: failed, why don`t active gunicorn service?
i hav ubuntu server 20.04 and a django project i set /etc/systemd/system/gunicorn.socket Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target and /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=sammy Group=www-data WorkingDirectory=/home/sammy/myprojectdir ExecStart=/home/sammy/myprojectdir/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ myproject.wsgi:application [Install] WantedBy=multi-user.target and i have this error gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Wed 2022-03-16 11:49:31 +0330; 12min ago TriggeredBy: ● gunicorn.socket Process: 1891 ExecStart=/home/sammy/myprojectdir/myprojectenv/bin/gunicorn --access-logfile - --workers 3 --bi> Main PID: 1891 (code=exited, status=217/USER) Mar 16 11:49:31 srv174847 systemd[1]: Started gunicorn daemon. Mar 16 11:49:31 srv174847 systemd[1891]: gunicorn.service: Failed to determine user credentials: No such process:: Failed to determine user credentials: No such process Mar 16 11:49:31 srv174847 systemd[1891]: gunicorn.service: Failed at step USER spawning /home/sammy/myprojectdir/myprojectenv/bin/gunicorn: No such process Mar 16 11:49:31 srv174847 systemd[1]: gunicorn.service: Main process exited, code=exited, status=217/USER Mar 16 11:49:31 srv174847 systemd[1]: gunicorn.service: Failed with result 'exit-code'. please help me -
how to get the number of row in a csv file in django
How can i solve? how can i get the count of no. of rows in a csv file using django.how can i solve this issue. while wrote code below its not working it showing the no.of. columns not row. Here my view def upload_csv(request): template = "upload_csv.html" if request.method == "GET": return render(request,template) csv_file=request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.info(request,'* This is not a csv file') return render(request,template) data_set = csv_file.read().decode('UTF-8') data =io.StringIO(data_set) next(data) for row in csv.reader(data,delimiter=',',): Company.objects.get_or_create( name = row[0], hr_name =row[1], hr_email=row[2], hr_verified=row[3], user_id=row[4], primary_phone=row[5], comments=row[6], ) context={} file_name = request.FILES['file'].name count = len(list(row)) company =UploadCsv( file_name=file_name, no_of_row =count, user = request.user ) company.save() return render(request, template,context) -
Can't Install xmlsec for Mac
I'm new to django. i am tring to implement python3-saml which requires Xmlsec. i am trying to install it Using "pip install xmlsec" on my virtal environment. but throwing this error. Collecting xmlsec Using cached xmlsec-1.3.12.tar.gz (64 kB) Installing build dependencies ... done Getting requirements to build wheel ... done Installing backend dependencies ... done Preparing metadata (pyproject.toml) ... done Requirement already satisfied: lxml>=3.8 in /opt/anaconda3/envs/conda_saml_env/lib/python3.10/site-packages (from xmlsec) (4.8.0) Building wheels for collected packages: xmlsec Building wheel for xmlsec (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for xmlsec (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [14 lines of output] running bdist_wheel running build running build_py package init file 'src/xmlsec/__init__.py' not found (or not a regular file) creating build creating build/lib.macosx-10.9-x86_64-3.10 creating build/lib.macosx-10.9-x86_64-3.10/xmlsec copying src/xmlsec/py.typed -> build/lib.macosx-10.9-x86_64-3.10/xmlsec copying src/xmlsec/tree.pyi -> build/lib.macosx-10.9-x86_64-3.10/xmlsec copying src/xmlsec/__init__.pyi -> build/lib.macosx-10.9-x86_64-3.10/xmlsec copying src/xmlsec/constants.pyi -> build/lib.macosx-10.9-x86_64-3.10/xmlsec copying src/xmlsec/template.pyi -> build/lib.macosx-10.9-x86_64-3.10/xmlsec running build_ext error: xmlsec1 is not installed or not in path. [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for xmlsec Failed to build xmlsec ERROR: Could not build wheels for xmlsec, which is required to install pyproject.toml-based projects I … -
How to get foreign key detailed values based on id in html template in django
In Models.py class Interview(models.Model): Current_Date = models.DateField(auto_now_add=True ) User = models.ForeignKey(User,on_delete=models.CASCADE) Recuirement = models.ForeignKey(Client_Requirement,on_delete=models.CASCADE) Candidate = models.ForeignKey(Candidate, on_delete=models.CASCADE) Interviewer = models.ForeignKey(Interviewer, on_delete=models.CASCADE) Interview_Mode = models.ForeignKey(Interview_Mode, on_delete=models.CASCADE) Date = models.DateField() Time = models.TimeField() Interview_status = models.ForeignKey(Interview_status, on_delete=models.CASCADE) Interview_Location = models.CharField(max_length=30) Comments = models.TextField(max_length=1000) Update_Date = models.DateTimeField(auto_now=True) def __str__(self): return str(self.Interviewer) in Views.py def BD(request): Interview_data = Interview.objects.all() context={'Interview_data':Interview_data} return render(request,'Sub/BD.html', context) How i can get all the data individual details of Recuirement, Candidate table In for loop tag in django -
Html - Create dropdown menu from logged in user's account
I would like to create a dropdown menu from the logged-in user account. Something like this: The dropdown menu can contain two options (MyOrder and Logout). Please do not provide the external stylesheet as it will mess up my current page. CSS <style> * { box-sizing: border-box; } body { margin: 0; } .nav { overflow: hidden; background-color: #939596; //background-color: #454545; //background-color: #808080; } .nav a { float: left; display: block; color: #ffffff; text-align: center; padding: 5px 16px; text-decoration: none; font-size: 18px; } .nav span { float: left; display: block; color: #ffffff; text-align: center; //padding: 45px 16px; padding-top: 40px; padding-right: 16px; padding-bottom: 20px; //padding-left: 80px; text-decoration: none; font-size: 13px; } .nav h1, .nav h1 a, .nav h1 a:visited, .nav h1 a:active { color: #ffffff; font-size: 25pt; text-decoration: none; } .nav a:hover { background-color: #eeeeee; color: #000000; } .nav a.active { background-color: #0e002b; color: #ffffff; } .nav .login-container { float: right; } .nav input[type=text], .nav input[type=password] { padding: 6px; margin-top: 8px; font-size: 17px; border: none; width: 120px; } .nav .login-container button { float: right; padding: 6px 10px; margin-top: 33px; margin-right: 16px; background-color: #1c87c9; color: white; font-size: 17px; border: none; cursor: pointer; } .nav .login-container button:hover { background-color: #0e002b; } @media screen … -
Delete all objects from model on specific value using button django
Please see screen shot of table for context: I'm trying to delete the table row using the corresponding Delete Asset button (i.e. delete all rows in a django model with Symbol: 1INCHUP) How I am mapping this out would be the Delete Asset button would send the corresponding Symbol to the following view: View FYI - this View is creating the table but I'm trying to get the delete button working here # CryptoAssets is a model def get_asset_price(request, symbol): sym = CryptoAssets.objects.filter(user_id=request.user.id).values('symbol') obj = sym.annotate(total_units=Sum('units'),total_cost=Sum('cost')).order_by('symbol') cp = [CryptoPrices.objects.filter(ticker=s['symbol']).values('current_price').order_by('ticker')[0] for s in sym] for i, o in enumerate(obj): o.update({'purchase_price': round(o['total_cost']/o['total_units'], 5)}) o.update({'current_price': cp[i]['current_price']}) pl = cp[i]['current_price']*o['total_units']-o['total_cost'] o.update({'profit_loss': round(pl, 5)}) o.update({'profit_loss_p': round(pl/o["total_cost"]*100, 2)}) # Delete Asset request if request.METHOD == "POST": asset = CryptoAssets.objects.filter(user_id=request.user.id, symbol=symbol) asset.delete() return redirect('coinprices/my-dashboard.html') context = { 'object': obj, } return render(request, 'coinprices/my-dashboard.html', context) HTML {% for row in object %} <tr> <td style="text-align:center">{{ row.symbol }}</td> <td style="text-align:center">{{ row.total_units }}</td> <td style="text-align:center"><span class="prefix">${{ row.total_cost }}</span></td> <td style="text-align:center"><span class="prefix">${{ row.purchase_price }}</span></td> <td style="text-align:center"><span class="prefix">${{ row.current_price }}</span></td> <td style="text-align:center"><span class="prefix">${{ row.profit_loss }}</span></td> <td style="text-align:center"><span class="suffix">{{ row.profit_loss_p }}%</span></td> <td style="background-color:white; border: 1px solid white;"> <form action="." method="POST">{% csrf_token %} <button href="{% url 'dashboard' row.symbol %}" class="btn btn-outline-danger btn-sm">Delete Asset</button> </form> … -
Django API calls on SSO enabled service now
the requirement is to fetch the incident details based on incident number from service now which is SSO enabled. Currently we are trying to fetch the incident details of service now from a Django application by django APIs but it is saying authentication failed because service now is SSO enabled. I am passing URL with username and password as below r = requests.get('https://my.website.com/rest/path', auth=('myusername', 'mybasicpass')) and its saying not valid. The service now API is being called from the same server. -
Am a newbie in django, am trying to count number of app registration request but result does not display on the template?
below is my code that i was trying to implement the task my views.py this is my view for counting the request def appSummary_view(request): context = {} user = request.user applications = ApplicationRequest.objects.all().filter(developer=user) total_request = applications.count() registered_app = applications.filter(status=1).count() pending_app = applications.filter(status=0).count() context = {'total_request':total_request, 'registered_app':registered_app, 'pending_app':pending_app} print(applications) return render(request, 'dashboard.html', context) #my models this is my model for app request class ApplicationRequest(models.Model): id = models.BigAutoField(primary_key=True) developer = models.ForeignKey( settings.AUTH_USER_MODEL, related_name="%(app_label)s_%(class)s", null=True, blank=True, on_delete=models.CASCADE, ) name_of_app = models.CharField(max_length=255, blank=True,null=True) domain = models.CharField(max_length=100, unique=True,null=True) org_name = models.CharField(max_length=200,null=True) redirect_uris = models.TextField( blank=True, help_text= ("Allowed URIs list, space separated") ) claim_of_property = models.TextField( blank=False, help_text= ("Proof of property, space separated"),null=True ) date_requested = models.DateTimeField(auto_now_add=True) status = models.IntegerField(default=0) def __str__(self): return self.name_of_app #my forms.py this is my form for registering the applications class RegisterAppForm(forms.ModelForm): name_of_app = forms.CharField(max_length=255, help_text='Required.Please enter the name of your applications') domain = forms.CharField(max_length=100, help_text='Required.Please enter the domain for your application') org_name = forms.CharField(max_length=200, help_text='Required.Please enter the name of the organization of your application') redirect_uris = forms.CharField(max_length=400,help_text='Required.Please enter redirect uris for your app') claim_of_property = forms.CharField(max_length=400, help_text='Required.Please provide the proof of property') class Meta: model = ApplicationRequest fields = ('name_of_app', 'domain', 'org_name', 'redirect_uris' , 'claim_of_property') template code this is my template … -
how can remove city name and update society name and save it into the database?
So I want to know how can I remove the city name from the society name and update the society name and save it into the database? Below code is taking all the society names that contain the city name. but I want to update all the society's names and save them. qs = Society.objects.all() citys = City.objects.values_list('name', flat=True) clauses = (Q(name__iendswith=name) for name in citys) query = reduce(operator.or_, clauses) data = qs.filter(query) Thanks!! -
Django Grapelli change background column headers
I'm using django grapelli. In my model there is color field which users can select color with colorfield widget. I want to change columns header background color. Does anyone know anything about this? I couldn't found anything. -
Django - How do you handle Two way Bindings
I have the following two models: class Step(models.Model): start_time = models.TimeField() time = models.IntegerField() schedule = models.ForeignKey(Schedule, on_delete=models.CASCADE) class Schedule(models.Model): identifier = models.CharField(max_length=10) name = models.CharField(max_length=100) steps = models.ManyToManyField('manager.Step', related_name='steps') However when editing the Schedule and adding steps via admin the Step does not update its schedule? How do you handle two way binding like this in Django? -
Get rid of   in ckeditor Django
How I can get rid of &nbsp appearing on templates, when using django-ckeditor, I tried with 'entities_additional': '' in settings as follows but still it is visible when using quotes or double space. CKEDITOR_CONFIGS = { 'default': { 'toolbar': [["Format", "Bold", "Italic", "Underline", "Strike", "SpellChecker"], ['NumberedList', 'BulletedList', "Indent", "Outdent", 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ["Image", "Table", "Link", "Unlink", "Anchor", "SectionLink", "Subscript", "Superscript"], ['Undo', 'Redo'], ["Source"], ["Maximize"]], 'height': 250, 'width': '100%', 'entities_additional': '' }, } -
why if i call the fields of the form one by one and i have action on the button reliant to this form there was no result displayed on Django
i want to use a form but what i want is calling the fields of the form one by one on the Html template and then if i click on a button "there was some calculation results will be displayed" , after much tries I have found that if i call the all the form in the html template using: <form action="{% url 'areas' %}" method="post" id="maincont" novalidate> {% csrf_token %} {{ form }} <button id="reslink" >Result</button> </form> --------> It works fine and show me the result values what i want to do call the fields of the form one by one on the html <form action="{% url 'areas' %}" method="post" id="maincont" novalidate> {% csrf_token %} <p>{{ form.domestic_residential}} Domestic and residential areas ml</p> <p>{{ form.office_area}} Office areas ml</p> <input id="submit" type="button" value="Click"/> <p >{{ resultat }}</p> </form> --------> It doesn't show any result. Any help will be appreciated because really i want to do it ( i want to call the fields one by one for things reliant to the design of the page). I want Just to know How i can correct this part of template to make me show some results( or any advices or some one had … -
Django CeleryTask return GeoDataFrames leads to TypeError: Object of type int64 is not JSON serializable
I am trying to build a web app in which I make use of celery to tackle a long running process. I need to pass to the view that called the task a couple of GeoDataFrame and an epsg projection value. return {'Working_area_final': Working_area_final.to_json(), 'PoI_buffer_small': PoI_buffer_small.to_json(), 'Streets_gdf': Streets_gdf.to_json(), 'PoI_buffer_BIG_exp': PoI_buffer_BIG_exp.to_json(), 'projection': str(proj.to_epsg(), 'ip': ip.to_json()} The problem occurs here. I get 'TypeError: Object of type int64 is not JSON serializable'. I can tell that before this command I manage to successfully print to console everything that has to be passed as result. -
distance based ordering in django
So i am using django and get user's location at registration time. Then i show these users on the front page of the app but sorted as per the distance, i.e, the closest ones to the logged in user are on the top and so on. Now what i am doing is i am ordering them as per distance on the backend using some annotate (etc) functions provided by django ORM. sortedQueryset = self.get_queryset().annotate(distance=Distance( 'coords', user.coords, spheroid=True)).order_by('distance') Where 'coords' is the column in db to store the point (location), user.coords is point (coordinates) of the logged in user. Now to get only first 100 users (say) from the database i can do something like this; sortedQueryset = self.get_queryset().annotate(distance=Distance( 'coords', user.coords, spheroid=True)).order_by('distance')[:100] But what it think, it still grabs all the rows, orders them as per distance and then gets 100 of them. Say we have a million users in db, then it always has to get all those and then sort them and then get only 100. I think it is a lot of overwork (maybe i am wrong or maybe this is the only way as i have to sort as per distance and that also depends on the … -
how to implement automatically send email when MySQL column get updated (django+MySql)
I have models like Id, Name, email, Status. And created serializers and views. I am updating the Status values by PUT method. How to implement an automatic email notification to smtp.example.com with the changed Status value. Ex: Status column value is 'abc' I am updating value 'abc' to 'xyz' using PUT. I want an email should automatically send to particular email-id belongs to that row using primary key Id. -
Pass request URL parameter into create view
I am hoping this is a simple tweak. I've been reading through various threads here but I am missing a very basic step -- how do I grab the argument from the URL request? For instance, the URL is http://127.0.0.1:8000/registration/student/item/create/8 URL definition is path('student/item/create/<int:pk>',views.CreateStudentBehaviorItem.as_view(),name='student_item_create'), My class view is as follows: class CreateStudentBehaviorItem(LoginRequiredMixin, generic.CreateView): model = StudentItem form_class = StudentItemForm success_url = reverse_lazy('registration:student_item_list') def get_form_kwargs(self): kwargs = super(CreateStudentBehaviorItem, self).get_form_kwargs() kwargs['pk'] = self.request.GET.get('pk') return kwargs The form is: class StudentItemForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.course = kwargs.pop('pk', 'all') super().__init__(*args, **kwargs) # Begin filtering by course ID class Meta: model = StudentItem fields = ("item_student","behavior_category","behavior_item","response","internal_comments") widgets = { 'item_student': forms.Select(attrs={'class': 'form-control'}), 'behavior_category': forms.Select(attrs={'class': 'form-control'}), 'behavior_item': forms.Select(attrs={'class': 'form-control'}), 'response': forms.Select(attrs={'class': 'form-control'}), 'internal_comments': forms.Textarea(attrs={'class': 'form-control', 'rows':5}), } I haven't even gotten to the point to filter because I can't seem to get the PK from the request URL. My minimal Django experience is with get_context_data to grab request URL details. I hope this is a simple correction to grab the value. I appreciate it. -
Django deployment on Heroku failed due to "ModuleNotFoundError at / No module named '_tkinter'"
I'm trying to deploy my Django app to Heroku and this error faced me on deployment I'm not using tkinter anywhere on my app of course and the stack trace does not point to my app the app is running with no issues locally -
ProgrammingError at /admin/patients/appointment/ column patients_appointment.date does not exist
I am facing the above error, even though the "date" column is there in the model. class Appointment(models.Model): name=models.ForeignKey(Patient, on_delete=CASCADE) doctor=models.ForeignKey(DoctorDetail, on_delete=CASCADE) start_time=models.TimeField() end_time=models.TimeField() date=models.DateField() def __str__(self): return self.name.name This was the error I was facing: -
Django Multiple Databases for Different Users
I'm wondering if it's possible to use multiple databases for different users in the same app? I've read about the multiple database documents and searched a lot online but could'nt found any tutorial for it. Is there any way to use different databases for different users in the same app ? -
Django with Postgres - Unique Constraint for One Tenant in Multitenant Database
I've been reading and reading and reading, but finally decided to shortlist my questions regarding multitenant Postgres with Django. I'm quite new with using Django, so please bear with me. We are developing a multitenant business platform with more than 300 tables. For tenants' ids, we have chosen UUID4, so there are my questions coming: Is it enough to use UUID4 for tenants' and users' ids only and then reference them as foreign keys in every other table? If not, Is there a need to use UUID4 in every table? That means that pk in each table will be UUID and that table will have all foreign keys as UUID4s as well.... The second solution would be the UUID4 for tenants' and users' pks only. Other tables would have bigint pks and only 2 foreign keys as UUID (tenant & user). In some tables, we need to have other unique data than just pk (such as names, document numbers, tax data and so on). Is there a way to determine/check the uniqueness of such data in a tenant dataset by db constraint or should that be solved by code? The data volume and number of tenants and users are in … -
How to get ids of the objects from django model?
How to get ids of the objects from the model. qs = Society.objects.all() cityID = City.objects.get(pk=1) The above query will return only one object whose id is 1. but I need all cities id so that can I access the city's names from id as you can see in below code. for s in qs: ... s_name = qs.filter(name__iendswith=cityID.name) ... break -
Live Recording -- saving to google cloud storage -- is it possible
i am wondering is there any possibility of uplaoding the live stream or recording to the google storage frame by frame with audio and video, aws is having the live recording storage options but i am not finding any good resources with the google cloud storage. is there any one out there who can help me with this problem? Thanks in advance. -
Django ajax url not reading
I have an ajax file which calls the url from the urls.py which gets the json data from the views.py but when I run the server it just shows Not Found:/dept-json/ I did manage to get it to work using the django snippet {% url 'accounts:dept-json'%} However I do not want this since I need to get and pass the variable from the dept-json data to another ajax url which is: url:`/prog-data/${selectedDept}/` I have read here that you can't pass variables in ajax like {% url 'accounts:prog-json' department%} how do I manage to do this? here is my code: main.js $.ajax({ type: 'GET', url: "/dept-json/", // url: "{% url 'accounts:dept-json'%}", success: function(response){ console.log(response) }, error: function(error){ console.log(error) } }) urls.py path('dept-json/', get_json_dept_data, name='dept-json'), path('prog-json/<str:department>/', get_json_prog_data, name='prog-json'), views.py def get_json_dept_data(request): qs_val = list(Department.objects.values()) return JsonResponse({'data':qs_val}) def get_json_prog_data(request, *args, **kwargs): selected_department = kwargs.get('department') obj_prog = list(Program.objects.filter(department__name=selected_department).values()) return JsonResponse({'data':obj_prog}) -
I already have a form created in HTML, how can I post the data from this form to the user's account on the Django database?
I am working on the project in which one user can create a quiz on the HTML pages without coding, in an interactive way. This created quiz should be displayed on the screen of another user, who will be attempting the tests. I am using Django framework for backend and I am very new to backend.