Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - update individual fields of a model
Im working on a django project and I have a user model and each user has a UserProfile. I want to implement a form so that a user can update his profile picture. This is what I have so far: views.py def update_image(request,username): response_data = {} if request.method == 'POST': image = request.POST.get('image') response_data['image'] = image UserProfile.objects.create( image = image ) return JsonResponse(response_data) context = { 'image':image } return render(request, 'userprofile.html', context) forms.py class ProfileUpdateForm(forms.Form): image = forms.ImageField(required=False,label='image') def clean(self): blocked_chars = set(punctuation) cleaned_data = super(ProfileUpdateForm, self).clean() image = cleaned_data.get('image') filename, file_extension = os.path.splitext(image) if not ".jpg" or '.png' in file_extension: raise forms.ValidationError(filename + 'is not an image') return image urls.py url(r'^(?P<username>[\w-]+)/update-image/$', update_image, name='update_image'), index.html <form id="profile_form" class="profile_form" method='POST' enctype="multipart/form-data" form_data="{{ request.user.profile.get_update_image_url }}"> {% csrf_token %} <div class="profile_form_group"> <div class="profile_table"> <div class="utable_row"> <div class="utable_th_1"> <span class="user_detail"> {{ form }}</span> </div> <div class="utable_th_2"> <span class="user_detail"> <input class='profile_img_btn' type="submit" value="Update Image"/> </span> </div> </div> </div> </div> </form> main.js var i_link = $('.profile_form').attr('form_data'); console.log(i_link) $(document).on('submit', '#profile_form',function(e){ e.preventDefault(); $.ajax({ type: 'POST', url: i_link, data:{ image :$('#id_image').val(), csrfmiddlewaretoken :$('input[name=csrfmiddlewaretoken]').val(), action : 'post' }, success:function(json,data,i_link){ console.log("HEY, THIS IS WORKING !" + data + i_link) document.getElementById("profile_form").reset(); }, error : function(xhr,errmsg,err) { console.log("HEY, THIS IS NOT WORKING !") … -
connect() failed (111: Connection refused) while connecting to upstream || NGINX to Gunicorn
My nginx's default.conf file : server { listen 8000; location / { proxy_pass http://127.0.0.1:8001; } location /static/ { autoindex on; alias /root/gunicorn/webserver/static/; } } And, the port it is routing to : root@ip-X.X.X.X:~/gunicorn/webserver# docker run -it -p 8001:8001 guncorn_new [2020-02-24 16:24:35 +0000] [6] [INFO] Starting gunicorn 19.10.0 [2020-02-24 16:24:35 +0000] [6] [INFO] Listening at: http://0.0.0.0:8001 (6) [2020-02-24 16:24:35 +0000] [6] [INFO] Using worker: sync [2020-02-24 16:24:35 +0000] [9] [INFO] Booting worker with pid: 9 NOTE: 127.0.0.1:8001 (gunicorn) is accessible when manually opened via browser. But not via NGINX. AND all this works when I EXPLICITLY mention the public IP of my server instead of '127.0.0.1' in the default.conf file. # For DevOps nerds # FROM nginx EXPOSE 8000 EXPOSE 80 COPY ./default.conf /etc/nginx/conf.d/default.conf # ERROR MESSAGE # root@ip-172-31-90-249:~/gunicorn/nginx# docker run -it -p 80:80 nginx_new 2020/02/24 16:22:39 [error] 6#6: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 45.248.29.38, server: localhost, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8001/", host: "54.85.138.232" -
How to work with django SlugField and slugify?And How to use it properly?
I google about how to use slug and already watched some videos.But I am confused how does this work. Help me by Giving Some Example or Any Resources. It will be be very helpful for me. Thanks Good People. -
IntegrityError at /personal_detail/
I got this error as I was getting MultiValueKeyDictError I used POST.get but than I got this error IntegrityError at /personal_detail/ NOT NULL constraint failed: users_personal_detail.beneficiary_adhaar_name Request Method: POST Request URL: http://127.0.0.1:8000/personal_detail/ Django Version: 3.0.3 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: users_personal_detail.beneficiary_adhaar_name Exception Location: C:\Python\Python38\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 396 Python Executable: C:\Python\Python38\python.exe Python Version: 3.8.1 Python Path: ['C:\\pradhan-mantri-matru-vandana-yojana\\pmmvy', 'C:\\Python\\Python38\\python38.zip', 'C:\\Python\\Python38\\DLLs', 'C:\\Python\\Python38\\lib', 'C:\\Python\\Python38', 'C:\\Users\\diwas\\AppData\\Roaming\\Python\\Python38\\site-packages', 'C:\\Python\\Python38\\lib\\site-packages'] My views.py looks like this,I used 'get' to avoid getting MultiValueKeyDictError def ApplyOnline(request): return render(request,'users/applyonline.html') @login_required def personal_detail(request): # ShowHideExample = request.POST.get('showHideExample',False) beneficiary_adhaar_name=request.POST.get('beneficiary_adhaar_name') adhaarno=request.POST.get('adhaarno') # adhaarcopy =request.POST['adhaarcopy'] idcard=request.POST.get('idcard') adhaar_eid=request.POST.get('eid') beneficiary_id_name=request.POST.get('beneficiary_id_name') idno=request.POST.get('idno') # idcopy=request.POST['idcopy'] apply_online = Personal_Detail(beneficiary_adhaar_name=beneficiary_adhaar_name,adhaarno=adhaarno, idcard=idcard,adhaar_eid=adhaar_eid,beneficiary_id_name=beneficiary_id_name,idno=idno) apply_online.save() return render(request,'users/applyonline.html') models.py (I tried using like idno=request.POST.get('idno',null=True) but it doesn't work) class Personal_Detail(models.Model): beneficiary_adhaar_name=models.CharField(max_length=30) adhaarno=models.IntegerField() adhaarcopy = models.ImageField(upload_to='adhaar/') idcard=models.TextField() adhaar_eid=models.IntegerField() beneficiary_id_name=models.CharField(max_length=30) idno=models.IntegerField() idcopy=models.ImageField(upload_to='identitycard/') def __str__(self): return self.beneficiary_adhaar_name + self.beneficiary_id_name I tried using nulll=False in my views like idcard=request.POST.get('idcard',null=True) but I again got error that get cannot associate with null or something like that. -
How ao apply custom filter to a django filters ModelChoicefilter
I'm using Django Filter to filter data in my Django project. Now I need to filter some specific ModelChoiceFilter based on the current logged in user. I've tried sending data using def _init_ to the form and then execute the filtering using self.fields['field_name'].queryset = my_qs, but it gives me unresolved error for self.filters. Finally, I've used the Filter.Method options from Django Filter, here is my code: views.py f = RequestsFilter(request.GET, queryset=LeaveRequest.objects.filter(user=request.user),user=request.user.id) forms.py class RequestsFilter(django_filters.FilterSet): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super().__init__(*args, **kwargs) start_date = DateFilter(field_name='date_time', lookup_expr='gt', widget=forms.TextInput(attrs={'type': 'date'})) end_date = DateFilter(field_name='date_time', lookup_expr='lt', widget=forms.TextInput(attrs={'type': 'date'})) employee = django_filters.ModelChoiceFilter(field_name='employee', method="filter_employee", queryset=Employee.objects.filter()) class Meta: model = LeaveRequest fields = ['employee', 'type', 'date_time'] def filter_employee(self, queryset, name, value): qs = queryset.filter(user=self.user).filter(**{name: value}) if len(qs) >= 1: return qs[0] else: return None This no longer brings an error, but the employee field still shows all of the employees in the database, not filtering it based on the user. -
How can I implement a File_name field that excludes my file path and contains only the file name [Django models]
I am developing an app in Django. In my template I have a fileform that allows users to store files in a model, they are stored in my media_root/uploaded_files/ directory: class my_model (models.Model): file_obj = models.FileField(upload_to='uploaded_files/', blank=False, null=False) def __str__(self): return "%s" % (self.file_obj) But in my admin section, accessing the model my_model I get file names like: • uploaded_ files/file_1 • uploaded_ files/file_2 • uploaded_ file /file_3 While I want: • file_1 • file_2 • file_3 How can I implement a File_name field that excludes “uploaded_ files” and contains only the file name? -
Is there a way to enable selecting multiple files on a single file upload in Django Admin so that upon saving multiple records are created?
I have a case where users upload files and each file has certain attributes. Often times there could be 10 files that will need to be uploaded into the database with the same attributes. To save time, it would be nice to allow the user to select all ten files and have 10 records added in the database, one record per file. My models are similar to the example below: class ContentCategory(models.Model): name = models.CharField(max_length=100) class Document(models.Model): file_name = models.CharField(max_length=100, blank=True) note = models.TextField(null=True, Blank=True) content_category = models.ForeignKey(ContentCategory, on_delete=models.PROTECT) document = models.FileUpload(upload_to=f'{content_category}/') def save(self): self.file_name = os.path.basename(self.document.name) super(Document, self).save() My admin.py is simple, like the below code: class DocumentAdmin(admin.ModelAdmin): exclude = ('file_name',) admin.site.register(Document, DocumentAdmin) admin.site.register(ContentCategory) So here is an exact scenario that happens often. 10 photos will need to be uploaded and all of them get the same content category and note. Is there a way to setup the admin to allow someone to select the proper content category and write out the note and then select all 10 files to upload and have 10 records created in the document table upon save? One for each photo? -
Django IntegerField retrieves a 0 as a None value
Django has started retrieving all of my IntegerField with a value of zero as None instead of as a zero. This is happening across all of my models. I recently updated mysql-connector-python so I am not sure if that could be the problem. Does anyone know of a global setting or bug that would cause Django to start doing this across all of my models? example: class Brands(models.Model): brand_id = models.AutoField(primary_key=True) brand_name = models.CharField(unique=True, max_length=512) blacklisted = models.IntegerField() blacklisted_date = models.DateTimeField(blank=True, null=True) date_created = models.DateTimeField() class Meta: managed = False db_table = 'brands' The values for blacklisted are all being retrieved as None instead of 0. They are stored as a 0 in the database. Django version 2.2.1 MySQL InnoDB Thanks for any help you can provide. -
How do I mofify existing fields in django that have a many to many relationship?
I have a model with a many to many field (participant field in my Activity model, see below) that I want to edit using createview. However, I can only choose from the already existing entries, not create new ones. It is possible to do that in the admin site so there is a solution but I can't figure it out. I have tried to modify form_valid in views but with no succes. Any ideas how to add or modify a field that has a many to many relation? views.py: #response=super(CreateTour,self).form_valid() #self.object.project=self.form.cleaned_data['participant'] class CreateTour(CreateView): form_class=CreateTourForm template_name='artdb/createtour.html' def get_context_data(self,**kwargs): context=super(CreateTour,self).get_context_data(**kwargs) context['formset']=CreateFormset() return context def form_valid(self,form): self.object=form.save(commit=False) for p in form.cleaned.data['participant']: ap=Person() ap.group=self.object ap.person=ap ap.save() return super(self).form_valid(form) models.py: class Activity(models.Model): activity_name=models.CharField(max_length=200,default='no name') project=models.ForeignKey(Project,on_delete=models.CASCADE,default=1) participant=models.ManyToManyField(Person) min_stage_area=models.IntegerField(default='2') light_requirements=models.CharField(max_length=200,default='no requirements') sound_engineer=models.CharField(max_length=200,default='not needed') comment=models.ManyToManyField(Comment) def __str__(self): return self.activity_name class Meta: ordering = ('activity_name',) forms.py: class CreateTourForm(ModelForm): class Meta: model=Activity fields=('activity_name','project','participant') widgets={'participant':CheckboxSelectMultiple,} template: {% extends "artdb/index.html" %} {% block ct %} <form method="post">{% csrf_token %} <div class="input-group"> {% for fr in formset %} {{fr}} {% endfor %} <a> {{form}} </a> <div class="input-group-append"> <button class="btn btn-success add-form-row">+</button> </div> </div> <hr></hr> <div class="row spacer"> <input type="submit" value="save"> </div> </form> {% endblock ct %} -
Django LDAPS configuration
I have a django server (in Centos) with an LDAP server and i want to configure it as LDAPs. The steps i've followed are (with a given .cer): Copy the cer into /etc/openldap/certs cacertdir_rehash /etc/openldap/certs update-ca-trust enable Copy the cert into /etc/pki/ca-trust/source/anchors/ update-ca-trust extract update-ca-trust check Then I changed the setting.py in my Django server: AUTH_LDAP_SERVER_URI = "ldap://xxx" to AUTH_LDAP_SERVER_URI = "ldaps://xxx:636" SERVER_DOWN({'info': "TLS error -8179:Peer's Certificate issuer is not recognized.", 'desc': "Can't contact LDAP server"} I'm pretty sure that the server is working (as it worked for normal LDAP). Can you help me? -
Unable to access request.session variable upon url callback in Django
I am trying to integrate Spotify Authorization flow (to gain access and refresh tokens) into my Django app. For this I have setup two Django endpoints - one for spotify login and another for spotify callback. The login endpoint redirects to the spotify authorization endpoint, which requires the user to login into their spotify account and grant permissions. This is followed by the Spotify API redirecting to the callback view in my Django app. Along with redirecting, the API sends a get variable, that is further utilised by the callback view to gain access and refresh tokens. I need to store these tokens for each user of my website and for that I need to gain access to the user id. However the request.session variable always comes in empty in the callback view. Suggestions for gaining access to the request.session variable? -
Store Json schema in django model
I have to validate my incoming json files through some schema files which will be sent before Json filesarrive, I need to store my schema files inside a model so I can validate my incoming json files. My problem is my schema file in not a standard type and it's format is like this: { namespace: ‘string’, schema: { field_1: type1, field_2: type2, … } } How can I store incoming schema in this scenario and validate incoming json files with them? -
Django NoReverseMatch at /create/
I want to create a system. For this system I need to a patient create form. When I click the button, I can save the patient but there is a error page after I pushed it. Reverse for 'create' with keyword arguments '{'slug': 'James'}' not found. 1 pattern(s) tried: ['create/$'] (When I fill the form, I write James into title field) And even I write James, in mySql database, title column is like id. 1, 2, 3, ... etc not James... Where is my mistake? Thanks a lot. urls.py app_name = "patients" urlpatterns = [ path('patients/', views.PatientList.as_view(), name='patients_list'), url(r'^create/$', patient_create, name='create'), path('create/<slug:slug>/', views.PatientsDetail.as_view(), name='patients_detail'), ] models.py from django.db import models from django.urls import reverse from django.utils import timezone from django.utils.text import slugify from ckeditor.fields import RichTextField class newPatients(models.Model): title = models.CharField(max_length=100) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) created_date = models.DateTimeField(default=timezone.now) dept = models.TextField() address = models.TextField() phone = models.CharField(max_length=15) notes = RichTextField(verbose_name="notes") slug = models.SlugField(max_length=100, unique=True, editable=False) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title def get_create_url(self): return reverse('patients:create', kwargs={'slug': self.slug}) def get_unique_slug(self): slug = slugify(self.title.replace('ı', 'i')) unique_slug = slug counter = 1 while newPatients.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, counter) counter += 1 return unique_slug def get_absolute_url(self): return reverse('patients:create', … -
Django-Ajax passing multiple parameters
I am trying to get more details on clicking a button "type="button" class="apireq"" defined on each row and capture the result in javascript and show it in a window I am not able to get the clicked row data in jquery .It says variable value undefined .I wanted to POST multiple values . Is this the way to do it ? Do I need to modify urls.py template <tbody id="collist"></tbody> </tr> {% for index, row in s_results.iterrows %} <tr> <td> {{ row.colname }} </td> <td> {{ row.dbname }} </td> <td> {{ row.schemaname }} </td> <td> {{ row.tablenm }} </td> <td> {{ row.coltype }} </td> <td> {{ row.collength }} </td> <td> {{ row.colscale }} </td> <td> <input type="button" class="apireq" data-colname="{{row.colname}}" data-dbname="{{row.dbname}}" data-schemaname="{{row.schemaname}}" data-tablenm="{{row.tablenm}}" /> </td> <tr> {% endfor %} </tbody> js/app.js $('.apireq').click(function () { var jq_column_name = $("#collist tr").last().attr("data-colname"); alert(jq_column_name); var jq_dbname = $("#collist tr").last().attr("data-dbname"); var jq_schemaname = $("#collist tr").last().attr("data-schemaname"); var jq_tablenm = $("#collist tr").last().attr("data-tablenm"); $.ajax({ type: "POST", url: "http://localhost:8000/refresh1/", contentType: 'application/json; charset=utf-8', data: { column_name: jq_column_name, db_name: jq_dbname, schema_name: jq_schemaname, table_name: jq_tablenm }, success: function (data) { alert("success!!");}, error: alert("Failed!!") });}); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script> urls.py path('refresh////', views.refresh1, name='refresh1'), -
Django on docker; Staticfiles disappearing
I am trying to deploy my django project using docker nginx and gunicorn. My Issue is that the staticfiles I use for my project are missing from the container. when in the project: ls staticfiles/ css disconnected.html images lib nothing.css after going into the container with docker exec -it foo_web_1 /bin/sh ls staticfiles/ admin my docker-compose file: version: '3.7' services: web: build: context: ./foo-app dockerfile: Dockerfile.prod command: gunicorn foo-app.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/foo-app/web/staticfiles - media_volume:/home/foo-app/web/mediafiles expose: - 8000 env_file: - ./.env.prod nginx: build: ./nginx volumes: - static_volume:/home/foo-app/web/staticfiles - media_volume:/home/foo-app/web/mediafiles ports: - 2375:80 depends_on: - web volumes: postgres_data: static_volume: media_volume: the nginx.conf file: upstream foo-app { server web:8000; } server { listen 80; location / { proxy_pass http://foo-app; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /staticfiles/ { alias /home/foo-app/web/staticfiles/; } location /mediafiles/ { alias /home/foo-app/web/mediafiles/; } } the part of the settings.py that relates to staticfiles: STATIC_URL = "/staticfiles/" STATICFILES_DIRS = [ os.path.join(BASE_DIR, "staticfiles") ] Inside my dockerfile I define the following: ENV HOME=/home/foo-app ENV APP_HOME=/home/foo-app/web RUN mkdir $APP_HOME WORKDIR $APP_HOME and later I simply copy the entire project in using COPY . $APP_HOME All other file show up perfectly fine, and I have tried remove and … -
How to do long running process in Django view?
I have a django web application and I have to create model for Machine Learning in a view. It takes so long time so PythonAnyWhere does not allow it and it kills the process when it reaches 300 seconds. According to that, i want to ask two questions. 1- Without celery, django bg task or something else, my view which contains the long running process does not work in order. But when I use debugger, it works correctly. Probably, some lines of code try to work without waiting for each other without debugger. How can i fix this? 2- PythonAnyWhere does not support celery or other long running task packages. They suggest django-background-tasks but in its documentation, the usage is not explained clearly. So I could not integrate it. How can i integrate django-background-tasks? Thank you. -
Many to Many relation with custom table in Django
I have two models with many to many relationships with custom table such as Clinic and Doctor and custom table DoctorClinic. how could I get the list of Doctors based on Clinics? this is my views.py class ClinicDetailView(generic.DetailView): model = Clinic def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['doctor_list'] = self.doctor_set.annotate( shift=F('doctor_list__shift'), timming=F('doctor_list__timming') return context I got the error object has no attribute doctor_set here is my models.py class Clinic(models.Model): name = models.CharField(max_length = 256) area = models.ForeignKey(Area, on_delete=models.CASCADE,default=None,null=True) city = models.ForeignKey(City, on_delete=models.CASCADE,default=None,null=True) address = models.TextField() contact = models.CharField(max_length = 18) category = models.CharField(max_length=30,choices = CHTYPE) lat = models.FloatField() lon = models.FloatField() class Doctor(models.Model): name = models.CharField(max_length = 256) speciality = models.CharField(max_length = 256) contact = models.CharField(max_length = 12) speciality = models.ForeignKey(Speciality, on_delete=models.CASCADE) clinic_hospital = models.ManyToManyField(Clinic, through='DoctorHospital') class DoctorHospital(models.Model): clinic = models.ForeignKey(ClinicHospital, on_delete=models.CASCADE) doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE) shift = models.CharField(max_length=10) # time_from = models.DateTimeField(auto_now_add=False,blank=True) # time_to = models.DateTimeField( auto_now_add=False,blank=True) timing = models.CharField(max_length=20,blank=True) and here is my urls.py path('clinichospital/<int:pk>/',views.ClinicHospitalDetailView.as_view(),name = 'clinichospital_detail') please help me how can doctor list I show. -
Maintaining wagtail in production
I work at a small size agency, and we now have several sites running Wagtail in production with kubernetes hosted in containers. We are trying to figure out a way to make the maintenance of these sites as easy as possible. For example with the wordpress sites we are maintaining we have a central repo which hosts the current wordpress core that all sites are running that we can deploy to to update all sites to the latest versions at once. In wagtail this is different, we use pypi to install it as a package, and we might need to run migrations as well. Does anyone have a suggested approach to make the handling of multiple wagtail sites as easy as possible, preferably push once, update all? -
How to save image in base64 format as file in secure way?
My try: import base64 def form_valid(self, form): self.object = form.save(commit=False) if self.request.POST.get('image_as_base64', None): format, imgstr = self.request.POST.get('image_as_base64').split(';base64,') ext = format.split('/')[-1] data = ContentFile(base64.b64decode(imgstr)) file_name = "'temp_name." + ext self.object.receipt.save(file_name, data, save=True) Do you see any security problems? The value in the frontend is generated in this way (Vue.js method): saveMapAsImage() { this.printPlugin.printMap('A4Portrait page', 'Miles'); self = this; this.routingMap.on('easyPrint-finished', e => { var reader = new window.FileReader(); reader.readAsDataURL(e.event); // e.event is a Blob object reader.onloadend = function () { base64data = reader.result; self.image_as_base64 = base64data; } }); } HTML <input v-model="image_as_base64" type="hidden" id="id_image_as_base64" name="image_as_base64"/> -
Why is collectstatic not copying all my directories?
Currently working on deployment for my django website. Im trying to get my static files working so obviously I used this command: python manage.py collectstatic. Once finished running it prints 119 files copied... I thought this was working until I cd'd into the newly created static directory and didn't find my css folder. Weirdly enough, I did see the admin folder. Once I saw this, I deleted my static folder entirely and attempted to directly copy the static folder using scp. I did this and all of my other folders (css, uploads, etc. And also the admin folder) appeared. I tried to collectstatic now with all of the folders there only to find out when I do that, it deletes all of my folders except for the admin folder. When I start the website up using the runserver command. There is no css on my homepage but there is in the admin page. Any help is very much appreciated!! Thanks in advance! -
How to save image in base64 format as file in secure way?
My try: import base64 def form_valid(self, form): self.object = form.save(commit=False) if self.request.POST.get('image_as_base64', None): format, imgstr = self.request.POST.get('image_as_base64').split(';base64,') ext = format.split('/')[-1] data = ContentFile(base64.b64decode(imgstr)) file_name = "'temp_name." + ext self.object.receipt.save(file_name, data, save=True) Do you see any security problems? The value in the frontend is generated in this way (Vue.js method): saveMapAsImage() { this.printPlugin.printMap('A4Portrait page', 'Miles'); self = this; this.routingMap.on('easyPrint-finished', e => { var reader = new window.FileReader(); reader.readAsDataURL(e.event); // e.event is a Blob object reader.onloadend = function () { base64data = reader.result; self.image_as_base64 = base64data; } }); } HTML <input v-model="image_as_base64" type="hidden" id="id_image_as_base64" name="image_as_base64"/> -
Wagtail Inline Panel - Sort Order
So I'm struggling with ordering the choices within an InlinePanel (for an orderable) on my site. In the admin page, when adding a new item, the options are presented in the order they were added to the site (so, essentially the 'id' for that item); this is less than ideal considering there are hundreds of options presented in a manner that is not user friendly. I'm assuming this needs to be defined as ordering meta within the orderable, but I can't seem to get it to work. This is what my orderable looks like: class RelatedPeople(Orderable): service = ParentalKey('service.Services', related_name='related_person') person = models.ForeignKey('person.People', null=True, on_delete=models.SET_NULL, related_name='related_service') panels = [ FieldPanel('person') ] I've tried the following with no success: class Meta: ordering = 'person' and, trying to append the field within 'person' that I want to sort by, 'name': class Meta: ordering = 'person.name' There must be an obvious way to solve this that I'm over looking. A default sort order of the 'id' (in this case, for 'person.People') is rarely ever going to be suitable from the perspective of the content creator. Any advice would be greatly appreciated! Thanks in advance, Rob -
How do I assign an id/pk number to an existing user?
first time poster, new coder. Forgive my ignorance! I am trying to query the id/pk of users in my user table in the python shell but it is telling me that my users don't have that attribute. I thought that was created automatically? Since it is clearly not, how do I assign my existing users id numbers and how do I make sure new users are automatically assigned id numbers going forward? Thanks in advance! >>>user = User.objects.filter(username='alice') >>>user <QuerySet [<User: alice>]> >>>user.id Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'QuerySet' object has no attribute 'id' >>> user.pk Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'QuerySet' object has no attribute 'pk' -
Update html columns and tables when database is changed by using Ajax, jquery. Django
I'm new in using Ajax and javascript. I have an HTML page which will show the shopping status from customers. Like the picture below. I would like to use Ajax and jquery to implement something like when the customer gets more products or put products back, the database will be updated, and the webpage will display immediately without refresh the webpage by using ajax. Also, it will calculate the total price. And when the new customer comes in or checks out, the new column will be added or removed. I have google how to use long polling: test.js $(document).ready(function(){ pollServer(); }); var url='127.0.0.1:8000/test/' var isActive = true; function pollServer() { if (isActive) { window.setTimeout(function () { $.ajax({ url: "http://127.0.0.1:8000/test/", type: "POST", success: function (result) { // alert('TTTT'); pollServer(); }, error: function () { // alert("FFFFFFF"); pollServer(); }}); }, 3000); } } test.html <div class="container custom-container-width" style="text-align=center;" > <div class="row gap-buffer" > {% for customer in Customer %} <div class="col-sm-3 p-3 gap-buffer colsize " style="background-color:white;box-shadow: 10px 10px 5px grey; " > <div class="profilesize"> <img src="{{ MEDIA_URL }}/{{customer.uuid}}/{{customer.uuid}}.jpeg" width=192 height=108 > </div> <br> <div> <div class="table-responsive" > <table > <thead class="thead-dark " > <tr > <th>Product</th> <th>Count</th> <th>Price</th> <th>Subtotal</th> </tr> </thead> <tbody … -
Django CKEditor widget auto width
How to make my 'CKEditorUploadingWidget' from ckeditor to automatically change width? I'm using 'as_crispy_field' from 'crispy_form_tags' for vanilla django widgets, which makes them change their width automatically. Since 'CKEditorUploadingWidget' is not vanilla django widget, 'as_crispy_field' doesn't work with it. How do I make it to change width automatically?