Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix the error cause when execute manage.py runserver command in Django?
I recently join with ongoing project which has done using Django framework and I am new to this framework. This code is not mine. When I run python manage.py runserver command I receive following error. I have done all the configuration asked in readme file. This is the local.py file try: from .base import * except ImportError: pass from configparser import RawConfigParser config = RawConfigParser() config.read('/etc/django_settings/hopster_settings.ini') SECRET_KEY = config.get('secrets', 'SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS += [ 'rest_framework_swagger', # to enable swagger documentation for rest api 'django_extensions', # for print db schemas ] DATABASES = { 'default': { 'ENGINE': config.get('database', 'DATABASE_ENGINE'), 'NAME': config.get('database', 'DATABASE_NAME'), 'USER': config.get('database', 'DATABASE_USER'), 'PASSWORD': config.get('database', 'DATABASE_PASSWORD'), 'HOST': config.get('database', 'DATABASE_HOST'), 'PORT': config.get('database', 'DATABASE_PORT'), } } SITE_ID = 1 STATIC_URL = '/static/' STATIC_NAME = 'hopster_static_cdn' MEDIA_NAME = 'hopster_media_cdn' STATICFILES_DIRS = [ os.path.join(os.path.dirname(BASE_DIR), "static"), # '/var/www/static/', ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), STATIC_NAME) # STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'images', 'static') # STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "english_vlog_static_cdn") # media files on local server MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), MEDIA_NAME) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', # convert rest output into json format by … -
"Redirect" user after right credentials with PyQt5
I made a Django API that returns if the user was logged successfully. I use that API result to log in the user in PyQt. My code is as follows: import json import sys import requests from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton, QLineEdit, QMessageBox, QLabel from PyQt5.QtCore import pyqtSlot from PyQtProject.request_login import querystring, headers class App(QMainWindow): def __init__(self): super().__init__() self.title = 'Login na aplicação' self.left = 600 self.top = 400 self.width = 380 self.height = 200 self.username = None self.password = None self.button = None def __call__(self, *args, **kwargs): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) # Create an username textbox self.username = QLineEdit(self) self.username.move(20, 20) self.username.resize(280, 40) self.username.setPlaceholderText('Usuário') # Create a password textbox self.password = QLineEdit(self) self.password.setEchoMode(QLineEdit.Password) self.password.move(20, 80) self.password.resize(280, 40) self.password.setPlaceholderText('Senha') # Create a button in the window self.button = QPushButton('Login', self) self.button.move(20, 140) # connect button to function on_click self.button.clicked.connect(self.on_click) self.show() @pyqtSlot() def on_click(self): username = self.username.text() password = self.password.text() querystring.update({'username': username, 'password': password}) url = "http://localhost:8000/login_api/" response = requests.request("GET", url, headers=headers, params=querystring) result = json.loads(response.content)[0]['message'] if result: pass else: QMessageBox.question( self, 'Erro', "Usuário não autenticado!", QMessageBox.Ok, QMessageBox.Ok ) self.username.setText("") self.password.setText("") def upload_file_page(self): pass if __name__ == '__main__': app = QApplication(sys.argv) ex = App() ex() sys.exit(app.exec_()) I need to … -
Securely send email from custom gsuit domain in python Django
I have two gsuit emails : admin@mydomain.com -- this is the main admin user@mydomain.com I want to send email from user@mydomain.com using python3.7 I created app_password for user@mydomain.com and tried the following code in Django: settings.py: EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'user@mydomain.com' EMAIL_HOST_PASSWORD = 'xxxxxxxxxxxxx' EMAIL_PORT = 587 main function: message = render_to_string('app1/email.html', { 'fn': ip_dict['first_name'], 'ln': ip_dict['last_name'] }) send_mail( 'hello world', '', 'user@mydomain.com', [ip_dict['email']], html_message=message, ) I get error : SMTPAuthenticationError at /url/ (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials v5sm4332617otk.64 - gsmtp') -
form.is_valid() is throwing error while using phone as primary key
I am trying to create a mobile-otp login portal in Django. I changed the User model and made phone number a primary key, User class looks like this. Models.py class User(AbstractBaseUser): username = models.CharField(max_length=50, blank=True, null=True, unique=True) phone = models.CharField(validators=[phone_regex], max_length=10, unique=True, primary_key=True) email = models.CharField(validators=[email_regex], max_length=50, blank=True) phone_verified = models.BooleanField(default=False) I am getting no errors while signing up the user. I am then sending the otp on the user's phone and when I am trying to validate the otp sent on the that phone, verify_form.is_valid() is throwing the error. I checked the error by using messages.error(request, "Error") and it shows User with this Phone already exists. Below is the views.py, forms.py. Views.py #function used to signup the user and to send the otp on the phone. def phonesignup(request): if request.method == 'POST': phone_form = forms.PhoneSignupForm(request.POST) if phone_form.is_valid(): user = phone_form.save(commit=False) phone = phone_form.cleaned_data.get('phone') password = BaseUserManager().make_random_password(length=12) user.phone = phone user.set_password(password) user.save() response = sendsmsotp(phone=phone) # more-code # function to verify the otp def verifysmsotp(request): if request.method == 'POST': verify_form = forms.OTPVerifyForm(request.POST) print(verify_form) if verify_form.is_valid(): #<----------------------Form Error Here sent_otp = verify_form.cleaned_data.get('otp') phone = verify_form.cleaned_data.get('phone') # more-code Forms.py class PhoneSignupForm(forms.ModelForm): phone = forms.CharField(label='Mobile Number', required=True) class Meta: model = User fields … -
How to change color of "like button" for individual posts in template using JQuery/AJAX?
I'm new to Django and have been self-teaching. I want to create a like button that changes color and submits .form through POST without having to refresh/reload the template/page. Forgive me if I'm asking the question improperly, it took me a while to phrase the question best I could. I'm looking at JQuery/AJAX examples that provide similar answers, but all of them consist of a single Object within a template. Since I have multiple Posts from multiple Users, the First Objects Button is the only one that changes color. So instead of using i.e. id="like-btn"; which only updates the first Objects' button, I found that using class="like-btn" updates all Posts. Now when the button is clicked, all "like-btn"'s from all Posts are changed. Now I'm stuck between updating only the First Object Button or updating All Object Buttons. '''template blog.html''' <form action="/blog/" method="POST" class="post-form">\ {% csrf_token %} <button class="hoverable" type="submit"> <i class="like-btn material-icons">check_box</i> </button> </form> <script type="text/javascript"> $(document).ready(function() { $(".like-btn").click(function() { $(".like-btn").css("color", "red"); $(".like-btn").css("background-color", "transparent"); }); }); </script> This result will update all "like-btn"'s in the template, instead of only updating the clicked "like-btn" -
Issues with Logout button responding to return to Welcome Page on iOS 12
While testing out Login and Logout functions with Server in encountered problem with triggering response from Logout button to go back to welcome page. enter image description here The output response I got on Xcode: 2019-09-01 11:26:55.228628-0400 DeliveryMobile[9388:267899] [] nw_socket_handle_socket_event [C13.1:2] Socket SO_ERROR [61: Connection refused] 2019-09-01 11:26:55.230803-0400 DeliveryMobile[9388:267899] [] nw_socket_handle_socket_event [C13.2:2] Socket SO_ERROR [61: Connection refused] 2019-09-01 11:26:55.241291-0400 DeliveryMobile[9388:268135] TIC Read Status [13:0x60000278f480]: 1:57 Also my APIManager.swift has the following code: // API to log out user func logout(completionHandler: @escaping (NSError?) -> Void) { let path = "api/social/revoke-token/" let url = baseURL!.appendingPathComponent(path) let params: [String: Any] = [ "client_id": CLIENT_ID, "client_secret": CLIENT_SECRET, "token": self.accessToken ] AF.request(url!, method: .post, parameters: params, encoding: URLEncoding(), headers: nil).responseString { (response) in switch response.result { case .success: completionHandler(nil) break case .failure(let error): completionHandler(error as NSError?) break } } } Let me know what I'm doing wrong. I am running this on swift 5 Xcode 10.3 -
Django. Rest framework. How to generate the same tags?
Digging out the features of Django Rest Framework, I constantly come across difficulties. Here it is now. I have photos, each photo has a separate field (photo_1, photo_2, photo_3, etc). These photos need to be uploaded to the same tags, like this: <image>photo_1_url</image> <image>photo_2_url</image> <image>photo_3_url</image> My models.py: photo_1 = models.ImageField(upload_to=image, blank=True) photo_2 = models.ImageField(upload_to=image, blank=True) photo_3 = models.ImageField(upload_to=image, blank=True) My views.py: class SerializerImage(serializers.ModelSerializer): class Meta: model = kv fields = ['photo_1', 'photo_2', 'photo_3'] In **xml** I get the following fields and this is wrong: <photo_1></photo_1> <photo_2></photo_2> <photo_3></photo_3> I need to place all the photos under the tag <image>. Help advice! How to make all images under one tag. I tried through self.fields.update. Tag photo_1 changes to an image, but this can only be done once. Two tags with the same name are not displayed. Thank! -
can search engine find django admin dashboard?
Do I need to add django admin file to 'robots.txt'? So Google or other search engines don't index it? Or it's already has 'nofollow,noindex'? If I need to add it to robots.txt how to do it? Thanks. -
Calculate weighted score from Salesforce data in Django
I'm looking to connect my website with Salesforce and have a view that shows a breakdown of a user's activities in Salesforce, then calculate an overall score based on assigned weights to each activity. I'm using Django-Salesforce to initiate the connection and extend the Activity model, but I'm not sure I've setup the Activity or OverallScore classes correctly. Below is my code for what I already have. Based on other questions I've seen that are similar, it seems like a custom save method is the suggested result, but my concern is that my database would quickly become massive, as the connection will refresh every 5 minutes. The biggest question I have is how to setup the "weighted_score" attribute of the Activity class, as I doubt what I have currently is correct. class Activity(salesforce.models.Model): owner = models.ManyToManyField(Profile) name = models.CharField(verbose_name='Name', max_length=264, unique=True) weight = models.DecimalField(verbose_name='Weight', decimal_places=2, default=0) score = models.IntegerField(verbose_name='Score', default=0) weighted_score = weight*score def __str__(self): return self.name class OverallScore(models.Model): factors = models.ManyToManyField(Activity) score = Activity.objects.aggregate(Sum('weighted_score')) def __str__(self): return "OverallScore" The ideal end result would be each user logged in gets a "live" look at their activity scores and one overall score which is refreshed every 5 minutes from the Salesforce … -
AttributeError: 'DisabledBackend' object has no attribute '_get_task_meta_for' for celery task
My Celery configuration is as follows: app = Celery('track_rides_application',backend='rpc://', broker='amqp://guest:guest@127.0.0.1/' ) I am getting this error: AttributeError: 'DisabledBackend' object has no attribute '_get_task_meta_for' Even though I provided backend attribute I am getting the above error -
Django annotate, access current row to traverse foreign keys
I have these models: class Sale(models.Model): date = models.DateField() profit = models.FloatField() expenses = models.FloatField() seller = models.ForeignKey(Seller) class Seller(models.Model): name = models.CharField() store = models.ForeignKey(Store) class Store(models.Model): name = models.CharField() country = models.ForeignKey(Country) given ids = [a list of seller ids...], I need a table like this: Store 1 -> sum of profits - sum of expenses of all sellers in ids and in store 1 Store 2 -> sum of profits - sum of expenses of all sellers in ids and in store 2 ... I can get all the stores like this: sellers = Seller.objects.filter(id__in=ids) q = Store.objects.filter(id__in=sellers.values("store_id")) At this point I'd iterate over q but that would defy the point of having an ORM. The alternative is using .annotate() but how can I tell .annotate to grab the sum of all profits of all sellers in store N? -
Kubernetes build django + uwsgi + nginx show failed (111: Connection refused) while connecting to upstream
when I create my.yaml, then nginx will show failed (111: Connection refused) while connecting to upstream have any sugesstion about this? Is there pod network do not connnect? uwsgi: [uwsgi] module = myapp.wsgi master = true processes = 10 socket = 127.0.0.1:8001 chmod-socket = 777 vacuum = true enable-threads = True nginx: upstream django_api { server 127.0.0.1:8001 max_fails=20 fail_timeout=10s; } server { listen 80; #location /media { # alias /media; # your Django project's media files - amend as required #} location /static { alias /usr/share/apps/static; # your Django project's static files - amend as required } location / { uwsgi_read_timeout 60; uwsgi_pass django_api; include ./uwsgi_params; # the uwsgi_params file you installed uwsgi_param Host $host; uwsgi_param X-Real-IP $remote_addr; uwsgi_param X-Forwarded-For $proxy_add_x_forwarded_for; uwsgi_param X-Forwarded-Proto $http_x_forwarded_proto; } } -
User can switch account to another user
I have an url path('dashboard/<int:user_id>/', views.dashboard, name='dashboard'), The problem is when User is logged in He can change user_id variable in url and switch to another user account. My question is how to prevent that behaviour. Should I change something in template or somewhere else ? -
django handling comments form in same page
i want know ,if is there any way where we could handle two form on a single template & view where one form doesnt take any arguments where as the other form takes arguments yeah one form is the post form to create a post while the other one is the comment form which actually takes an argument(pk) to get that particular post id and add create that object i have tried to add two forms which will create two objects in single view the post object and its post form actually works fine but whereas the comment object requires a pk argument to filter the post object to be created and when i tried changing my view from post_create(request) to def post_create(request,pk) it fired up an error saying that pk value has not been given def post_create(request): if request.method=='POST': form = PostCreateForm(request.POST,request.FILES) comment=CommentForm(request.POST) post=Post.objects.get(id=pk) # comment= # print(form) if request.FILES: print('there is a file') else: print('no file') # if re if form.is_valid() or comment.is_valid(): # c=comment.save(commit=False) psts = form.save(commit=False) psts.author = request.user # if comment: # psts.comment.add(comment) # else: # print('there is nothing') # psts.image = print(psts.image) psts.save() if comment.is_valid(): comment = comment.save(commit=False) comment.post= post comment.user = request.user comment.save() … -
How to create a form that adapts to the number of users with django 2?
I am biginner wiht django, and I would like to create a form that could adapt him to the number of user. The goal is to declare the presence or not of employees and the number of hours they worked during the day, knowing that the number of employees can change from one day to another. So I thought of creating two variables : an integer counting the number of hours performed during the day, and another boolean corresponding to the presence or not of the employee, and being reproduced as many times as there are employees. So, I tested that : forms.py : class HoursDeclarationForm(forms.Form): number_of_hours = forms.FloatField(required=True) for user in User.objects.all(): presence = forms.BooleanField(label="{0} {1}".format( User.first_name, User.last_name ) ) views.py : def hours_declaration (request): form = HoursDeclarationForm(request.POST or None) return render ( request, 'HoursDeclaration/hours_declaration.html' , locals() ) hours_declaration.html : <h1>Ceci est la page ou tu peux attribuer à chaque salarié le nombre d'heure qu'il a effectué.<h1> <form action="{% url "hours_declaration" %}" method = "post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="submit"> </form> But I get a single checkbox preceded by: "django.db.models.query_utils.DeferredAttribute object at 0x00000255505DEF98 django.db.models.query_utils.DeferredAttribute object at 0x00000255505DEFD0" :, no matter the number of users. Please … -
Django-Channels trying to understand
I was working with django to display some data and i was using refresh page to read the new data then after i looking around the internet how to make the data streamable i saw about channels. the thing is im newbe with python and after reading for hour i cant understand how channels works. it was very simple because was adding the data to a list and then i display one by one from the list to the webpage like this: {% block content %} <ul class="list-data-panel"> {% for s in stats %} <li data-header="{{ s.0 }}"> ........... my question is a posible to make this with channels1 or 2 version and if there is anyone can explain how to do it or if there is any tutorial exept the chat. thank you for reading and sorry for my poor english -
I need a plugin for authipay on the python django project
I am going to implement the Authipay on my django project. Is there any opensource for this? I need your help as soon as possible. Any advice would be appreciated. Thanks for your time. Regards. -
TypeError: can't pickle psycopg2.extensions.Binary objects (after having switched to Python 3)
I just switched my Django app (Django 1.11.20) from Python 2.7 to Python 3.6.6 and the following line now generates a bug : caches['pgcache'].set(id, mydict, 10000) Here is the error message : Internal Server Error: /trip/province-oristrano-2138 Traceback (most recent call last): File "C:\terradiem\terradiem\venvpython\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\terradiem\terradiem\venvpython\lib\site-packages\django\core\handlers\base.py", line 249, in _legacy_get_response response = self._get_response(request) File "C:\terradiem\terradiem\venvpython\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\terradiem\terradiem\venvpython\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\terradiem\terradiem\trip\views.py", line 320, in trip caches['pgcache'].set(targetobjectid, mydict, 10000) File "C:\terradiem\terradiem\venvpython\lib\site-packages\django\core\cache\backends\db.py", line 87, in set self._base_set('set', key, value, timeout) File "C:\terradiem\terradiem\venvpython\lib\site-packages\django\core\cache\backends\db.py", line 114, in _base_set pickled = pickle.dumps(value, pickle.HIGHEST_PROTOCOL) TypeError: can't pickle psycopg2.extensions.Binary objects I don't understand what is the problem. Any clue ? Thank you -
Django how to generate short random slug?
I'm implementing photo sharing web application where the link of each photo will be different. "localhost.com/fggcxdf" how to generate a short random slug that should be unique. -
How to return user details in response after login in django rest_framework
Hi I am beginner in Django Here I want user email and name in response after user login using api. Thanks in advance for your help. models.py I want user email and user name in response only getting auth token in response class UserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): if not email: raise ValueError('Users must have an email address') if not password: raise ValueError('Users must have a password') user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user(email,password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' serializers.py I want user email and user name in response only getting auth token in response class UserSerializer(serializers.ModelSerializer): email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) class Meta: model = get_user_model() fields = ('email', 'password', 'name') extra_kwargs = {'password': {'write_only': True, 'min_length': 6}} def create(self, validated_data): user = User.objects.create_user('name',validated_data['email'], validated_data['password'],) return user class AuthTokenSerializer(serializers.Serializer): email = serializers.CharField() password = serializers.CharField( style = {'input_type':'password'}, trim_whitespace = False ) def validate(self, attrs): email = attrs.get('email') password = attrs.get('password') user = authenticate( request = self.context.get('request'), username = email, password = password … -
Import and save thumbnailphoto from ldap to django imagefield
I am trying to save the picture of a user retrieved from active directory using django ldap library, but i am unable to store it in the write way, i have spent hours searching this issue, if any one can help me i will be grateful, this the format of the thumbnail photo b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00H\x00H\x00\x00\xff\xdb\x00C\x00\x08\x06\x06\x07\x06\x05\x08\x07\x07\x07\t\t\x08\n\x0c\x14\r\x0c\x0b\x0b\x0c\x19\x12\x13\x0f\x14\x1d\x1a\x1f\x1e\x1d\x1a\x1c\x1c $.\' ",#\x1c\x1c(7),01444\x1f\'9=82<.342\xff\xdb\x00C\x01\t\t\t\x0c\x0b\x0c\x18\r\r\x182!\x1c!22222222222222222222222222222222222222222222222222\xff\xc0\x00\x11\x08\x00`\x00`\x03\x01!\x00\x02\x11\x01\x03\x11\x01\xff\xc4\x00\x1c\x00\x00\x01\x04\x03\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x01\x03\x06\x07\x00\x04\x05\x08\xff\xc4\x00:\x10\x00\x01\x03\x03\x02\x03\x05\x06\x04\x03\t\x00\x00\x00\x00\x00\x01\x00\x02\x03\x04\x05\x11\x06!\x121a\x07\x14AQq\x13"2\x81\xa1\xc1#BR\x91\x15$r5C\x82\xa2\xb1\xb2\xc2\xd1\xe1\xff\xc4\x00\x19\x01\x00\x02\x03\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x02\x03\x05\x04\xff\xc4\x00\x1d\x11\x01\x01\x01\x00\x03\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x02\x03\x04\x11!\x12"1\xff\xda\x00\x0c\x03\x01\x00\x02\x11\x03\x11\x00?\x00\xb3\x02 \x10\x04\x02\\&E\xc2\xcc 3\t0\x80B\x85\x00$ !\x00\xe0\x08\xc0H\xca\x02,&LP\xbb\xd6\xbem1\x11Y-\xf2\\\xe4$\x83)\xcb"\x1e\x87\x9b\xbdF\xddTu\xb9\x99\xedO\x18\xbb\xbeCt\x1a\xf2\xae9\xf8/\xd6gQ\xc3\x8c\x9a\x9aw\x99X\xde\xaen2\x07Q\x9c)\xa43ES\x04s\xc1#%\x86F\x871\xec9\x0e\x07\x91\x05,o;\x9e\xc1\xbe=b\xf9DP\xa9\xa0\x12\x84\x84\x19\xc0\x11\x00\x90\x10\x08\xb0\x99!z\xf6\xe9$r[\xec\xac\xda*\xde9*\x1c\x0e\t\x8d\x98\xf7=\x1cy\xf4\x18\xf1Z\xf6\xc0\xc7G\x82\xdc\x11\xcb\x03\x92\xcf\xed_w#C\xa9\x9f1i\xcb\x88\x02"Z\xd3\x9f4\xc6\x85\xac}%\xe2\xba\xccO\xf2\xcfgz\xa6g\x83\x0eq#GL\x90q\xea\x8e\xad\xf3~\x1fk>\xe3\xd4\xf0\xa1!h3\x82P\x90\x80p\x04a \x12\xa6\x15\xce\xb9"MM\x03\xa2s^\xf8h\xdc\xc2?C\x8b\xb3\xbf\xa8!E(\xefwjz\xa6\x96T\xcb;G\xc6\xce\xee\x18\xdf\x91\xe6\xb8y|\xbb\xad\x0e\x19\xa9\x88\xdd\xd4\xb5u\xf3U63%S kZ\xe3\xdd\xcf\tv|\x13\xbab\xa9\xb6\xfb\xc5\xbe\xb2\xa9\xf3\xfb6:H\xcb\xa4\x19v\x1e\xdc\x0c\xf9\x8c\xe1G\x8f^yj\\\x98\xba\xf6E\xb8\xed\x8a\x12\xb4\x19\xa1(J\x01\xc0\x8c$\n\x11&\x15\xe6\xb6\x87\xb8\xdec\xadtn\xf6U\x1c,/\x03`q\x8d\xff\x00a\xfb\xae}EM\x0cT.\x99\xac\x19\xc7\xbcZ\x06@\xf1Y\xdc\xd9\xb3u\xab\xc1\xb9s\x03O|\xb6\\\xebOv\xcc\x91\xb66\x87\xf1\x01\x80G$\x0c?\xc4\xf5\x1d%\r$>\xd7$\xbd\xe0~V\x0ed\xf4\xdc(\xe7\x17\xf5\xf9K|\x92g\xf5\xea\xd4w2\x9b+M\x92D\x88\x07B \x91\t*a\x1f\xd6\x94o\xaf\xd2W8"\x19\x90Bd`\xf3,!\xdfe@\xc5^+e\x8e9\x9f#\xe3\x03\xe0\xe2\xd8\x95W$\xf7\xea\xde=y\xf2\xb7k\xe9{\xac\x1e\xdd\xd1\x1ag\xe31\xba9\x83\xb8\xbdp\x06\x02\x96\xf6E\xc5[~\xb9W8\x93\xeci\xc4c>ov\x7f\xe2\xa3\xc7\xf7\xea\xcek?\xc8\xb8\nl\xab I have stored first the image bytes string in a field and then save it into the imagefield, but when i open it i have a message as if the format is not recognized by the photo editor. This is the code that i have tried : current_user = CustomUser.objects.filter(username=user).first() current_user.user_image.save('{0}/photos/{1}.jpg'.format(settings.MEDIA_ROOT, username), ContentFile(current_user.user_image_string)) What is the newt step that i have to do ? -
How generate a DOC and a PDF from html <div> in Django
Good day, In Django project I have an html file with a div in which some fields(like p) change the content by radiobutton choice (using JavaScript). Need to turn the div with the changed content (by radiobutton choice) into pdf and doc (with saving of all styles). Any help is appreciated. I tried "wkhtmltopdf" but it generates pdf only with model contents from db and without result of radiobutton work. <!--Choice radiobuttons--> function Display(obj) { fioid=obj.id; if(fioid=='exampleRadios1'){ document.getElementById("fiz").style.display='block'; document.getElementById("ip").style.display='none'; document.getElementById("ur").style.display='none'; } else if(fioid=='exampleRadios2'){ document.getElementById("ip").style.display='block'; document.getElementById("fiz").style.display='none'; document.getElementById("ur").style.display='none'; } else if(fioid=='exampleRadios3'){ document.getElementById("ur").style.display='block'; document.getElementById("fiz").style.display='none'; document.getElementById("ip").style.display='none'; }} <div class="col-12"> <div class="form-check"> <input class="form-check-input" type="radio" name="exampleRadios" id="exampleRadios1" value="FIZ" onclick="Display(this);" checked> <label class="form-check-label" for="exampleRadios1"> FIZ </label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="exampleRadios" id="exampleRadios2" value="IP" onclick="Display(this);"> <label class="form-check-label" for="exampleRadios2"> IP </label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="exampleRadios" id="exampleRadios3" value="UR" onclick="Display(this);"> <label class="form-check-label" for="exampleRadios3"> UR </label> </div> </div> <div> <p style="text-align: justify; font-family: Times New Roman;"> <span style='display: block;' id="fiz">This is FIZ</span> <span style='display: none;' id="ip">This is IP</span> <span style='display: none;' id="ur">This is UR</span> </p> <div> -
In Django, how to add creator of a group to that group instantly?
I'm creating a 'social' app in Django, where the users can create groups (Alliances) and others can join these groups. User Profiles and Alliances are connected through Membership model. I´d like the creator of such group to be a member of it instantly. I'm inexperienced in Django, in fact, this is my first project. But I figured that this maybe could be solved by signals? My user Profile model: class Profile(models.Model): ... user = models.OneToOneField(User, on_delete=models.CASCADE) alliances = models.ManyToManyField('Alliance', through='Membership') ... My Alliance model: class Alliance(models.Model): ... name = models.CharField(max_length=10, unique=True) members = models.ManyToManyField('Profile', through='Membership') ... My Membership model: class Membership(models.Model): ... profile = models.ForeignKey('Profile', on_delete=models.CASCADE) alliance = models.ForeignKey('Alliance', on_delete=models.CASCADE) ... The solution I figured could work (using signals) would look something like this: @receiver(post_save, sender=Alliance) def create_membership(sender, instance, created, **kwargs): if created: Membership.objects.create(profile=???, alliance=instance) Where the '???' should be the creators profile. I'll be really glad for any help. -
How to keep the bootstrap 4 datetimepicker plus widget on top
Is it really not possible to keep the date time picker widget on top - or so it seems at this point. I am using the "django-bootstrap-datepicker-plus" (source) I find it difficult to keep the datepicker widget in view when I am using it in an inline formset. The first image shows in a normal form render, whereas the second shows the situation when being used in inline formsets. As can be seen the one in the inline formset, the widget is only partly visible (a scroll bar appears whenever the date field is clicked or gets focus and I am able to scroll up or down and select the date I want). For the normal form what I have done is this: A. In the template I have this in the css (in the head section): .tablehdr-wrapper-scroll-y { display: block; max-height: 400px; min-width:550px; max-width:550px; overflow-y: auto; -ms-overflow-style: -ms-autohiding-scrollbar; overflow: visible!important; } B. And in the form section, I have this: {% if field.name == "docdate" %} <div style="z-index: 99999;" {{ field }}</div> {% else %} ------- ------ {% endif %} I can't make it more obvious that the idea used here has been the fruit(!) of labor of skimming … -
How to call a function when the user POSTs an image in django rest api
I am making a face detection api that will take image as an input from a user. How can i call a function when the user creates a POST request? I have the face detection code that was made using opencv i want to integrate it in my api. models.py from django.db import models import uuid from .validators import validate_file_extension def scramble_uploaded_filename(instance,filename): extension = filename.split(".")[-1] reformated = "{}.{}".format(uuid.uuid4(),extension) return reformated def scramble_uploaded_filename1(instance,filename): extension = filename.split(".")[-1] return "{}.{}".format(uuid.uuid4(),extension) class UploadVideo(models.Model): video = models.FileField('Uploaded Video',upload_to=scramble_uploaded_filename1, validators=[validate_file_extension] ) class UploadImage(models.Model): image = models.ImageField('Uploaded Image', upload_to=scramble_uploaded_filename) urls.py in resp api from django.conf.urls import url, include from rest_framework import routers from imageupload_rest.viewsets import UploadImageViewSet, UploadVideoViewSet router = routers.DefaultRouter() router.register('images', UploadImageViewSet, 'images') router.register('videos', UploadVideoViewSet, 'videos') app_name = 'reviews' urlpatterns = [ url(r'^',include(router.urls)), ] serializers.py from rest_framework import serializers from imageupload.models import UploadImage, UploadVideo class UploadImageSerializer(serializers.ModelSerializer): class Meta: model = UploadImage fields = ('pk', 'image', ) class UploadVideoSerializer(serializers.ModelSerializer): class Meta: model = UploadVideo fields = ('pk', 'video' , ) viewsets.py from rest_framework import viewsets from imageupload_rest.serializers import UploadImageSerializer, UploadVideoSerializer from imageupload.models import UploadImage, UploadVideo class UploadImageViewSet(viewsets.ModelViewSet): queryset = UploadImage.objects.all() serializer_class = UploadImageSerializer class UploadVideoViewSet(viewsets.ModelViewSet): queryset = UploadVideo.objects.all() serializer_class = UploadVideoSerializer I want a message that will say …