Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
(Beginner) Error when loading 'python manage.py runserver' on Visual Studio Code part of Django project
I'm fairly new to this and am currently learning Django on Visual Studio Code using a Mac. I'm getting a few error and was wondering if someone could help. When I try to run my project through virtualenv I get the following error in the Terminal: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/username/Desktop/VSC/test/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/username/Desktop/VSC/test/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/Users/username/Desktop/VSC/test/lib/python3.8/site-packages/django/core/management/base.py", line 392, in check all_issues = self._run_checks( File "/Users/username/Desktop/VSC/test/lib/python3.8/site-packages/django/core/management/base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "/Users/username/Desktop/VSC/test/lib/python3.8/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/Users/username/Desktop/VSC/test/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/Users/username/Desktop/VSC/test/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/Users/username/Desktop/VSC/test/lib/python3.8/site-packages/django/urls/resolvers.py", line 407, in check for pattern in self.url_patterns: File "/Users/username/Desktop/VSC/test/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/username/Desktop/VSC/test/lib/python3.8/site-packages/django/urls/resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/username/Desktop/VSC/test/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/username/Desktop/VSC/test/lib/python3.8/site-packages/django/urls/resolvers.py", line 581, in urlconf_module return import_module(self.urlconf_name) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", … -
How to use a variable from one function in the other function in Django Views
I have 2 functions: The 1 function checks the URL for scheme: def checkurl(self): if request.method == 'POST' and 'url' in request.POST: url = request.POST.get('url', '') if not url.startswith('http://') and not url.startswith('https://'): url = "https://" + url return url The 2 function should use the url variable. But it says "name 'url' is not defined". Here is the second function: def tests(request): ################################################## # URL Parse: netloc, scheme ################################################## x = datetime.datetime.now() time = x.strftime("%Y-%m-%d-%H-%M-%S") if request.method == 'POST' and 'url' in request.POST: headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0'}#headers # Set Width and Height width_get = request.POST.get('width', '') height_get = request.POST.get('height', '') if width_get is not None and width_get != '': width = width_get else: width = 1600 if height_get is not None and height_get != '': height = height_get else: height = 1000 if url is not None and url != '': url_parsed = urlparse(url) scheme = url_parsed.scheme netloc = url_parsed.netloc if netloc.startswith('www.'): netloc = netloc.replace('www.', '') image_path = "media/" + netloc + "-" + time + ".png" shot_path = "/media/" + netloc + "-" + time + ".png" path = "C:/WebDrivers/chromedriver.exe" driver = webdriver.Chrome(path) driver.get(url) driver.set_window_size(width, height) driver.save_screenshot(image_path) screenshot = image_path driver.quit() var_dict … -
How to dynamically display checkboxes in form?
I want to display checkbox options based on queries from the view. For instance, this is my current code: view: def new_role_task(response, id): ... query = Query.objects.filter(id=id) if response.method == 'POST': form = Form(response.POST) if form.is_valid(): .... return redirect(f'/...') else: form = Form() return render(response, ...html', {'form':form, ...}) form: FAVORITE_COLORS_CHOICES = [ ('blue', 'Blue'), ('green', 'Green'), ('black', 'Black'), ] class Form(forms.Form): checkbox_fields = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=FAVORITE_COLORS_CHOICES, ) ... Instead of FAVORITE_COLORS_CHOICES, I want to use queries that I would make from the view itself that will be dynamic depending on the params passed to the page. For instance, I come from Rails and within rails, you can accomplish this on the front or backend by doing: Front: <%= collection_check_boxes(:post, :author_ids, Author.all, :id, :attribute) %> This would then display all records from the Author model. Or you can define Author like @authors = Author.where(ids: [1,2,3]) <%= collection_check_boxes(:post, :author_ids, @authors, :id, :attribute) %> This would then display all Authors from the query that match. I assume for Django, all I need to do is get my query into [('')] format and then somehow get that to override the form.py file? What is the method on accomplishing this? I guess there are … -
Failing to Upload JSON Postgresql Database Backup to New Django Heroku App via loaddata
I am upgrading an old app to a new app on Heroku (Python 3.7 Django 2.2). Locally, I was able to successfully upload json database backup fixture and it works great. I've created a new app with no problems, but when I upload the database backup fixture to the new Heroku app the process just ends after several seconds and the data is not uploaded. I am given no errors. This is my command: heroku run python manage.py loaddata db-back1.json The response: Running python manage.py loaddata db-back1.json on ⬢ app-name... up, run.6706 (Free) Shortly, after it just ends the process with no error. Notes and things I've tried: My json fixture file is 300mb, so it's quite large. It took several minutes to upload on my local instance. Do I need to upload to S3 first? I've upgraded the app to standard on heroku and and the url of the database has been updated correctly and is set to the right database, though the response keeps including (Free). To be clear, the Heroku app is working successfully, it just has no data. Further, I was able to get the app and dataload working successfully on my local version. This leads … -
I/O operation on closed file in django with 'ImageKit'
In my django project I am using ImageKit to size my profile images. I have a model with these fields: pasfoto = models.ImageField(upload_to='images/', blank=True) pasfoto_thumbnail = ImageSpecField(source='pasfoto', processors=[ResizeToFill(150, 200)], format='JPEG', options={'quality': 60}) ImageSpecField is imported from Imagekit. I am saving my images on amazon-S3 via Django-storages When I upload an image via the template (edit form) rendered via an UpdateView it shows the detail template after success. The pasfoto_thumbnail is used in this template, that is rendered via a class based DetailView in Django. In this case I see an error 'I/O operation on closed file'. But after a browser refresh is shows the right image. What is happening and how could I solve this issue? -----DEBUG MESSAGE ------- error message from django debug -
I want each item of these lists to be printed side by side in Django template
context = {'list1':list1,'list2':list2} return render(request,"template.html",context) this is the last two lines of my views.py file I want each item from list1 and list2 to be printed side by side in a table what I tried is {% for item1 in list1 %} {% for item2 in list2 %} <tr> <td>item1</td> <td>item2</td> </tr> {% endfor %} {% endfor %} but it is printing all values of list2 to just for single object of list1 -
Python csv reader for row in reader gives syntax error
New to Django/Python. I need to write an import script for a CSV file to seed some data (not using fixtures, did that already as that is JSON based and not CSV). This works: import csv from datetime import datetime from django.utils.timezone import make_aware from django.core.management.base import BaseCommand from chatterbox.models import Organisation, Course, Student class Command(BaseCommand): def handle(self, **options): CSV_PATH = './students_AEKI.csv' Student.objects.filter(organisation__name__exact="AEKI").delete() with open(CSV_PATH) as file: file.readline() # skip the header csv_reader = csv.reader(file, delimiter=',') org = Organisation.objects.filter(name='AEKI') for row in csv_reader: _, Student.objects.get_or_create( first_name=row[0], last_name=row[1], email=row[2], organisation=org[0], enrolled=row[4], last_booking=row[5], credits_total=row[6], credits_balance=row[7], ) This does NOT work: import csv from datetime import datetime from django.utils.timezone import make_aware from django.core.management.base import BaseCommand from chatterbox.models import Organisation, Course, Student class Command(BaseCommand): def handle(self, **options): CSV_PATH = './students_AEKI.csv' Student.objects.filter(organisation__name__exact="AEKI").delete() with open(CSV_PATH) as file: file.readline() # skip the header csv_reader = csv.reader(file, delimiter=',') org = Organisation.objects.filter(name='AEKI') for row in csv_reader: enrolled_utc = datetime.strptime(row[4], '%Y-%m-%d') last_booking_utc = datetime.strptime((row[5], '%Y-%m-%d') _, Student.objects.get_or_create( first_name=row[0], last_name=row[1], email=row[2], organisation=org[0], enrolled=enrolled_utc, last_booking=last_booking_utc, credits_total=row[6], credits_balance=row[7], ) Syntax error at the "_". I need to do some manipulation (eg like adding timezone to date fields) on data before creating it in the table. So what is wrong with the 2nd version? -
DRF reverse for 'user-create' not found
Got a view named MyUserCreate and in app/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'api/users^$', views.MyUserCreate.as_view(), name='user-create'), ] In app/tests.py self.create_url = reverse('user-create') Running python manage.py test Gives this error Traceback (most recent call last): File "C:\Users\tiago\Desktop\letsgo\COVID19-be\django_server\user\tests.py", line 13, in setUp self.create_url = reverse('user-create') File "C:\Users\tiago\Desktop\letsgo\venv\lib\site-packages\django\urls\base.py", line 87, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "C:\Users\tiago\Desktop\letsgo\venv\lib\site-packages\django\urls\resolvers.py", line 677, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'user-create' not found. 'user-create' is not a valid view function or pattern name. What can I do to solve it? -
How to compare the fields taken through a form to those of a model created in django?
I have created a Customer model in my models and registered it on admin.py. Then I made a login form and took field values using get method.Now I want to iterate through all the objects of customer created and find the one with those two matching fields.I have made a login function in the views.py. This is my model:class Customer(models.Model): FirstName = models.CharField(max_length=100, default="") LastName = models.CharField(max_length=100, default="") address = models.CharField(max_length=500, default="") EmailId = models.CharField(max_length=120, default="") PhoneNo = models.CharField(max_length=12, default="") Password = models.CharField(max_length=120, default="") And this is my function: def login(request): if request.method=="POST": FirstName= request.POST.get('FirstName', '') Password = request.POST.get('Password', '') for customer in Customer.objects.all(): if FirstName==customer.FirstName and Password==customer.Password: return redirect ( 'customer-home') return render(request, 'customer/login.html') I'm not getting the desired results. -
Django Add new record error duplicate key value violates unique constraint "" Django Id doesn't sync with database
I developed a Django Application and it was working correctly, until I did a data migration to the database created by django migration, I migrated the data using an sql script and Pgadmin. Now I have the database full with records but when I am trying to add new record using django form I got the below error duplicate key value violates unique constraint "learningcenters_partnerorganization_pkey" DETAIL: Key (id)=(1) already exists. taking into consideration that the available id for this table is 10. Model: class SLPAcademicRound(models.Model): name = models.CharField(max_length=45, unique=True, verbose_name=_('Academic Round Name')) code = models.CharField(max_length=5, unique=True, verbose_name=_('Code')) cycle = models.ForeignKey( SLPCycle, blank=False, null=True, verbose_name=_('SLP Cycle/SLP Cycle'), on_delete=models.CASCADE, ) learning_center = models.ForeignKey( LearningCenter, blank=False, null=True, verbose_name=_('Learning Center'), on_delete=models.CASCADE, ) round_date_start = models.DateField( blank=True, null=True, verbose_name=_('SLP Round Start Date') ) round_date_end = models.DateField( blank=True, null=True, verbose_name=_('SLP Round End Date') ) current_round = models.BooleanField( blank=True, null=True, verbose_name=_('Current Round') ) View: class AddSLPAcademicRoundView(LoginRequiredMixin, GroupRequiredMixin, CreateView): template_name = 'bootstrap4/common_form.html' form_class = SLPAcademicRoundForm queryset= SLPAcademicRound.objects.all() group_required = ["LearningCenterManager"] def get_absolute_url(self): return reverse("slp:slp_academic_round_list") def form_valid(self, form): print((form.cleaned_data)) form.save(self.request) return super(AddSLPAcademicRoundView, self).form_valid(form) def get_form_kwargs(self, *args, **kwargs): kwargs = super().get_form_kwargs(*args, **kwargs) kwargs['user'] = self.request.user return kwargs -
How can i make a sing-in (login) in react native from django rest framework api?
I have made an api in django rest framework which already returns a token when entering a certain link, and the links require authentication too. I'm going to use react native for the app (mobile app), the point is ... I don't know how to do the sing-in in react navite using the django api rest. I have searched the internet a lot but I have not found concrete information that relates django with react native and singin. The truth is that I am new to react native and I don't know what to look for specifically to make the singin. Which are the steps to follow? Please, if you can help me? I am frustrated with so much searching. Thank you. -
Test creation of a custom user using DRF
The goal is to test creating a new custom user using APITestCase. In models.py got two new classes inheriting from AbstractBaseUser and BaseUserManager, respectively class MyUser(AbstractBaseUser): objects = MyUserManager() class Meta: db_table = 'user_entity' user_id = models.AutoField(primary_key=True) #username = models.CharField(max_length=USERNAME_MAX_LENGTH, unique=True, validators=[validators.validate_username]) username = models.CharField(max_length=20, unique=True) password = models.CharField(max_length=256) first_name = models.CharField(max_length=25) last_name = models.CharField(max_length=25) email = models.EmailField(verbose_name='email', max_length=100, unique=True) last_access = models.DateField(default=datetime.date.today) creation_date = models.DateTimeField(default=timezone.now) last_update = models.DateField(default=datetime.date.today) user_type = models.IntegerField() is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name', 'user_type'] def __str__(self): return str(self.user_id) + " (%s)" % str(self.email) def has_perm(self, perm, obj=None): return self.user_type == 0 def has_module_perms(self, app_label): return True and class MyUserManager(BaseUserManager): def _create_generic_user(self, email, username, password, first_name, last_name, user_type): if not username: raise ValueError("Username cannot be empty") if not email: raise ValueError("Email cannot be empty") if not first_name: raise ValueError("First name cannot be empty") if not last_name: raise ValueError("Last name cannot be empty") if not password: raise ValueError("Password cannot be empty") user = self.model( username=username, first_name=first_name, last_name=last_name, email=self.normalize_email(email), user_type=user_type, is_staff=user_type == 0, is_active=False ) user.set_password(password) user.save(user=self._db) return user def create_user(self, email, username, password, first_name, last_name): return self._create_generic_user(email, username, password, first_name, last_name, 2) def create_admin(self, email, username, … -
How to generate shareable links in django
Example : localhost/profile - private url with login authentication for above link need to create shareable link like : localhost/h45n64n56nm56 when i'm shared above link to public peoples then public peoples can able click on that url and see the profile how to done this in django ?? (how to create private url to public url and access the public urls in django) -
How to use bulk_create in batches (is_slice) and avoid duplicate PK error
I am using bulk_create generate multiple records from an ajax json POST. In the docs, the guidance states: If you want to insert objects in batches without evaluating the entire generator at once, you can use this technique as long as the objects don’t have any manually set primary keys It gives this example: from itertools import islice batch_size = 100 objs = (Entry(headline='Test %s' % i) for i in range(1000)) while True: batch = list(islice(objs, batch_size)) if not batch: break Entry.objects.bulk_create(batch, batch_size) However, when I run this exact code I get a unique primary key constraint error: django.db.utils.IntegrityError: duplicate key value violates unique constraint 'entry_pkey' This appears to be because the code loops over the same set of objects infinitely (while True) and does not move the islice start and stop values along the list. Are the docs wrong? Have I misinterpreted the code/could it be something else I am missing here? I am using PostgreSQL. -
Passing variable from template to view in django
How can I pass value from django templates to views.py?? I have written Index.html having view function index() now I have created another view function places() in which I need to pass the value of p tag from Index.html file. It doesn't include any POST or GET method. Index.html {% block content %} <div > {% for key,values in image_data.items %} <div class="divtag"> <!-- {{key}} --> <a href="Places" class="tag" > <img src="{{values}}"/> <div class="middle"> <p class="center" data={{key}}>{{key}}</p> </div> </a> </div> {% endfor %} </div> {% endblock %} Views.py #main index view def index(request): img = MyModel.objects.all() template = loader.get_template('Index.html') image_data = {} for obj in img: image_data[obj.image_name] = obj.image print("-----------------------------------------------------------------") return render(request,'Index.html',{"image_data" : image_data}) # where i need to return value from template def places(request): name = 'Paris' #i want name value from p tag in html file if(name == 'Paris'): img = Paris.objects.all() template = loader.get_template('Index.html') image_data = { 'images' : [obj.image for obj in img], 'name' : [obj.image_name for obj in img], 'description' : [obj.image_description for obj in img] } image_data_zip = zip([obj.image for obj in img],[obj.image_name for obj in img],[obj.image_description for obj in img]) print("-----------------------------------------------------------------") return render(request,'Paris.html',{"image_data_zip" : image_data_zip}) else: img = Germany.objects.all() template = loader.get_template('Index.html') image_data … -
Trigger is not working Django REST API Test Case
I used the Django REST framework to build API and written a Trigger in PostgreSQL. basically trigger function checks the value in the second database and if the value presents then it gives exception and also removes the row from the first table. when I test this in the Django REST framework the data is not inserted and the trigger doesn't work so I end up doing the duplicate entry. so is there any way to insert data in database while testing? -
How to create Article Detail models in Django?
I have problem when i try to create article detail on my web app. Stuff like that: class ArticleDetail(models.Model): title = models.CharField(default='title', max_length=121) image = models.FileField(upload_to='/uploads') content = models.TextField() But i don't know how to render to template. Example: # THIS IS TITLE OF ARTICLE # image_1 # Content # image_2 # continue content # format code (just like markdown) # continue content How i can implement models for this? Thanks for help. -
How To Insert Value in CKEDITOR using AJAX in Django?
I am using AJAX request to send form data back in the views.py but I am not able to save CKEDITOR form. First, I am inserting some value to the CKEDITOR using setData method Here is my AJAX Code function showComnt(){ var getcm ="<blockquote>" + $("#cmntbysuraj").text()+ "</blockquote> <br> <hr> <br> <br>" CKEDITOR.instances['id_content'].setData(getcm); }; function SendComment(){ var currentURL= window.location.href.toString() var value = CKEDITOR.instances['id_content'].getData() var token = '{{ csrf_token }}'; $.ajax({ type: "POST", url: currentURL , data: { csrfmiddlewaretoken: token, content:value, }, dataType:'json', success: function(data){ if(data){ } } }); }; In my views.py. I am trying to save the form but it is not valid. How can I save the form ..... .... .... getCmntfromUser = request.POST.get("comment") form= CommentPage(request.POST or None) if form.is_valid(): print('form is valid') instance = form.save(commit=False) instance.user = user instance.post_id = postId instance.save() ...... ..... .... Note- When I print(form) , I got the whole page in HTML format. I don't understand why this is happening. -
Django wrong username, password for custom user model
I have created custom user model by using 'OneToOneField'. I have created the signup and signin system but only signup is working and I am able to register new user but, when I try to signin using that created user, Django is not allowing me to signin by showing my custom message 'Username or password is wrong'. I have double checked the username, password and it is correct but still Django is not allowing me to signin. Here are my codes. models.py class Vendor(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) phone_number = models.CharField(max_length = 12, blank = True) forms.py class SignInForm(forms.Form): username = forms.CharField(max_length = 20, widget = forms.TextInput(attrs = {'class': 'form-control', 'placeholder': 'Username'} )) password = forms.CharField(max_length = 15, widget = forms.PasswordInput(attrs = {'class': 'form-control', 'placeholder': 'Password'} )) views.py form = self.form(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username = username, password = password) if user: if user.is_active: login(request, user) return redirect('dashboard') else: messages.error(request, 'Your email address is not verified. Please verify it') else: messages.error(request, 'Username or password is wrong') -
Django: How to add ManyToMany Value in form from other Model
So i have 2 Models. Ingredient and recipe. I want to add like a plus button with a popup that will open a Modal on this page, that will let me create an Ingredient. I don't want that the User has to create ingredients and then the Recipe. My Models: class Recipe(models.Model): name = models.CharField(max_length=100, blank=False) ingredient = models.ManyToManyField('Ingredient',) for_persons = models.IntegerField(null=False) instruction = models.TextField(blank=True) def get_absolute_url(self): return reverse('Rezept-Detail', kwargs={'pk': self.pk}) class Ingredient(models.Model): name = models.CharField(max_length=100, blank=False) quantity = models.IntegerField(null=False, blank=False) UNIT_CHOICES = ( ("ML", "Milliliter"), ("L", "Liter"), ("KG", "Kilogramm"), ("PCK", "Packung"), ("P", "Portion"), ) unit = models.CharField( max_length=20, choices=UNIT_CHOICES ) def __str__(self): return self.name My Form: class RecipeForm(forms.ModelForm): class Meta: model = models.Recipe fields = ['name', 'ingredient', 'for_persons', 'instruction'] Someone know, how to tackle this? -
Excluding some values from raw query
I have made a raw query(for postgresql) that the list the songs required to be played on the requests. However, when I am unable to exclude the songs from this raw query which have been blocked in my SongsBlocked model. initial_query_string = '''select songs.id,songs.albumart,songs."albumartThumbnail", cpr.votes, is_requested from (select id,albumart, "albumartThumbnail" from (select song_id from core_plsongassociation where playlist_id in (%s))'''%pl_ids_tuple songs_request = Song.objects.raw(initial_query_string + ''' as sinpl left join songs on sinpl.song_id=id where explicit=False ) as songs left join (select song_id, bool_or(thirdpartyuser_id=%s) as is_requested from (select * from core_priorityrequests where client_id=%s and is_played=False ) as clpr left join core_priorityrequests_third_party_user on clpr.id=priorityrequests_id group by priorityrequests_id, song_id, ) as cpr on songs.id=cpr.song_id where songs.name ilike %s or songs.artist ilike %s limit %s offset %s''', [request.anon_user.id, restaurant.client.id,search_string,search_string,limit,offset,]) The SongsBlocked Model is as follows: class BlockedSongs(models.Model): client = models.ForeignKey('Client') user= models.ForeignKey(settings.AUTH_USER_MODEL) song = models.ManyToManyField('Song') playlists = models.ManyToManyField('Playlist', blank=True) Can anyone suggest the except query that I am missing here? -
Django rest framework different permissions on different projects for a user
In a project management application, a user is assigned multiple projects and can have different permissions on different projects. We tried implementing it using groups and permissions. The problem is that we didn't find a way to associate permissions with projects. We tried by extending groups model and assigning different groups to the user but in this case, when checking for permissions all the permission from all the groups is appended so no luck there as well. What is the better way to handle this? -
Unable to upload picture to s3 using boto on production
i have an endpoint from which I upload images to s3. Now the problem is that the code is not working on production server while upload from a local machine and the testing server is working fine. This is the error i get on production: Exception Type: HTTPClientError at /v3/file/ Exception Value: An HTTP Client raised and unhandled exception: 'module' object has no attribute 'wait_for_read' Api code: import boto3 from hireapp.settings import AWS_S3 from django.shortcuts import render from django.utils.crypto import get_random_string from .serializers import AdCategorySerializer class FileUpload(APIView): permission_classes = (IsAuthenticated, ) def post(self, request, format=None): img = request.data["file"] session = boto3.Session( aws_access_key_id=AWS_S3["AWS_ACCESS_KEY_ID"], aws_secret_access_key=AWS_S3["AWS_SECRET_ACCESS_KEY"], ) s3 = session.resource('s3') image_name = get_random_string(25) + img.name s3.Bucket(AWS_S3["AWS_STORAGE_BUCKET_NAME"]).put_object(Key='media/%s'%image_name, Body=img, ACL='public-read') #url to image image_url = "https://mobile.testapp.net/media/{image}".format(image=image_name) return Response(image_url,status=status.HTTP_200_OK) And this is part of stacktrace: *File "/home/irongate-server/irongate-server/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/irongate-server/irongate-server/local/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/home/irongate-server/irongate-server/local/lib/python2.7/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/home/irongate-server/irongate-server/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 477. response = self.handle_exception(exc) File "/home/irongate-server/irongate-server/local/lib/python2.7/site-packages/rest_framework/views.py" in handle_exception 437. self.raise_uncaught_exception(exc) File "/home/irongate-server/irongate-server/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 474. response = handler(request, *args, **kwargs) File "/home/irongate-server/irongate-server/hireapp/v3/views.py" in post 29. s3.Bucket(AWS_S3["AWS_STORAGE_BUCKET_NAME"]).put_object(Key='media/%s'%image_name, Body=img, ACL='public-read') File "/home/irongate-server/irongate-server/local/lib/python2.7/site-packages/boto3/resources/factory.py" in do_action 520. response = action(self, *args, **kwargs) File "/home/irongate-server/irongate-server/local/lib/python2.7/site-packages/boto3/resources/action.py" … -
Django websockets image upload binary get extension
I am trying to send image via javascript websockets as binary data var ws = new WebSocket('ws://127.0.0.1:8000/ws/message/'); var file = document.getElementById('ImageUpload').files[0]; console.log(file) ws.binaryType = "blob"; ws.send(file) Using Django channels I am receiving the binary data from channels.generic.websocket import WebsocketConsumer class Consumer(WebsocketConsumer): def connect(self): ..... ..... self.accept() def receive(self, text_data=None, bytes_data=None): if bytes_data: # doing some stuffs How can get the extension(.jpg/.png) of the image file form the binary data which I receive via websocket, can you pleas guide me some suggestion for this, it will be very helpful for me. Thanks in advance. -
multiple html form from a single form model in django
i need your assistance im building a school president vote tallying system the vote results are saved in the polls table as candidate id | pollingstationid | result | when capturing the results the html page will render the form for each candidate. for example if there are 3 candidates the html form will have 3 forms: candidate 1: result _______ candidate id 1001 pollingstationid 301 candidate 2: result _______ candidate id 1002 pollingstationid 301 candidate 3: result _______ candidate id 1003 pollingstationid 301 [submit button] the problem: when i click submit, its only saving the last form(i.e candidate 3) how do i get all three entries into the database each as a new row. views.py class candidatesview(AjaxFormMixin, View): form_class = pollsForm model = Polls template_name = 'app/candidates.html' def get(self, request): form = self.form_class() candidatesls = Candidates.objects.all() context = {'title':'polls','form' : form, 'candidates': candidatesls } #print(context) return render(request, self.template_name, context ) def post(self, request): form = pollsForm(request.POST) candidatesls = Candidates.objects.all() if form.is_valid(): print(form.cleaned_data['Result']) print(form.cleaned_data['Candidateid']) print(form.cleaned_data['PollingstationID']) form.save() messages.success(request,('Form submitted successfuly')) else: messages.warning(request,('nah!')) print(messages) context = {'title':'polls','form' : form, 'candidates': candidatesls, 'message':messages} return render(request, self.template_name, context) forms.py class pollsForm(forms.ModelForm): class Meta: model = Polls fields = ['Result', 'Candidateid','PollingstationID'] html (candidates.html) {% extends …