Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Impossible to create a WS connection Handshake not working
I'am trying to make channel working and I have an error. When I am trying to connect to a websocket: var chatSocket = new WebSocket('ws://' + window.location.host + '/ws/chat/' + roomName + '/'); consumer.py:- from channels.generic.websocket import WebsocketConsumer import json class ChatConsumer(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): pass def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] self.send(text_data=json.dumps({ 'message': message })) It gives error: (index):16 WebSocket connection to'ws://127.0.0.1:8000/ws/chat/loby/' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET -
What algorithm does tinyUrl, YouTube, imgur etc used to generate random url that is unique?
How YouTube, imgur, bitly etc generate short url. How do they check for uniqueness. What hashing algorithm do they use. I'm learning to implement it in my django project. -
Javascript backtick string interpolation creates a URL with blank spaces
When using string interpolation with backticks to create an URL which posts to a django endpoint, the created url adds unnecessary whitespace and a new line. The faulty js in question: (function (window, document, undefined){ // Upvote / Downvote selectors: const upvote = document.getElementById('upvote'); const downvote = document.getElementById('downvote'); const object_id = document.getElementById('object_id').textContent; // const object_id = document.getElementById('object_id').innerHTML; // csrftoken getter function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); // Voting function const vote = ($route) => { fetch(`/${$route}/${object_id}/`, { method:'post', headers:{ 'X-CSRFToken':csrftoken, 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8', 'X-Requested-With':'XMLHttpRequest' }, }) .then((response) => response.json()) .then((responseData) => { console.log(responseData); return responseData; }) .catch(error => console.warn(error)); } // Event listener adder const add = ($element, $route) => { $element.addEventListener('click', vote.bind(null, $route)) } add(upvote, "upvote") add(downvote, "downvote") })(window, document); When I hardcode the URL, it completes successfully: function vote_up(){ fetch(`/upvote/3/`, { method:'post', headers:{ 'X-CSRFToken':csrftoken, 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8', 'X-Requested-With':'XMLHttpRequest' }, }) .then((response) => response.json()) .then((responseData) => { console.log(responseData); return … -
Django search bar not getting to the right page
My page has two ways to search services - one is a search bar and the other is clickable categories. The clickable category go to a page that has a category primary key attached to the view and the search bar results do not have a category pk attached. Thus, I created two separate views for this reason. The problem is that both views go to the same page the index.html. I want the search bar to go to the index_search.html. I think I set-up everything correctly, but it still does not work. Two views: search view, clickable items view: #search form view def service_finder(request): model = Service if ('s' in request.GET) and request.GET['s'].strip(): query_string = request.GET['s'] #get query is just searching for search terms in those fields of the query set entry_query = get_query(query_string,['description', 'tags', 'category']) table = Service.objects.filter(entry_query)[:60] return render(request, 'index_search.html', {'table': table}) #clickable items view def servicesListView(request, category): model = Service table = Service.objects.filter(category=category)[:60] return render(request, 'index.html', {'table': table}) Here is the html template with both the search bar and clickable items: {% block content %} <main class="category"> {% include "search_form.html" %} <section class="category-list"> <div class="container"> <div class="row"> {% for service in service_cat %} <div class="col-sm-12 col-lg-6"> … -
Passing dynamic parameter to urlpatterns or DefaultRouter
I have several categories that I want to create distinct views for in rest_framework. But all the categories pull from the same Model. It strikes me that these categories could be passed to urlpatterns as a keyword (or DefaultRouter). Then you can use the keyword to filter the Model as required. Here's my view: class CategoryRankedViewSet(ModelViewSet): serializer_class = CategoriesSerializer def get_queryset(self): return Categories.objects.all().order_by(self.kwargs['category']) One way I was able to make this work was: urlpatterns = [path('<' + category + '>/', CategoryRankedViewSet.as_view({'get': 'list'}), name=category) for category in CATEGORIES] But its not perfect because the key for the parameter is set to the value of first item in CATEGORIES, rather than a more generic term like 'category'. Has anyone ever tried this and is there a more effective method? I was considering DefaultRouter but it is not obvious if parameters can be passed to DefaultRouter I was also looking for ways that the literal url could be accessed and accessing the category that way. Does not appear this is possible in a ViewSet in DRF -
No module named 'django.contrib.auto'
the site is working OK after "python manage.py runserver" im getting the pages as i should , the problem is that when im trying to submit the registration form / or trying to login to the admin page im getting No module named 'django.contrib.auto' even though i haven't had any code issues , went over my code and checked several answers but none of them solved the issue . 1. tried to modify the url.py file - no 2. added to the "INSTALLED_APPS = django.contrib.auto" - no 3. added to the views.py - no 4. checked my code for errors - no INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'basic_app', ] urls.py: from django.contrib import admin from django.urls import path from django.conf.urls import url from django.conf.urls import include from basic_app import views urlpatterns = [ path('admin/', admin.site.urls), url (r'^$',views.index,name='index'), url (r'^basic_app/',include('basic_app.urls')), ] forms.py : from django import forms from django.contrib.auth.models import User from basic_app.models import UserProfileInfo class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = ('username','email','password') class UserProfileInfoForm(forms.ModelForm): class Meta(): model = UserProfileInfo fields = ('portfolio_site','profile_pic') models.py: from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfileInfo(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) … -
How get GitHub username in django-allauth after authentication?
I added django-allauth to the Django project and I can authentication with GitHub on website. After user authentication, I want to get GitHub username(a user who logged in). How to do it? -
Connecting the elastic beanstalk environment with existing RDS instance
I have an existing RDS MYSQL instance which is in default VPC. I want to connect to this instance through app running on Elastic beanstalk env, which i am not able to do. Beanstalk env and RDS instance are in same VPC and the security groups allow access to port 3306 for all the IPs. Can someone please help? Opened all the security groups for accessing port 3306. -
Django files location
My project structure is: main settings.py and etc. app1 views.py and etc. app2 views.py and etc. manage.py I have decorators that i use in views at app1 and app2. Where should locate file decorators.py? Options in my opinion: create decorators.py in app1 folder and import this to at app1.views and app2.views create decorators.py in app1 folder and import this to app1.views and create decorators.py in app2 folder and import this to app2.views.py (decorators.py will contains the same code, not so good) create decorators.py in main folder and import this to at app1.views and app2.views Your opinion? -
How can I overcome to OrderedDict' object has no attribute 'register' in django?
OrderedDict' object has no attribute 'register' I creating api on django I used register in urls to register defaultrouter() but got this specified error using python anywhere as a server -
Building Bar Chart from data retrieved from Django Database
I'm trying to build a django app where the data is stored in a database (like Sqlite3 or Postgres) then retrieve it in the views and plot the data into a bar chart in the template to show it for the user. what's the easiest way to achieve that? -
How to create a finite state machine with a dynamic number of steps
I have a simple linear workflow where a single task will have a list of approvers that it must pass through (linearly, each in turn) for confirmation before being completed. I have designed this to use the User model for approver, with 2 additional models: A Task model to govern details of individual tasks in a workflow; and a TaskStep model to explicitly manage the relationship between the Tasks and Approvers (rather than relying on Django to autopopulate). class Task(models.Model): title = models.CharField(max_length=30) approvers = models.ManyToManyField( get_user_model(), related_name='approvers_taskstep_set', through='TaskStep' ) class TaskStep(models.Model): approver = models.ForeignKey( get_user_model(), null=True, on_delete=models.SET_NULL ) task = models.ForeignKey(Task, null=True, on_delete=models.SET_NULL) I would like to use django-fsm to create a finite state machine to track the status of each task in the workflow. I know I can do this easily if I pre-define the number of approvers in each workflow. E.g. if it were 3 I could simply put this in an integerfield and then create associated functions each approver would call: // in Task(models.Model): STATUS_APPROVER_1 = 0 STATUS_APPROVER_2 = 1 STATUS_APPROVER_3 = 2 STATUS_CHOICES = ( (STATUS_APPROVER_1 , 'With approver 1'), (STATUS_APPROVER_2 , 'With approver 2'), (STATUS_APPROVER_3 , 'With approver 3'), ) status = FSMIntegerField( choices=STATUS_CHOICES, … -
In DRF, can we use other field than the primary field for a related model?
I am using Django Rest Framework for a small REST API. It's my first interaction with DRF and is pretty much all clear. But: I have an Category model, for which I have an ID and an UUID field. The UUID field I want to use it for public exposed API. What I basically want to achieve, is to be able to use Category.uuid instead of Category.id when I expose the API endpoint to the public (for all CRUD actions): class CategoryModel(models.Model): uuid = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) class ArticleModel(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, unique=False, related_name='articles') category = models.ForeignKey(CategoryModel, on_delete=models.CASCADE, related_name='articles') # This serializer won't work as expected: class ArticleSerializer(serializers.ModelSerializer): user = serializers.HiddenField( default=serializers.CurrentUserDefault() ) category = serializers.CharField(source="category.uuid") class Meta: model = ArticleModel fields = ('category', 'user') validators = [ UniqueTogetherValidator( queryset=ArticleModel.objects.all(), fields=('category', 'user'), message=_('You have already added an article in this category') ) ] I have also tried to use a custom serializer, exposing only the uuid field, but without success. Please do not suggest to use uuid as primary key in CategoryModel. I don't want to do that! Test post data: { category: "328d9185-02ae-4963-88a5-03ef67421697" } Posting the above data, I would expect to create an article having the category.uuid … -
How can i capture an image in an android app then send that image to my django rest api?
So i wanted to create an image that will be used to capture an image using the camera app, then that image will be send to the django rest api for image processing. I am currently using retrofit2. I have already made an app that allows a user to choose an image from gallery and then send it to the api, however i can not achieve this if the user wants to capture an image. btnChooseFile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_PICK); intent.setType("image/*"); startActivityForResult(intent,0); } }); upload the image to api btnUpload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { File file = new File(imagePath); System.out.print(imagePath); RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"),file); MultipartBody.Part body = MultipartBody.Part.createFormData("image",file.getName(),requestBody); Call<FileInfo> call = fileService.upload(body); call.enqueue(new Callback<FileInfo>() { @Override public void onResponse(Call<FileInfo> call, Response<FileInfo> response) { if(response.isSuccessful()){ Toast.makeText(AttendanceActivity.this,"Image Uploaded",Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call<FileInfo> call, Throwable t) { Toast.makeText(AttendanceActivity.this,"Error"+t.getMessage(),Toast.LENGTH_SHORT).show(); } }); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { if (data == null) { Toast.makeText(this, "Unable to choose image", Toast.LENGTH_SHORT).show(); return; } Uri imageUri = data.getData(); try { Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri); imageview.setImageBitmap(bitmap); } … -
Django second signal not saving user
Django 2.4Python 3.7 I am implementing a badge system located on github here. Currently I have a Checkin model and a Badge model, the Checkin model sends a signal to my signals.py file each time a form is saved which then triggers either of two functions (or both) in utils.py to create the badge or add a user if the badge already exists. This flow generates both test badges and the first badge is assigned to a user when the condition is met but 2nd badge (although created) is not assigned the instance.user. I thought that the issue was using 1 util function like in the github link to generate both badges so I created two unique functions to trigger each respective receiver. I am also using a function based view instead of a class CreateView (like the github link). But I strongly doubt there is an issue there since both badges are being created, just not saving. If I move the signal functions to Checkin models I get "can't import Checkin from checkin.models" error which is probably due to a circular import issue (I need to clean up my files a little bit). I've confirmed that the ORM returns … -
Create a re-usable question template in Django
In Django, I want to create a model for a Questionnaire that can be created and used as a template by the user. To do this, my thought is to create a Question class with the desired attributes, then create a QuestionTemplate class that will group the questions together into one, re-usable template. However, I'm not sure how to create a class with an unknown number of attributes. class Question(models.Model): group = None name = models.CharField(max_length=264) question = models.CharField(max_length=264) response = models.TextField() rating = Rating(min_value=0, max_value=5) class QuestionTemplate(models.Model): pass I'd like to have the ability to group these user created questions into a template that the user can apply. -
Is there any open sourced django abac(Attribute Based Permission Control) system
I'm implementing a django app. And I'm searching for any open sourced ABAC system I can use. Do you have any recommendations for ABAC system I can directly use for django? Background: For my app, I will need access control for database entries(using MySQL) After investigation, I think it's better to use Attribute based instead of role based access control. django provides role based access control, but seems no ABAC available. I only found pycasbin (https://github.com/casbin/pycasbin) for the use case. I'm hoping to know if there's any other abac system I can use or read through? Thanks -
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.