Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
adding a record to FontawesomeIcons table through Serivces class
i want to add a service to Services section in my website. each service has an icon that comes from Fontawesome website. i have 2 class: class FontawesomeIcons(models.Model): icon_name = models.CharField(max_length=200) icon_fontawesome = models.CharField(max_length=200) class Serivces(models.Model): icon = models.ForeignKey(FontawesomeIcons, on_delete=models.CASCADE, related_name='services') icon_name = models.CharField(max_length=200) icon_fontawesome = models.CharField(max_length=200) icon.icon_name = icon_name icon.icon_fontawesome = icon_fontawesome when i'm going to create a service i want to add an icon for that in the Services page in django admin CMS. i want to fill FontawesomeIcons class values through Services class. thank's for any help. -
Django-Background-Tasks: Initialize Task at midnight and repeat every midnight
Good day SO, I am currently using Django, and the Django-Background-Tasks package. I have a periodic task that I need to run at midnight, and it is to be repeated every midnight. I am a beginner at using the package, and am confused by the following: How do I set the repeat parameter during initialization? Here is my code: from background_task import background from datetime import datetime, date today_date = datetime.datetime.today() today_midnight = today_date.replace(hour=23, minute=59, second=59) @background(schedule=today_midnight) def send_reminders():... send_reminders(repeat=Task.DAILY) I wanted to set the parameter 'repeat' to task.DAILY, as stated in the documentation. However, I have encountered the following: NameError: name 'Task' is not defined I know I have to import something to define Task, but I couldn't find it. Can anyone help me? -
How to return folder name uploaded from <input webkitdirectory mozdirectory> to views.py in django
I have an HTML file in my Django project which has directory selector using <input type="file" name="file" id="uploadFolder" webkitdirectory mozdirectory/> I want to pass the folder path selected to views.py . I tried it using FormData concept but I am getting just file name not the folder path. I did something like below: <form method="POST" enctype="multipart/form-data" id="fileUploadForm"> {% csrf_token %} <input type="file" name="file" id="uploadFolder" webkitdirectory mozdirectory/><br/><br/> <input type="button" value="Submit" id="btnSubmit"/> </form> and on buttton cllick something like this: $.ajax({ type: "POST", enctype: 'multipart/form-data', url: "/upload/", data: data, processData: false, contentType: false, cache: false, timeout: 600000, success: function (data) { $("#result").text(data); console.log("SUCCESS : ", data); $("#btnSubmit").prop("disabled", false); }, error: function (e) { } }); }); How can I get the full path(or folder name)? -
How to get data from select forms using CBV or FBV
I'm having an issue displaying data from a Model that is retrieved from a select form. I prefer to use a CBV, but it doesn't matter at this point as long as it solves the issue. I've tried both ways and encounter a different problem for each way. I'll start with my CBV attempt. views.py class VehicleCompareView(FormView): template_name = "main/vehicle_compare.html" form_class = forms.CompareForm # I added different iterations of this in an attempt # to call the data in the html after previous attempts failed def get_form_data(request): form = forms.CompareForm(request.GET) data = form.cleaned_data['v-selection'] if form.is_valid(): data = form.cleaned_data['value'] return data forms.py class CompareForm(forms.Form): objectlist = forms.queryset = models.Vehicle.objects.all().order_by('make') html <div class="some class"> <form name="vform" method="get"> <select class="form-control" name="v-selection"> <option value="" selected disabled>Select Vehicle 1</option> {% for q in form.objectlist %} {% for b in q.package_set.all %} <option value="{{q}}" name="v-option"> {{ q.v_make }} {{ q.v_model }} {{ b.name }} </option> {% endfor %} {% endfor %} </select> <input value="submit" type="submit"> </form> <div> <p>{{data.v_make}}</p> </div> With this I am able to have a dropdown box that allows a selection in the right format, but nothing gets returned after submitting the selection. The next way I tried was with a FBV. I made … -
How to get the right revcounter through Django Pagnination?
I have a list of users. I list them in page with pagination like the following 113 - User13 112 - User 12 The problem is that each page is initializing with the the quantity set to the pagination. Let's say I have set a pagination with 10 users. each page will be set with the same counter like: 10 - user10 9 - user 8 - user1 I have tried this, but it's not working. {{forloop.revcounter0|all_profiles.end_index}} - {{user.get_full_name}} What I want is, with for instance 6 users divided by 2 pages with a pagination set to 3 users. Note the correct counter Page 1 6.- User 6 5.- User 5 4.- User 4 Page 2 3.- User 3 2.- User 2 1.- User 1 -
How Do I Install a Django Package from Github
I am using Django and Pipenv and have come across a package that I cannot install using "pipenv install [package_name]." The package I am trying to install is django-dynamic-formset. I have tried running this from my pipenv shell: "pipenv install -e git+https://github.com/elo80ka/django-dynamic-formset@v1.1#egg=django-dynamic-formset." I get the error below: https://github.com/elo80ka/django-dynamic-formset (src) (.venv) C:\Users\username\Documents\src>pipenv install -e git+https://github.com/elo80ka/django-dynamic-formset@v1.1#egg=django-dynamic-formset Installing -e git+https://github.com/elo80ka/django-dynamic-formset@v1.1#egg=django-dynamic-formset… Adding django-dynamic-formset to Pipfile's [packages]… Installation Succeeded Pipfile.lock (706c4a) out of date, updating to (0db539)… Locking [dev-packages] dependencies… Success! Locking [packages] dependencies… [= ] Pinning VCS Packages...error: pathspec 'v1.1' did not match any file(s) known to git Traceback (most recent call last): File "c:\users\username\appdata\local\programs\python\python37\lib\runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "c:\users\username\appdata\local\programs\python\python37\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\username\AppData\Local\Programs\Python\Python37\Scripts\pipenv.exe\__main__.py", line 9, in <module> File "c:\users\username\appdata\local\programs\python\python37\lib\site-packages\pipenv\vendor\click\core.py", line 764, in __call__ return self.main(*args, **kwargs) File "c:\users\username\appdata\local\programs\python\python37\lib\site-packages\pipenv\vendor\click\core.py", line 717, in main rv = self.invoke(ctx) File "c:\users\username\appdata\local\programs\python\python37\lib\site-packages\pipenv\vendor\click\core.py", line 1137, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "c:\users\username\appdata\local\programs\python\python37\lib\site-packages\pipenv\vendor\click\core.py", line 956, in invoke return ctx.invoke(self.callback, **ctx.params) File "c:\users\username\appdata\local\programs\python\python37\lib\site-packages\pipenv\vendor\click\core.py", line 555, in invoke return callback(*args, **kwargs) File "c:\users\username\appdata\local\programs\python\python37\lib\site-packages\pipenv\vendor\click\decorators.py", line 64, in new_func return ctx.invoke(f, obj, *args, **kwargs) File "c:\users\username\appdata\local\programs\python\python37\lib\site-packages\pipenv\vendor\click\core.py", line 555, in invoke return callback(*args, **kwargs) File "c:\users\username\appdata\local\programs\python\python37\lib\site-packages\pipenv\vendor\click\decorators.py", line 17, in new_func return f(get_current_context(), *args, **kwargs) File "c:\users\username\appdata\local\programs\python\python37\lib\site-packages\pipenv\cli\command.py", line 254, in … -
Get database table data older then 10 days in django
I am trying to retrieve data older then 10 days to update that field data. Currently my model is like class Restaurant(models.Model): is_approved = models.BooleanField(null=False, default=False) timestamp = models.DateTimeField(auto_now_add=True) my database table is Now when I query like dish = Restaurant.objects.filter(timestamp__gt=datetime.now() - timedelta(days=10)) I get whole table data. even I tried to change from day to 1 day . still full database result. -
Merge two user data dictionary data into a single dictionary ,have having same user data in python
Here the Problem is Explained. I ahve Users having multiple skiils . Showing Data like the Problem with seperate skills data Solution I needed for same user's skills will be at same array data. Problem: Data is LIke this Type: { 'group'= 'GR-A', 'users'=[ { 'id' = 1, 'name' = 'A' 'skills' = { 'id' = 1 'name' = 'skill-A' } }, { 'id' = 1, 'name' = 'A' 'skills' = { 'id' = 2 'name' = 'skill-B' } }, { 'id' = 2, 'name' = 'B' 'skills' = { 'id' = 2 'name' = 'skill-B' } }, ] } Data Solution Needed: { 'group'= 'GR-A', 'users'=[ { 'id' = 1, 'name' = 'A' 'skills' = [ { 'id' = 1 'name' = 'skill-A' }, { 'id' = 2 'name' = 'skill-B' } ] }, { 'id' = 2, 'name' = 'B' 'skills' = [ { 'id' = 2 'name' = 'skill-B' } ] }, ] } -
Why docker-compose don't copy files to virtualbox machine when running? "python: can't open file 'manage.py': [Errno 2] No such file or directory."]
I have problem with my dockers and I don't know why it happens. I created docker-machine with this command: docker-machine create --driver virtualbox --virtualbox-share-folder $(pwd) dev Now, I run docker-compose from django-cookiecutter template: docker-compose -f local.yml build and then docker-compose -f local.yml up From this moment I have that error from django: ... django_1 | PostgreSQL is available django_1 | python: can't open file 'manage.py': [Errno 2] No such file or directory project_django_1 exited with code 2 Also when I used docker-compose -f local.yml exec <here_id_container> django sh to check if any files are there, folder app is empty. Any clues? -
How to render multiple times to same template in a single function block
I want to render multiple times in each if statement to same template. But in the HTML template it's only taking the last rendered statement. I passed the context in the form of dictionary in the return render statement. views.py if not match : #messages.info(requests,'Invalid') return render(requests, 'validate/home1.html', {'title' : 'Invalid mail'}) if not country_code: return render(requests, 'validate/home1.html', {'title3' : 'Enter correct country code'}) if not pwd_match : return render(requests, 'validate/home1.html', {'title1' : 'Enter password again'}) if not phone : return render(requests, 'validate/home1.html', {'title2' : 'Enter 10 digit number'}) home1.html <form id="waterform" method="post" autocomplete="off"> {% csrf_token %} <div class="formgroup" id="name-form"> <label for="name">Country Code*</label> <input type="text" id="name" name="name" required /> </div> <div> <p style="color: red; margin-left: 10px">{{ title3 }}</p> </div> <div class="formgroup" id="email-form"> <label for="email">Your e-mail*</label> <input type="text" id="email" name="email" required /> </div> <div> <p style="color: red; margin-left: 10px">{{ title }}</p> </div> <div class="formgroup" id="email-form"> <label for="password">Your password*</label> <input type="text" id="pwd" name="pwd" required /> </div> I want to display each condition (title, title1, title2) which satisfies the if blocks. -
Problem in Django 2.2 with Debug=True on Ubuntu
I am trying to run a project in Django 2.2 with Debug=True on Ubuntu but I get this error in python manager.py runserver: TypeError: 'module' object is not iterable does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import error. This is /myparentapp/urls.py: from django.conf.urls import include, url from django.contrib import admin from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'', include('moeaforhdlweb.urls')), url(r'^admin/', admin.site.urls), url(r'^tinymce/', include('tinymce.urls')) ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This is /mychildapp/urls.py: from django.conf.urls import url from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^help/$', views.help, name='help') ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) I test this project on Windows 10 and it works perfectly, but not on Ubuntu. Besides, if I comment this line: url(r'', include('moeaforhdlweb.urls')) it works. Any help will be grateful, thanks a lot. -
Define blueprints grouping objects in Django
Django modelling question: I'm writing a manufacturing e-commerce site. We have an inventory of all components and we want to define blueprints for products that we could build using those components. How could I model that? Say for example I have a class AtomicComponent class AtomicComponent(models.Model): component = models.CharField(max_length=255) length = models.IntegerField(blank=True, null=True) thickness = models.IntegerField(blank=True, null=True) colour = component = models.CharField(max_length=255) quantity = models.IntegerField(blank=True, null=True) +----+------------+--------+-----------+--------+----------+ | id | Component | length | thickness | colour | quantity | +----+------------+--------+-----------+--------+----------+ | 45 | table-legs | 80 | 3 | white | 90 | | 46 | table-tops | 100 | 3 | white | 25 | | 47 | bolts | 1 | null | null | 3000 | +----+------------+--------+-----------+--------+----------+ How could I specify blueprints like: ikea-table: 4x(id=45) + 1x(id=46) + 4x(id=47) Trying to find a way so that the product could have a relationship with specific objects so that when a customer tries to order a table, it would check if all the components are available. -
Transfer all related models to different user in Django
In my django 1.8 app I can get all linked objects from other models of a user with user._meta.get_fields(). I now want to update/transfer all linked objects to point to an admin user. This is what I've tried: In [6]: from danube.people.models import Profile In [7]: admin = Profile.objects.get(id=1000) In [8]: user = Profile.objects.get(id=1002) In [9]: userData = user._meta.get_fields() In [10]: for item in userData: ...: extModel = item(related_model=admin) ...: # extModel = item(related_model_id=1000) ...: extModel.save() ...: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-10-aa9ee22a4e75> in <module>() 1 for item in userData: ----> 2 extModel = item(related_model=admin) 3 extModel.save() 4 TypeError: 'ManyToOneRel' object is not callable How can I overcome the TypeError: 'ManyToOneRel' object is not callable Error? -
authenticating client in multiple APIs
How to authenticate client when there is more than one API (obviously in all of them) and these APIs are using different authentication methods (token, session, ...) I need a general idea any help would be awesome. -
Authenticating user in websocket connections
I am trying to build a basic chat app with Django as backend. I am using WebSockets after the user logs in. However, I am not able to figure out a good way to authenticate the user. I was thinking about using Tokens but there doesn't seem to be a good way to send it from a javascript client to the server. Also, I also saw the implementation to authenticate on the first received message given here, however, it doesn't seem to be a great solution due to the following reasons: We have to accept the WebSocket connection with I'm pretty sure has some overhead. It doesn't seem to be much secure as for example if the client never sends the 1st message which is supposed to authenticate, the connection remains open for a long time and that behavior can be exploited to bring down the server by opening thousands of connections together. So is there any better way to implement authentication with WebSockets? For reference, I have tried the 2nd and 3rd method given here although couldn't figure out what to do at client end in the 2nd one. Also, it's not a full-stack app that I am building. … -
Django forms is not valid
my page html : resrver salle ! <form> {% csrf_token %} {{ form.as_p }} <input type="submit" value="reserver"> </form> views .py : def reserversalle(request , id): form= ReserverSalle(request.POST or None) print(form) if form.is_valid(): print("gooddd") context= { 'form' : form , } return render(request,'registration/reserversalle.html', context) forms.py : class ReserverSalle(forms.Form): nomsalle = forms.CharField(required=True , widget=forms.TextInput) motifresa = forms.CharField(required=True , widget=forms.TextInput) datedebut = forms.DateField( initial="2019-06-21", widget=forms.SelectDateWidget(years=YEARS)) heuredebut = forms.TimeField( initial='00:00:00') heurefin = forms.TimeField( initial='00:00:00') hello i try to submit my form but my form is not valid please i need some help -
Django Trigram search with rankings across multiple models
I'm trying to create an aggregated search result across multiple fields in multiple models and return a result ordered by rank. I can figure out each of these things on one model, but not merging the results from multiple models. One method I envision working is to take the weighted Trigram score for each record, append it to the record, and then sort by that score once the records from each search are combined in a list. How would I go about retrieving the weighted score for each record? Here's the code I'm working with: q = "search query" # ie "honey" A = 1.0 B = 0.4 C = 0.2 D = 0.1 total_weight = A + B + C + D trigram = A/total_weight * TrigramSimilarity('name', q) + \ B/total_weight * TrigramSimilarity('brand__name', q) + \ B/total_weight * TrigramSimilarity('description', q) + \ D/total_weight * TrigramSimilarity('category__name', q) results = Product.objects.annotate( similarity=trigram ).filter(similarity__gt=0.1).order_by('-similarity') This code works fine, in that it returns a ranked result within the model Product, and I can produce similar results in other models. So my main question is: How can I show ranked Trigram similarity results from multiple models, ordered by their rank regardless of what model … -
how to upload image at google cloud storage using app engine in django rest framework?
install pip install django-google-cloud-storage Configuration On your django settings.py file you need to add the following settings GOOGLE_CLOUD_STORAGE_BUCKET = '/your_bucket_name' # the name of the bucket you have created from the google cloud storage console GOOGLE_CLOUD_STORAGE_URL = 'http://storage.googleapis.com/bucket' #whatever the ulr for accessing your cloud storgage bucket GOOGLE_CLOUD_STORAGE_DEFAULT_CACHE_CONTROL = 'public, max-age: 7200' # default cache control headers for your files And finally declare the file storage backend you will use on your settings.py file DEFAULT_FILE_STORAGE = 'django_google_cloud_storage.GoogleCloudStorage' but not working -
Update only specific fields
//views def newEnroll(request): GradeYear = request.POST.get['customers'] payment = request.POST.get['paymentID'] pending = "Enrolled" update = StudentUser.objects.filter(PaymentTypes=payment,pending=pending,Grade_Year=GradeYear) update.Grade_Year = ([GradeYear]) update.PaymentTypes = ([payment]) update.Request = ([pending]) return render(request, 'accounts/pending.html') //model class StudentUser(models.Model): Grade_Year = models.CharField(max_length=500, null=True, blank=True) Subjects = models.CharField(max_length=500, null=True, blank=True) SectionID = models.ForeignKey(Section, related_name='+', on_delete=models.CASCADE, null=True, blank=True) CourseID = models.CharField(max_length=500, null=True, blank=True) PaymentTypes = models.CharField(max_length=500, null=True, blank=True) RoomID = models.ForeignKey(Room, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Request = models.CharField(max_length=500, null=True, choices=Pending_Request,blank=True) I'm getting this error 'method' object is not subscriptable -
How to create an image from binary data returned by a request to store and use in Django app?
I am using the "Dropbox API Explorer - get_thumbnail" to get a thumbnail of images stored in Dropbox folders. The response returns a blob in binary. I am attempting to create a image file to store as an imagefield on my django app's database. I followed this to create the image https://2.python-requests.org//en/latest/user/quickstart/#binary-response-content. # get_thumbnail request url = "https://content.dropboxapi.com/2/files/get_thumbnail" # product_path is a variable storing path from list_folder new_product_path = "{\"path\":\"/%s\"}" %(product_path) headers = { "Authorization": "Bearer <api_token_ommitted>", "Dropbox-API-Arg": new_product_path } r = requests.post(url, headers=headers) thumbnail = Image.open(BytesIO(r.content)) # album is foreign key for Album model product = Product.objects.create(album=album, name=converted_name, image=converted_url, thumbnail=thumbnail) print('Product has been created!') print(r.content) b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00C\x00\x06\x04\x05\x06\x05\x04\x06\x06\x05\x06\x07\x07\x06\x08\n\x10\n\n\t\t\n\x14\x0e\x0f\x0c\x10\x17\x14\x18\x18\x17\x14\x16\x16\x1a\x1d%\x1f\x1a\x1b#\x1c\x16\x16 , #&\')*)\x19\x1f-0-(0%()(\xff\xdb\x00C\x01\x07\x07\x07\n\x08\n\x13\n\n\x13(\x1a\x16\x1a((((((((((((((((((((((((((((((((((((((((((((((((((\xff\xc0\x00\x11\x08\x00$\x00@\x03\x01"\x00\x02\x11\x01\x03\x11\x01\xff\xc4\x00\x1f\x00\x00\x01\x05\x01\x01\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\xff\xc4\x00\xb5\x10\x00\x02\x01\x03\x03\x02\x04\x03\x05\x05\x04\x04\x00\x00\x01}\x01\x02\x03\x00\x04\x11\x05\x12!1A\x06\x13Qa\x07"q\x142\x81\x91\xa1\x08#B\xb1\xc1\x15R\xd1\xf0$3br\x82\t\n\x16\x17\x18\x19\x1a%&\'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz\x83\x84\x85\x86\x87\x88\x89\x8a\x92\x93\x94\x95\x96\x97\x98\x99\x9a\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xff\xc4\x00\x1f\x01\x00\x03\x01\x01\x01\x01\x01\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\xff\xc4\x00\xb5\x11\x00\x02\x01\x02\x04\x04\x03\x04\x07\x05\x04\x04\x00\x01\x02w\x00\x01\x02\x03\x11\x04\x05!1\x06\x12AQ\x07aq\x13"2\x81\x08\x14B\x91\xa1\xb1\xc1\t#3R\xf0\x15br\xd1\n\x16$4\xe1%\xf1\x17\x18\x19\x1a&\'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x92\x93\x94\x95\x96\x97\x98\x99\x9a\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xff\xda\x00\x0c\x03\x01\x00\x02\x11\x03\x11\x00?\x00\xfa\x16\x8a\xc3_\x15h\xcd\x1c\x8c\xb7\xa8v\x9cm\xc1\x05\xbe\x80\xf5\xa7\xc3\xe2m\x1eB\xa0\xea6\xf1\x92\xa5\xb1+l \x0e\xb9\'\x8f\xd6\xbc\xa5R\r\xd93\xdcxj\xd1Wp\x7fs6h\xacx|K\xa2L3\x0e\xabg \xeb\xf2\xc9\x9a\xcd\xd6|w\xa3i\x9at\xd7m$\xb3\xac\\\x95\x8a2I\xa6\xe7\x14\xec\xd8G\rZ[A\xfd\xc7UEs\xd6\x9e0\xd1n,\x92\xe5\xaf\x16\x10\xc8\x1fd\xa0\x86\xc7\xb0\xefV-\xfcO\xa2\xcd\x07\x9a\xba\x9d\xa0PpCH\x14\x83\xee\x0f\xf3\xe9B\x9c_Pxj\xd1\xde\x0f\xeef\xcd\x15\x917\x894h@2j\x96x<\xe5d\r\xc7\xe1\x9ab\xf8\xa7B.\xe85{-\xeb\xc1\x1eg"\x9d\xd1>\xc2\xae\xfc\xaf\xeeg\xc2\xd3^\xddN\x00\x9a\xe2g\x00`\x06rq@\xbc\xb8\xe33\xc8p0>c\xd3\xd2\xa0\xa2\xbd\xbeT\xba\x18\xacMT\xef\xcc\xfe\xf3F\xcbX\xbb\xb4\x04C)Q\x90\xdcz\xd5\xa4\xf1>\xa6\xa1\xc7\xda\\\xab\x8c2\x93\xc1\xe75\x89EC\xa5\x07\xbaGB\xcc\xb1)[\x98\xd9\xb9\xf1\r\xf5\xc3\xc7#\xce\xfb\xd3\xa6\x0e1U\xe7\xd6/\'bd\x99\xc9 \x83\xcfPz\xd6u\x14\xd5(-\x90\xdeg\x89\x7fh\xb35\xed\xc4\xbc4\xcf\x8fL\xd4+,\x8ar\xae\xc0\xe7<\x1ae\x15VH\xe6\x9e&\xac\xdf4\xa4\xc2\x8a(\xa6b\x14QE\x00\x14QE\x00\x14QE\x00\x7f\xff\xd9' -
Lists are not currently supported in HTML input. When attempting to upload multiple photos through the django rest framework in one click
I am trying to use the django rest framework to carry out multiple POST events once I point it to a directory. The idea is that I will specify the country and a directory containing multiple images. Then the API must go to the directory, and post each image in that directory to the database along with more details available from the filename of each image. Following some pointers from the internet, I managed to build out a little model and framework that looks like it could work except for one thing. The default rest API page doesn't support the HTML input of lists. I would like to know if my time will be better spent trying to fit the API page to my requirements or if I should go about building my own HTML interface. Or to be more direct What is the fastest (and simplest) way for me to upload multiple images (each image is a separate instance in the db) into a database using Django and the Django REST Framework? models.py: from django.db import models # Create your models here. class Tiles(models.Model): image = models.ImageField(blank=True, null=True) lat = models.FloatField(blank=True, null=True) lng = models.FloatField(blank=True, null=True) country = models.CharField(blank=True, … -
Show user GitHub's repositories on a webpage
What the best way, what the simple way if I want to show all https://api.github.com/users/serhii73/repos user GitHub's repositories on a webpage? -
pre_save signal using tastypie api not allowing me to access "instance" field
I'm working on this small Django project in which I'm using pre_save signals to update a table in which I save the cumulative value of a certain quantity, whenever a new Transaction is created or modified, the corresponding value in the table is updated. If i add a transaction manually from the admin page everything works fine but today i tried to create a new Transaction through a POST request using tastypie generated api, the problem is that when my update_total_if_changed function is called by the signal, the instance parameter is /api/v1/transaction/ instead of the actual python object, therefore i get "Transaction has no FieldName." since the instance actually points to the tastypie entrypoint instead of the newly created object. Below you can see the code of my signal @receiver(pre_save, sender=Transaction) def update_total_if_changed(sender, instance, **kwargs): try: obj = sender.objects.get(pk=instance.pk) except sender.DoesNotExist: #new transaction tw, new = TotalWaste.objects.get_or_create(depot=instance.depot, waste = instance.waste) tw.total += instance.quantity tw.save() else: if not obj.quantity == instance.quantity: # Field has changed tw, new = TotalWaste.objects.get_or_create(depot=instance.depot, waste = instance.waste) tw.total = tw.total + instance.quantity - obj.quantity tw.save() -
Django rest framework upload multiple images
I have 2 model The Problem is , I am trying implement Multiple file uploaded and from front end I am sending like postimage: [object File] Problem is I am not getting the postimage in my serializer. Please help me Python with Django Rest Framework My Model class Post(models.Model): """ Model for the Post""" title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique=True, editable=False)`enter code here` description = models.TextField(blank=True, null=True) photo = models.ImageField(blank=True, null=True, upload_to='media/') user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='posted_user' ) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class PostImages(models.Model): """ Model for handling multiple images for Postings""" post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='post' ) image = models.ImageField(blank=True, null=True, upload_to='media/post_images/') My View class PostPublishView(generics.ListCreateAPIView): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) queryset = Post.objects.all() serializer_class = serializers.PostManageSerializer def get_queryset(self): """ return objects for the current auth user""" return self.queryset.filter(user=self.request.user).order_by('-title') def perform_create(self, serializer): """ Create newpost""" post = serializer.save(user=self.request.user) My Serializer : class PostImageSerializers(serializers.ModelSerializer): id = serializers.IntegerField(required=False) post = serializers.ImageField(required=False, use_url=True, max_length=None, allow_empty_file=True) class Meta: model = PostImages fields = ('id','post') class PostManageSerializer(serializers.ModelSerializer): user = serializers.StringRelatedField() postimage = PostImageSerializers(many=True) class Meta: model = Post fields = ( 'title', 'user', 'slug', 'postimage', 'description', 'photo', 'active') def create(self, validated_data): # task = Post.objects.create(**validated_data) images_data … -
How does django authentication work internally?
I was looking under the hood, on how the different authentication systems work in django. I have a basic idea that in case of session authentication, sessions are stored some where in the session models. It is easier to understand token authentication, as in token authentication, tokens are created which are in turn stored in the frontend. But, how is the login saved when the user goes for basic authentication or session authentication? When using basic authentication, assuming the User that is imported in from django.contrib.auth.models import User, we can use the decorator login_required, but how exactly does it work?