Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
save thumbnail image path django python
i am generating thumbnail and i want to save image path to database when i upload from admin and api: class Image(models.Model): license_type = ( ('Royalty-Free','Royalty-Free'), ('Rights-Managed','Rights-Managed') ) image_number = models.CharField(default=random_image_number,max_length=12,unique=True) title = models.CharField(default=random_image_number,max_length = 100) image = models.ImageField(upload_to = 'image' , default = 'demo/demo.png') thumbnail = models.ImageField(upload_to='thumbs') category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE) shoot = models.ForeignKey(ImageShoot, on_delete=models.CASCADE, related_name='Image', null=True,blank=True) image_keyword = models.TextField(max_length=1000) credit = models.CharField(max_length=150, null=True) location = models.CharField(max_length=100, null=True) license_type = models.CharField(max_length=20,choices=license_type, default='') uploaded_at = models.TimeField(auto_now_add=True) def __str__(self): return self.title def save(self, *args, **kwargs): super(Image, self).save(*args, **kwargs) if not self.make_thumbnail(): raise Exception('Could not create thumbnail - is the file type valid?') def make_thumbnail(self): fh = storage.open(self.image.path) image = PILImage.open(fh) image.thumbnail((400,400),PILImage.ANTIALIAS) fh.close() thumb_name, thumb_extension = os.path.splitext(self.image.path) thumb_extension = thumb_extension.lower() thumb_filename = thumb_name + '_thumb' + thumb_extension temp_thumb = BytesIO() image.save(temp_thumb, FTYPE) temp_thumb.seek(0) self.thumbnail.save(thumb_filename, ContentFile(temp_thumb.read()), save=True) temp_thumb.close() return True this if we upload image from admin admin.py: @admin.register(Image) class ImageAdmin(admin.ModelAdmin): readonly_fields=['image_number','uploaded_at'] fields = ['title','image_number','shoot','category', 'image','image_keyword','thumbnail','credit','license_type','location','uploaded_at'] this is my views for api currently just uploading bulk image with out thumbnail how can i create thumbnail from this : views.py: class EventImageUploadView(APIView): def post(self, request,category): #title = forms.CharField(max_length = 100) file = request.data['file'] data={ 'image':file, 'category_id':category } EventsImage.objects.create(**data) return JsonResponse(json.dumps({'message': "Uploaded"}), status=200, … -
Include auto increment field to JSON response
New to Django and Django Rest. I am looking to modify the JSON return response of my view so that it also returns the id of the created user. The things is, the id is an auto increment integer and so I don't know how I can retrieve the info to add it to the JSON. Any help would be appreciated. Thanks. models.py class CustomUsers(AbstractUser): email = models.EmailField(unique=True) username = models.CharField(max_length=100) USERNAME_FIELD = 'email' class Meta: db_table = "custom_users" serializers.py class CustomUsersCreateSerializer(serializers.ModelSerializer): def create(self, validated_data): last_name = validated_data['last_name'] first_name = validated_data['first_name'] username = validated_data['username'] email = validated_data['email'] password = validated_data['password'] user_obj = USER( last_name=last_name, first_name=first_name, username=username, email=email, ) user_obj.set_password(password) user_obj.save() return validated_data class Meta: model = USER fields = ('id', 'last_name', 'first_name', 'username', 'password', 'email') extra_kwargs = {'password': {'write_only': True, 'min_length': 10}} views.py class UserCreateAPIView(CreateAPIView): serializer_class = serializers.CustomUsersCreateSerializer queryset = CustomUsers.objects.all() -
csrf token value not changing in django
I am a newbie to django framework. I have created a simple arithmetic application using django. As suggested in django document, i wrote {% csrf_token %} in my template file. But, the thing i notice is that, token value is not changing on post request. it is showing same value every time with expiry of 364 days So, let me know the settings to change CSRF Token Value in each post request. Thanks in advance My template code below <form action="{{ action }}" method="post"> {% csrf_token %} <fieldset> <legend>{{ tag }}:</legend> Number 1: <input type="text" size="10" name="num1" value="{{ n1|default:0 }}"><br> <span> {{ operator }} </span><br> Number 2: <input type="text" size="10" name="num2" value="{{ n2|default:0 }}"><br> <span> = </span><br> Result&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;: <input type="text" size="10" value="{{ res|default:0 }}" disabled> &nbsp; <span>{{ warning|default:'' }} </span><br><br> <input type="submit" size="10"> </fieldset> </form> <a href="/app1">App1 Home</a> My view code below def add(request): warn = '' res, n1, n2 = (0, 0, 0) try: n1 = int(request.POST['num1']) n2 = int(request.POST['num2']) res = n1 + n2 except (ValueError, TypeError): warn = 'Text data is not allowed.' params = {'operator': '+', 'action': 'add', 'tag': 'Addition' ,'n1': n1, 'n2': n2, 'res': res, 'warning': warn} return render(request, 'arithmatic_app1.html', params) -
Django: Get all sub related instances of the given instance
I would like to get all sub related instances of all classes that have reference to the given instance. I have tried using related_name, but it doesn't serve the purpose as it only gets all instances of one particular class, not all instances of all related classes. How could I achieve this? I need to get all related instances to perform an operation similar to on_delete=models.CASCADE. Model class AlertTypeMaster(): alert_type_name = models.CharField(max_length=255) description = models.CharField(max_length=255) active = models.BooleanField(default=True) class MachineAlertZone(): machine_id = models.ForeignKey(MachineMaster, on_delete=models.CASCADE) alert_type_id = models.ForeignKey(AlertTypeMaster, on_delete=models.CASCADE) radius_value = models.CharField(max_length=50) active = models.BooleanField(default=True) class ActivityRecording(): alert_type_id = models.ForeignKey(AlertTypeMaster, on_delete=models.CASCADE) working_area_id = models.ForeignKey(WorkingAreaMaster, on_delete=models.CASCADE) staff_id = models.ForeignKey(StaffMaster, on_delete=models.CASCADE) type_of_occur = models.CharField(max_length=255) active = models.BooleanField(default=True) Given the one object of AlertTypeMaster, I should be able to get all objects from both MachineAlertZone and ActivityRecording. Please suggest any suitable approaches! -
Django forms does not care about html input
In my django project i have reate a form for manage user registration, here my code: models.py: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,) u_fullname = models.CharField(max_length=200) u_email = models.EmailField() u_profile = models.CharField(max_length=1) u_type = models.CharField(max_length=1, default='F') u_job = models.CharField(max_length=100, null=True, blank=True, default='D') u_country = models.CharField(max_length=20, null=True, blank=True, default='Italy') u_regdata = models.DateTimeField(auto_now=True) u_picture = models.ImageField(upload_to='profile_images', blank=True) u_active = models.BooleanField(default=False) u_terms = models.BooleanField(default=False) def __unicode__(self): return self.u_profile forms.py class ProfileModelForm(ModelForm): class Meta: model = UserProfile fields = ['u_fullname', 'u_job', 'u_country', 'u_email', 'u_terms', ] def clean(self): cleaned_data = super(ProfileModelForm, self).clean() u_fullname = cleaned_data.get('u_fullname') u_job = cleaned_data.get('u_job') u_country = cleaned_data.get('u_country') u_email = cleaned_data.get('u_email') u_terms = cleaned_data.get('u_terms') if not u_terms: raise forms.ValidationError("Please read and accept our Terms of Service") return u_terms if not u_fullname and not u_job and not u_country and not u_terms: raise forms.ValidationError('You have to write something!') the views.py if request.method == 'POST': if 'user_reg' in request.POST: form = ProfileModelForm(request.POST) if form.is_valid(): instance = form.save(commit=False) #Create user and get the id n_user = User.objects.create_user(username=request.POST['u_email'], email=request.POST['u_email'], password=request.POST['u_password']) instance.user = User.objects.get(id=n_user.id) instance.u_profile = 'U' instance.save() return else: messages.error(request, "Error") at the end my html form portion: <form action="" method="POST"> {% csrf_token %} {{ form.errors }} <div class="row"> <div class="col-lg-12 no-pdd"> <div class="sn-field"> <input type="text" name="u_fullname" … -
Django : How to send a Socket Chat Content to the Client
Now Socket itself is working well. But this alone cannot complete the chat I wanted. When I send a chat, I want to save the chat contents on the server, and I want to call up the chat contents when I connect to the chat room. my socket code : class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] sender = text_data_json['sender'] # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'sender' : sender } ) # Receive message from room group async def chat_message(self, event): message = event['message'] sender = event['sender'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message, 'sender' : sender })) my model : class Message(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='sender') receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='receiver') message = models.CharField(max_length=1200) timestamp = models.DateTimeField(auto_now_add=True) is_read = models.BooleanField(default= False) def __str__(self): return self.message class Meta: ordering = ('-timestamp',) Is there a good way to make a chat I want? -
Django & Python: Creating a Timetable
I am trying to use Django to create a timetable. I have tried to realise it with Python, it looks like: durations = [30, 30, 45] #lessons with various durations count=0 start_time = 9 for x in durations: count = count + x/60 end_time = count + start_time print(end_time) Output: 9.5 # 09:30 10.0 # 10:00 10.75 # 10.45 My Django template: {% for student in students %} <tr> <td>{{forloop.counter}}</td> <td>{{ student.first_name }}&nbsp;{{ student.last_name }}</td> <td>{{ student.duration }} mins</td> <! Stuck here: start time and end time ––> <td>Start Time - End Time</td> </tr> {% endfor %} My goal is getting a table like this: Student A | 30 mins | 09:00 - 09:30 Student B | 30 mins | 09:30 - 10:00 Student C | 45 mins | 10:00 - 10:45 There are filters to do mathematical operations such "add" and "sub", but seems we can't do something like "x = x + 1"? Any ideas? Thanks a lot! -
Cannot access value for CheckboxSelectMultiple using request.POST
I am designing a form which uses CheckboxSelectMultiple to let a user select toppings for a pizza. Topping is its own class with just a 'name' attribute. class Pizza(models.Model): menu = models.ForeignKey(Menu, on_delete=models.CASCADE, related_name="pizza") style = models.ForeignKey(PizzaStyle, on_delete=models.CASCADE) size = models.ForeignKey(Size, on_delete=models.CASCADE) is_special = models.BooleanField(default=False) num_toppings = models.IntegerField() toppings = models.ManyToManyField(Topping, blank=True) price = models.DecimalField(max_digits=5, default=0.00, decimal_places=2) class PizzaForm(ModelForm): class Meta: model = Pizza exclude = ['menu', 'price'] widgets = { 'toppings': CheckboxSelectMultiple, } labels = { 'num_toppings': 'Number of Toppings', 'is_special': 'Gluten Free Dough' } The form creates fine in views.py with the correct labels for each Topping. However, when I pass the form data to another page (cart), I can only pass the number of the last checkbox selected in the form. (i.e. if pepperoni is selected and is the third checkbox in the list, then request.POST['toppings'] returns 3. I'm trying to do something like this in views.py for cart such that I can generate a list of toppings: toppings = "" for topping in request.POST['toppings']: print(topping.label) toppings = ", ".join(topping) I have tried some searching through the documentation but cannot seem to figure out my problem. Thank you! -
Uncught typeError: cannot read property closest of null in Materialize stepper.js
I am working with Materialize css and using Materialize stepper but it is showing uncaught typeError: cannot read 'closest' of null with Django but without django its working fine do anyone have any idea about that? -
What is the most efficient method to synchronize my database and the data received from an API?
I'm storing user's data and articles using the Pocket API into a SQLite Database using Django Framework. How can I efficiently maintain consistency between the database and the data received from the API? I'm planning to update the database once every 24 hours. -
django2 views.pyl: attribute the values from list
Beginner of Django. Several questions about Django Q: How to write a proper way to let Django views.py read values individually from list without ‘’ Example: Urls.py path('booklist/<str:pk>/', views.Paristour, name='Paristour'), views.py it works with single value def Paristour(request,pk): a =('aa') if a == pk: contact = "good" else: return render(request, '404.html', locals()) return render(request, 'paristour.html', locals()) It doesn’t work. All I want is to pk == aa, pk == bb, pk ==cc without aa, bb, or cc, the rest of str(string) goes to 404 html def Paristour(request,pk): a =['aa', 'bb', 'cc'] if a == pk: contact = "good" else: return render(request, '404.html', locals()) return render(request, 'paristour.html', locals()) best regards Thank you very much -
Google cloud datastore Rollback its previous saved row
I am using Django with Google cloud datastore i.e. Djange (https://djangae.org/) I am new to these tech stacks and currently facing one strange issue. when I persist data by calling Model.save(commit=true) . The data gets saved into cloud datastore but after 4/5 mins it gets reverted. To test it further I tried to directly change the value in database but it also got reverted after sometime. I am kind of confused as there is no error or exception I see . I am making atomit transaction and wrapped my code with try except to catch any exception but no luck. could someone please advise me as how to debug further here. -
After creating new field Leads in admin, Admin site structure get change
in my admin section I have created new field Leads and for that, I did some changes like 1. In models.py I have created a new table CustomUser(AbstractUser) that extending AbstractUser 2. In setting.py I have added AUTH_USER_MODEL = 'users.Custom_User'. 3. in admin.py I have import Custom user and register it Now I'm facing issues that I cant enter image description here -
How to convert JSON string to Python Object (Dictionary)
I am having a weird issue. Running Django 3.0.1 and in my view I have a try statement. For some reason I am not able to convert the JSON string to a Python Object (dict). This is my code: try: message_to_clientsservice = { 'id': id_id, 'name': 'create-member-client-for-tenant-setup', 'payload': { 'clientName': client_name, 'kbCorporationId': int(kb_corp_id), 'email': email, 'clientTypeId': client_type_id, 'address': { 'countryCode': country_code, }, 'phoneNumbers': [] } } clientsservice_request_header = { 'Content-Type': 'application/json', 'ServiceAccessToken': service_access_token, 'Ocp-Apim-Subscription-Key': ocp_apim_subscription_key, 'Authorization': 'Bearer ' + bearer_token } # print(message_to_clientsservice) # print(type(message_to_clientsservice)) # print(json.dumps(message_to_clientsservice)) # print(type(clientsservice_request_header)) # print(clientsservice_request_header) clients_service_response = requests.post(clientsservice_url, headers=clientsservice_request_header, data=json.dumps(message_to_clientsservice)) print(clients_service_response.status_code) json_data_scrambledegg = clients_service_response.text for r in (('\\', ''), ('{\\', ''), ('\"\"}\"}', '\"\"}}'), ('\"payload\":\"', '\"payload\":')): json_data_scrambledegg = json_data_scrambledegg.replace(*r) print(type(json_data_scrambledegg)) print(json_data_scrambledegg) data = json.loads(json_data_scrambledegg) print(data) except: print('Something went wrong! Try again or contact your Sysadmin!') messages.warning(request, 'Something went wrong! Try again or contact your Sysadmin!') return render(request, 'create_member_company/create_member_feedback.html') else: messages.success(request, 'Your Message was sent successfully!') return render(request, 'create_member_company/create_member_feedback.html') and getting this output: January 09, 2020 - 04:58:01 Django version 3.0.1, using settings 'erm_admin.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. 200 <class 'str'> {"id":"66995ab6-2962-465c-aa52-f68108f2ac97","name":"create-member-client-for-tenant-setup-response","correlationId":"025bb4aa-9396-4202-bcbc-fcbabfd498a8","payload":{"newlyCreatedClient":{"clientId":7270,"clientName":"Milk Man 1","corporationId":4520226,"corporationName":"Milk Man 1"},"suggestedExistingClients":null,"success":true,"errorMessage":""}} Something went wrong! Try again or contact your Sysadmin! [09/Jan/2020 04:58:07] "POST /create_member/ HTTP/1.1" … -
disable form field if data is exist in database
I want to enter the username and disable username field if already exists during form initialization. I want the username text field disabled if the username exists in the database. class UserForm(forms.ModelForm): class Meta: model=AppUser fields=['username','password'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) user_id = self.request.POST.get('user_id') if AppUser.objects.filter(usernbame=user_id).exists(): self.fields['username'].disabled = True -
Django: App to store/edit/version control configuration data for a linux tool
I have a tool on Linux. The tool requires a lot of configuration data (say in JSON/YAML format). In addition, the configuration data can change over time so there is a need to version it. The users would like to enter/edit this configuration data using a web portal. What would be the ideal/fastest way to prototype a Django app that does this? (I have a small Django test site up and running). Would a form or modelform be more suitable? I will let the user edit the fields/save the data via the admin interface or some sort of form editor + version it. Eventually, I need to somehow serialize it to a file for the linux tool to pick up. Thanks for any ideas. -
How to apply find.all() using bs4 in Django
I am converting the dataframe into table after that I am trying to find out the <tr></tr> inside the table tag so that I could apply different checks on that but the problem is that it is not working. Although the same code is working on the localhost but when deploying it is making problem with the it is not applying on that . When I am trying to access the <th></th> it is working. Here inside the find("thead").find_all('tr') it is working here in this part of the code for j in soup.find("thead").find_all('tr'): But When I am trying to access if soup.find('tbody').find_all('tr') is not None: #but here it gives us None_type tbody tag #soup not finding tbody tag This gives us None_type tbody tag #soup not finding tbody tag This is the complete code soup = BeautifulSoup(sorted_df.to_html(), "html.parser") count = 0 for j in soup.find("thead").find_all('tr'): if count == 0: j.append(BeautifulSoup('<td><b><center>Next Result</center></b></td>', 'html.parser')) count += 1 else: j.append(BeautifulSoup('<td></td>', 'html.parser')) modal_identifier = 0 print(soup,"HERE") #here it shows that soup has tbody tag in it job_card = 0 if soup.find('tbody').find_all('tr') is not None: #but here it gives us None_type tbody tag #soup not finding tbody tag i = 0 while ((soup.find_all("tr")) is not … -
Using CKEditor with AWS S3 Static files
I am trying to use CKEditor with the static files using 'collectstics', which all the static files are served from the AWS S3. Everything else seems to work, but except for the CKEditor. When I just run my server using Local Filesystem, it works obviously. But if I serve the static files from S3, the CKEditor does not render into the templates. How can I deal with this problem? -
mobile apps development with python
I want to start learning to create mobile apps (IOS/Andriod) with python. what is the best framework or libraries that I should learn to use? I have read about many things like Django or kivy and some other similar things, but I still can't decide what is the best among them, and is it good idea to create apps with python? -
Django Rest Framework Relationship
(Question before: Django Rest Framework nested relationship) I've made serializer like this: serializers.py from rest_framework import serializers, fields from .models import Pegawai,Barang class BarangSerializer(serializers.ModelSerializer): class Meta: model = Barang fields = ( 'pegawai', 'nama_barang', 'harga_barang', ) def to_representation(self, instance): rep = super().to_representation(instance) rep['pegawai'] = instance.pegawai.name return rep class PegawaiSerializer(serializers.ModelSerializer): barangs = BarangSerializer(read_only=True, many=True) class Meta: model = Pegawai fields = ( 'id', 'name', 'alias', 'barangs', ) Results : { "pegawai": "Ryan", "nama_barang": "burjo", "harga_barang": "1234" }, And How to make the result like this in the barang API when posted the data: { "pegawai": {"id" : 1, "name" : "Ryan", "alias" : "R"} "nama_barang": "burjo", "harga_barang": "1234" }, Please help, cheers. -
Django Error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/helpdesk/login/?next=/
I'm a beginner. I'm trying to build a helpdesk system using Django helpdesk framework. But when I click on login button, I get the following error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/helpdesk/login/?next=/ Using the URLconf defined in moog.urls, Django tried these URL patterns, in this order: admin/ ^dashboard/$ [name='dashboard'] ^tickets/$ [name='list'] ^tickets/update/$ [name='mass_update'] ^tickets/submit/$ [name='submit'] ^tickets/(?P<ticket_id>[0-9]+)/$ [name='view'] ^tickets/(?P<ticket_id>[0-9]+)/followup_edit/(?P<followup_id>[0-9]+)/$ [name='followup_edit'] ^tickets/(?P<ticket_id>[0-9]+)/followup_delete/(?P<followup_id>[0-9]+)/$ [name='followup_delete'] ^tickets/(?P<ticket_id>[0-9]+)/edit/$ [name='edit'] ^tickets/(?P<ticket_id>[0-9]+)/update/$ [name='update'] ^tickets/(?P<ticket_id>[0-9]+)/delete/$ [name='delete'] ^tickets/(?P<ticket_id>[0-9]+)/hold/$ [name='hold'] ^tickets/(?P<ticket_id>[0-9]+)/unhold/$ [name='unhold'] ^tickets/(?P<ticket_id>[0-9]+)/cc/$ [name='ticket_cc'] ^tickets/(?P<ticket_id>[0-9]+)/cc/add/$ [name='ticket_cc_add'] ^tickets/(?P<ticket_id>[0-9]+)/cc/delete/(?P<cc_id>[0-9]+)/$ [name='ticket_cc_del'] ^tickets/(?P<ticket_id>[0-9]+)/dependency/add/$ [name='ticket_dependency_add'] ^tickets/(?P<ticket_id>[0-9]+)/dependency/delete/(?P<dependency_id>[0-9]+)/$ [name='ticket_dependency_del'] ^tickets/(?P<ticket_id>[0-9]+)/attachment_delete/(?P<attachment_id>[0-9]+)/$ [name='attachment_del'] ^raw/(?P<type>\w+)/$ [name='raw'] ^rss/$ [name='rss_index'] ^reports/$ [name='report_index'] ^reports/(?P<report>\w+)/$ [name='run_report'] ^save_query/$ [name='savequery'] ^delete_query/(?P<id>[0-9]+)/$ [name='delete_query'] ^settings/$ [name='user_settings'] ^ignore/$ [name='email_ignore'] ^ignore/add/$ [name='email_ignore_add'] ^ignore/delete/(?P<id>[0-9]+)/$ [name='email_ignore_del'] ^$ [name='home'] ^view/$ [name='public_view'] ^change_language/$ [name='public_change_language'] ^rss/user/(?P<user_name>[^/]+)/$ [name='rss_user'] ^rss/user/(?P<user_name>[^/]+)/(?P<queue_slug>[A-Za-z0-9_-]+)/$ [name='rss_user_queue'] ^rss/queue/(?P<queue_slug>[A-Za-z0-9_-]+)/$ [name='rss_queue'] ^rss/unassigned/$ [name='rss_unassigned'] ^rss/recent_activity/$ [name='rss_activity'] ^login/$ [name='login'] ^logout/$ [name='logout'] ^password_change/$ [name='password_change'] ^password_change/done$ [name='password_change_done'] ^kb/$ [name='kb_index'] ^kb/(?P<item>[0-9]+)/$ [name='kb_item'] ^kb/(?P<item>[0-9]+)/vote/$ [name='kb_vote'] ^kb/(?P<slug>[A-Za-z0-9_-]+)/$ [name='kb_category'] ^help/context/$ [name='help_context'] ^system_settings/$ [name='system_settings'] The current path, helpdesk/login/, didn't match any of these. Below is my settings.py : import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '7)%lt=ea(z6mi1k$3ho5jmlz^(5kz01h78&f6pl7u=k6$1hzao' # SECURITY WARNING: … -
Django Rest Framework - Ordering a nested reverse lookup serializer
Is it possible to order/sort a serializer availability that is both a reverse lookup and nested inside unit serializer? For example, I wish to order availability by start_time instead of id. Due to the model relationship between Unit and Availability, the only way for me to nest availability serializer in unit was to use source='availability_set' in the unit serializer. However, when I try to use a serializer method to sort the 'availability' by 'start_time', I get an error "SerializerMethodField() AttributError object has no attribute". Usually, serializer methods work well but I think this might have to do with the reverse nature of the model relationship. Any idea how to solve this? JSON Data { "id": 1, "address": "123 Stewart Ave", "manager": { "company": "BarberShop Inc.", "logo": null }, "availability": [ { "id": 9, "start_time": "2020-01-07T12:00:00Z", "end_time": "2020-01-07T14:00:00Z", "staff": { "user_id": 3, "name": "Sandra", "profile_pic": "" } }, { "id": 17, "start_time": "2020-01-07T09:00:00Z", "end_time": "2020-01-07T10:00:00Z", "staff": { "user_id": 3, "name": "Sandra", "profile_pic": "" } }, ... Serializers class StaffSerializer(serializers.ModelSerializer): name = serializers.StringRelatedField(source='user',read_only=True) class Meta: model = Staff fields = ['user_id', 'name', 'profile_pic'] class AvailabilitySerializer(serializers.ModelSerializer): staff = StaffSerializer() class Meta: model = Availability fields = ['id','start_time', 'end_time','staff'] class ManagerSerializer(serializers.ModelSerializer): class Meta: model … -
Django Channel objects message passing and class execution?
I have a routing.py where it looks like this application = ProtocolTypeRouter({ 'websocket': backEndConsumer, 'http': frontEndConsumer, ]) I want my frontEndConsumer to tell my backEndConsumer to execute a websocket_send text but whenever I try to do that nothing happens. I am sure this is because my frontEndConsumer isn't actually talking to my backEndConsumer. This means I need some sort of loop in backEndConsumer that polls shared data somewhere and waits for a request to send command, but How do I even have a loop in heroku when I'm using Django Channels and ASGI? Otherwise I need a way for my frontendConsumer to directly execute a function in backEndConsumer, how would I do that? -
How do I store multiple checkbox data in a list of array?
I'm working on a Django form with multiple checkbox that looks like this: multiple checkbox form I've manage to store the data in multiple separate columns: picture of the data row in my database My question is how can I store the multiple checkbox data in a single column instead of multiple separate columns? Here's the checkbox's HTML <label class="form-control acl-label">Project Management</label> <div><input class="project" value="listing" name="project[]" type="checkbox" id="project-listing.{{user.id}}"> <label for="project-listing.{{user.id}}">Listing</label></div> <div><input class="project" value="create" name="project[]" type="checkbox" id="project-create.{{user.id}}"> <label for="project-create.{{user.id}}">Create</label></div> <div><input class="project" value="edit" name="project[]" type="checkbox" id="project-edit.{{user.id}}"> <label for="project-edit.{{user.id}}">Edit</label></div> <div><input class="project" value="delete" name="project[]" type="checkbox" id="project-delete.{{user.id}}"> <label for="project-delete.{{user.id}}">Delete</label></div> <br/> Here's the code for my view.py file project_mgmt = request.POST.getlist('project[]') engagement_mgmt = request.POST.getlist('engagement[]') issue_mgmt = request.POST.getlist('issue[]') user_mgmt = request.POST.getlist('user[]') reporting_mgmt = request.POST.getlist('reporting[]') setting = request.POST.getlist('setting[]') audit_log = request.POST.getlist('audit[]') AccessControl.objects.filter(uid_uname=user_id).update(project_mgmt=project_mgmt, engagement_mgmt=engagement_mgmt, issue_mgmt=issue_mgmt, user_mgmt=user_mgmt, reporting_mgmt=reporting_mgmt, setting=setting, audit_log=audit_log) -
How to connect microsoft graph to on premis 2013 microsoft exchange?
We are trying to integrate a on premis Microsoft 2013 exchange server into a in-house web django application. The objective is to be able to query the entire database of mails , and send mail from within our webapplication . So far , we have been successful using the microsoft graph API , however the success only applies to accounts that have the outlook domain name (those that were registered as a personel user account via the outlook.com website) . We are not able to access the mail data that resides on our on premis mail server , therefore we wish to ask if there is a solution for this?