Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to detect operating system name and version, browser name and version, and type of user's device in Django?
How to detect requesting public infomration of device which is used by a user in Django. I need to restrict multple logins from the same account. I am developing the project in Django REST framework (just for more info). I have tried django-user-agents. I works well but not all the time. I am having hard time to detect if user is using mobile. Question: Can you suggest some other libraries or the ways to get such thing done or what things should I do to implement it by myself? -
scientific web application using python
I need advice about building a web-app. I intend to build a web app that able to get data and perform machine learning and scientific calculation on them and give results with visualization. also, I wonder how can I make such a web application that works on PC and phones(android and ios) and can be executable for example on google chrome or firefox. -
Python script execution from remote machine with some file path as an argument
Here I have one Django form, on form POST I have to run one script that is in different VM (ex 192.0.x.x) and my application is in different VM (ex 192.0.x.x). Problem: In form POST I am saving CSV file to the server and inserting that path to the script as args. Script is in diffrent vm (ex. X). Django app with the uploaded file is in different VM (ex. Y) import subprocess from django.contrib import messages def nboarding(request): if request.method == 'POST': form = NForm(request.POST, request.FILES) if form.is_valid(): operation = form.cleaned_data['operation'] partner = form.cleaned_data['partner'] file = form.cleaned_data['file'] output = script_function(operation, partner, file) messages.success(request, '%s Successfully...' %operation) return redirect('nboarding') #messages.success(request, success_message, extra_tags='safe') #return redirect('/xxx') else: form = NForm() context = { 'form': form, 'menu_device':'active', 'submenu_nboarding':'active', } return render(request, 'monitor/nboarding_form.html', context=context) def script_function(operation, partner, file): #--operation = operation, --partner = partner, --filepath = file return subprocess.chek_all(['python', '192.0.0.0/usr/script.py', '--operation', operation '--partner', partner '--filepath', file]) How to run that script with a file path from different machine ? What I am trying is - return subprocess.check_all(['python', '192.0.0.0/usr/script.py', '--operation', operation '--partner', partner '--filepath', file]) But It's not working -
How to deal with multiple nested one one field in django restframeworks
I have multiple model for eg: class A(models.Model): something = models.CharField(max_length=255) class B(models.Model): a = models.OnetoOneField(A, ...) ...... ...... class C(models.Model): a = models.OnetoOneField(A, .....) ........ ......... upto more than 6 and in my serializer, I'm trying to do somethings like this class ASerializer(serializers.ModelSerializer): b = BSerializer(required=True) c = CSerializer(required=True) ........... ............ class Meta: field = ['all field contains from model A', 'b', 'c', ....] Here I'm using generic LisCreateAPIView. I know i can override create method in serialier, but it only works for one nested one to one field. Here is my create method. When I've only one nested models it works fine but not works for multiple nest one to one model. def create(self, validated_data): location_data = validated_data.pop('b', 'c'. ...) attendance = m.Attendance.objects.create(**validated_data) m.GPSLocation.objects.create(attendance=attendance, **location_data) return attendance -
Celery Task Error | __init__() missing positional argument operation_name
I am having a certain list of celery tasks, which I run as a group(tasks). While doing so, I am getting the error Task scans.tasks.assest_scan[task_id] raised unexpected: TypeError("__init__() missing 1 required positional argument: 'operation_name'",) asset_scan_tasks = group([task_one.si(*args), task_two.si(*args)]) Can someone help me with why exactly I am getting this error? -
deploying heroku show me Push failed error django
PATH=/app/.heroku/python/bin:/app/.heroku/vendor/bin::/usr/local/bin:/usr/local/bin:/usr/bin:/bin:/tmp/codon/vendor/bin:/app/tmp/buildpacks/8790c95df255b386056ea169648fd4a33d1cb3fba81f73b536f26374f6af107145f64a5980db7a52177f63bb41527f360ebd2e3bef7b8917bda7b51cf284cfdb/vendor/:/app/tmp/buildpacks/8790c95df255b386056ea169648fd4a33d1cb3fba81f73b536f26374f6af107145f64a5980db7a52177f63bb41527f360ebd2e3bef7b8917bda7b51cf284cfdb/vendor/pip-pop ENV_DIR=/tmp/d20200522-55-1lqsbbw BUILD_DIR=/tmp/build_441ebfec7be420678ba0eb80ddd22701 DEFAULT_PYTHON_VERSION=python-3.7.7 PKG_CONFIG_PATH=/app/.heroku/vendor/lib/pkgconfig:/app/.heroku/vendor/lib/pkg-config:/app/.heroku/python/lib/pkg-config: LATEST_27=python-2.7.18 _=/usr/bin/env ! Push rejected, failed to compile Python app. ! Push failed what is the problem? I have several files already in exact directory -Procfile -runtime.txt -requirements.txt In procfile, python3 version is 3.7.7 I am using postsql database I already fix my staticfile error by looking this heroku log. -
How to turn below code into django web app
print('''Instructions: To decrypt enter 'dec' and to Encrypt enter 'enc' ''') #Initializing circular Alphabet alpha_list = ['a','b','c','d','e','f','g','h','i','j', 'k','l','m','n','o','p','q','r','s','t','u','v', 'w','x','y','z','a','b','c','d','e', 'f','g','h','i','j','k','l','m','n', 'o','p','q','r','s','t','u','v','w','x', 'y'] #Getting Inputs input_text = input("Input Text: ") key = int(input("Key: ")) operation = input("Enter OPeration 'enc/dec' ") #Defining Lists to Store Data text_list=[] decrypt=[] last_list=[] character=0 #Storing Input Text to a list as Single characters for letters in input_text: text_list.append(letters) #Iterating through circular alphabet and user input list for char in text_list: for letter in alpha_list: #matching Charcaters if char == letter: character=(alpha_list.index(char)+1) #matching Operation if operation == "enc": decrypt.append(alpha_list[character-1+(key)]) else: decrypt.append(alpha_list[character-1-(key)]) #Converting List in to a string dec_string=''.join (map(str,decrypt)) #Fixing double character Error for dec in range (0,len(dec_string),2): last_list.append(dec_string[dec]) if operation == "enc": print("Encrypted Value: ",''.join(map(str,last_list))) else: print("Decrypted Value: ",''.join(map(str,last_list))) This a small script to encrypt and decrypt words. I'm trying to figure out a way to write exact script in django. Can anyone tell me a way to get an approach. I need to know how to write a model for this, writing views. Thank you -
Analytics API in JavaScript not run on google cloud platform
In Django google Analytics API in JavaScript runs locally(localhost) when I deploy on a google cloud platform instance (ubuntu 18.04) code link (https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/web-js) it's not showing a login button. what should I do? authorize button didn't show output -
Django - Date field resets in UpdateView when using datepicker
I've added a datepicker to my UpdateView. Datepicker works fine, however, on edit the date field shows dd/mm/yyyy rather than the value set when the record was created. views.py class ActionUpdate(LoginRequiredMixin, UpdateView): model = Action form_class = MyActionForm forms.py class DateInput(forms.DateInput): input_type = 'date' class MyActionForm(forms.ModelForm): class Meta: model = Action fields = '__all__' widgets = { 'due_date': DateInput(), } Is there a way to show the existing date (or blank if no date set) by default? Thanks in advance for your help. -
Why isn't Heroku's Postgresql updating according to Django's models.py?
Currently I'm running into issues with my models.py and Postgresql. The site is deployed on Heroku using Postgresql and the problem is models.py. Currently, I have models.py as a models.Charfield() and it works fine with sqlite, but when I deployed it to production, Postgresql still reports that it's a models.IntFied(). And because it's an integer field it won't allow for characters for some reason. Originally, I had it as a integerfield but decided to change to charfield, yet it still won't change to charfield. Solutions I've tried: resetting the database on heroku, deleting and recreating the database on heroku. Any help is appreciated, Thanks -
Django query child table from the parent table
This might be a really basic question and I tried my best to solve it after searching a lot. Im trying to have support for I18n for my table structure. I found a solution by using the below query. But I need the reverse approach (first get the main category and then look for the respective translation) without hitting the DB multiple times. Output Im expecting is to fetch all Main Category id's and names for a given language. main_category_trnanslations = MainCategoryTranslation.objects.filter(language_id='en').select_related('main_category') class MainCategory(models.Model): main_category_id = models.PositiveSmallIntegerField(primary_key=True) image = models.URLField(null=True) class Meta: db_table = 'lookup_main_category' class MainCategoryTranslation(models.Model): main_category = models.ForeignKey(MainCategory, on_delete=models.CASCADE) name = models.CharField(max_length=30) language_id = models.PositiveSmallIntegerField() class Meta: db_table = 'lookup_main_category_translations' -
How am i supposed to use onsubmit event in django template?
i am creating a website using django, i have added a little js for validation, but it's not working, i am newbie in js, so kindly help me. html snippet <form onsubmit=" return validate_bus()" action="confirm_bus/{{busname}}" method="post"> {% csrf_token %} <div id="left"> <label>Departure date</label> <input type="date" autocomplete="off" name="date" id="departuredate"> <br><br> <label>Username</label> <input type="text" name="username" id="BusUsername" autocomplete="off"> </div> <div id="right"> <label>Number of seats</label><br> <select autocomplete="off" name="seats" > <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <br> </select><br><br> <label> password</label> <input type="password" autocomplete="off" name="password" id="password"> </div> <label id="error_message">{{error_message}}</label><br> <button type="submit">Confirm booking</button> </form> and this is my js snippet function validate_bus() { var date = document.getElementById("departuredate").value; var username = document.getElementById("BusUsername").value; var seats = document.getElementById("seats").value; var password = document.getElementById("password").value; var date_regx = /^(19|20)\d\d([- /.])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])$/ var username_regx = /^[a-zA-Z0-9_$.@]+$/ var password_regx = /^(?=.*\d).{4,12}$/ var seats_regx = /[1-6]{1}/ var valid = true console.log(date, username, seats, password); if (! date_regx.test(date)) { valid = false; } if (! username_regx.test(username)) { valid = false; } if (! seats_regx.test(seats)) { valid = false; } if(! password_regx.test(password)) { valid = false; } if (!valid) { var error = document.getElementById("error_message").innerHTML = "invalid input"; } console.log(valid) return valid; }; whenever i run the code it says, TypeError: document.getElementById(...) is null -
Django - TemplateDoesNotExist Error / cant find .html file
django can not find .html file and return TemplateDoesNotExist Error! See image below. Views.py from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request, 'blog/home.html') def about(request): return HttpResponse('<h1>Blog About</h1>') Urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='blog-home'), path('about/', views.about, name='blog-about'),] Settings.py In setting.py everything is default i only changed one thing in TEMPLATES[]" 'DIRS': [os.path.join(BASE_DIR, 'template')], For more donwload codes rar file: https://drive.google.com/open?id=1zg5CN4IyqPtMMyvkru6fUYAQJcbmfX00 -
Error in Django Rest Framwork. 'str' object has no attribute 'pk'
Hi I'm trying to get the output from a Stored Procedure which I have written in MS SQL server into Rest API. I have succeeded in getting the Output. But I have failed in appending the output to rest api. Please help.... Here is my Serializers.py code: class Get_Count_Serializer(serializers.HyperlinkedModelSerializer): class Meta: model = ErRegisteredUsers fields = ('__all__') Here is my Views.py code: from django.db import connection from .serializers import * from .models import * from rest_framework import viewsets class Get_Count_Viewset(viewsets.ModelViewSet): cursor = connection.cursor() cursor.execute('EXEC [dbo].[ER_Get_Registration_Types_Count]') results = cursor.fetchone() #result = dict(results) queryset = results serializer_class = Get_Count_Serializer This is my URLS.py from django.urls import include, path from rest_framework import routers from . import views router = routers.DefaultRouter() router.register('Get_Count', views.Get_Count_Viewset, basename='Get_Count') # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path('admin/', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) The below is the error I'm getting: enter image description here -
django create_user() method wont be called
i have this problem for a month im using abstractbasemodel and basemanagerto create a login and signup api using rest framework but when i create a user password is saved raw synce i use set_password() method and custom model manager it confuses me please help me this is my code : class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('id' ,'email' ,'name' ,'password') extra_kwargs = { 'password':{ 'write_only':'True', 'style': {'input_type': 'password'} } } def create(self, validated_data): user = UserProfile.people.create_user( email = validated_data['email'], name = validated_data['name'], password = validated_data['password'] ) class UserProfileViewSet(viewsets.ModelViewSet): serializer_class = serializers.UserProfileSerializer queryset = models.UserProfile.people.all() authentication_classes = (TokenAuthentication, ) permission_classes = (UpdateOwnProfile, ) filter_backends = (SearchFilter, ) search_fields = ('name', 'email') class UserLoginApiView(ObtainAuthToken): renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES class UserProfileManager(BaseUserManager): def create_user(self, email, name, password=None): print("user model manager") if not email: raise ValueError('User Must Have an Email Address') email = self.normalize_email(email) user = self.model(email=email, name=name ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name, password): user = self.create_user(email, name, password) user.is_superuser = True user.is_staff = True user.save(using=self._db) return user class UserProfile(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) people = UserProfileManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] def get_full_name(self): return self.name def get_short_name(self): return … -
How to "collapse" Django constance database settings fieldsets?
I have next django constance database settings: CONSTANCE_CONFIG = { 'SEO_TITLE': ('', 'Сео заголовок'), 'SEO_DESCRIPTION': ('', 'Сео описание'), 'ERROR_TITLE': ('', 'Заголовок 404'), 'ERROR_DESCRIPTION': ('', 'Содержимое 404') } CONSTANCE_CONFIG_FIELDSETS = OrderedDict([ ('Seo', ('SEO_TITLE', 'SEO_DESCRIPTION')), ('Страница 404', ('ERROR_TITLE', 'ERROR_DESCRIPTION')) ]) I want to "collapse" fieldsets like this (model fieldsets in admin): class ModelClassAdmin(admin.ModelAdmin): fieldsets = ( ('SEO', { 'classes': ('collapse',), 'fields': ( 'SEO_TITLE', 'SEO_DESCRIPTION' ) }), ('404', { 'classes': ('collapse',), 'fields': ( 'ERROR_TITLE', 'ERROR_DESCRIPTION' ) }), ) How can I do it? -
How to set timezone for Africa/Lusaka in Django with MySQL Database
I am trying to set timezone for my country Zambia on my django project. In settings.py I have the code below TIME_ZONE = 'UTC' TIME_ZONE = 'Africa/Lusaka' USE_I18N = True USE_L10N = True USE_TZ = True And in my views.py I have imported timezone and passing it like so post.created_date = timezone.now(). Regardless of the changes I make after doing some research the time is still 2 hours behind. Is there something I am missing? Thanks for the help. -
Django Bad Reqsut 400 issue
Had this Django Project that constant had this 400 issue but it miraculously solves itself. 6 months went and some setting change within the server and now the bad request had come back to haunt us. I look up in this issue but every advice keeps saying the issue in 2 areas: Within the Django setting.py first DEBGU = Ture second ALLOW_HOST = [empty] I constantly relook over this fact to point I can even remember it in my sleep. I would bag anyone who had knowledge of network, please share some possible solution. -
Load multiple Django forms in the same page on button click
I am trying to design a single page site where i have a form initially and after entering some data and on clicking a button (say Submit) i want it to load 2nd form right below the first one and again entering some data and clicking another button will load the 3rd form below the 2nd form. I have succeeded in displaying the 2nd form but it immediately disappears after it is shown on the screen. I am not sure how to handle this to keep the 2nd one displayed and from there move to the next form. Below is my codes: views.py from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .forms import sampleForm, action RDS = '' def get_Nodes(request): form = sampleForm() if request.method == 'POST': form = sampleForm(request.POST) if form.is_valid(): RDS = form.cleaned_data['RDS'] print(RDS) form2 = action(request.POST) tmp = { 'form': form, 'form2': form2, } return render(request, 'form.html', tmp) def choice(request): if request.method == 'POST': form2 = action(request.POST) if form2.is_valid(): choose = form2.cleaned_data['choose'] print(choose) form2 = action() return render(request, 'form2.html', {'form': form2}) forms.py from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit class sampleForm(forms.Form): RDS = forms.CharField(label='RDS IP Address: ') def __init__(self, … -
Django sending email with template
I want to send email using Django. In the mail body , I want to send Bootstrap "Card" which contain "Image" and HTML content. Sending mail is successful. But, It is not showing the image in the received mail. Also, It is not in the Bootstrap "Card" format. Please some one help me. views.py emailSubject = "Mail from XYZ.COM" emailOfSender = EMAIL_HOST_USER emailOfRecipient = viewed_bog.profile.user.email html_content = render_to_string('receipt_email.html', {'item': viewed_bog, }, request=request) try: emailMessage = EmailMultiAlternatives(subject=emailSubject, body=html_content, from_email=emailOfSender, to=[emailOfRecipient, ], reply_to=[emailOfSender, ]) emailMessage.attach_alternative(html_content, "text/html") emailMessage.send(fail_silently=False) except SMTPException as e: print('There was an error sending an email: ', e) receipt_email.html This is the HTML template containing Bootstrap 4 "Card" using Django-templating language. With in the Card I am having Image. Now, I am able to send mail successfully. But Image is not showing in the received mail. and also, mail body is not in the "Card" format. -
pass django HTML template variables to javascript file
First of all, I have read almost all the posts about passing Django HTML template variables to JS but I couldn't find any answer fitting my question. I am having a forloop generating forms, so I use django HTML template variables to make an ID for each new form, and i would like to use the ID of that form in a separate JS file. I can't figure out the best way to get these form IDs into my js file. Here is a piece of my HTML code..: {% if trains.count > 1 %} <h2><b>You have worked on {{ trains.count }} trains today. Affect the cars you have worked on today to the trains:</b></h2> {% for train in trains %} <h3><b>{{ train }}</b></h3> <form method="POST" id="affect_car_{{train}}" action="{{'AffectedCar'}}" class="form-style-5"> {% csrf_token %} <select class="limitedNumbSelect2" id="car-list" multiple="true" required style="width: 400px;"> {% for car in cars %} <option value="{{car.id}}" name="{{car.id}}" id={{car.id}}>{{car.name}}</option> {% endfor %} </select> </form> {% endfor %} {% endif %} I saw some people doing it by declaring a var in a script inside the html template, but how would I know how many of them are existing when in the JS part? Thanks for your help! -
Heroku: installing Postgres without local db | Django
I've already pushed my Django files to Heroku via Git and now I'd like to configure at Heroku server the Postgres database. After that, I need to transfer my local sqlite database to Heroku Postgres. All of this issue is because I don't have admin rights on my local PC (corporate unit) to install Postgres. So basically: 1. Configure remotely Postegres at Heroku; 2. Migrate local database (sqlite) to Heroku (Postgres). I don't know if there is another path to go on... Thank you! -
Django Models - One to Many or Many o Many
In Django there are no One-to-Many relationships, there are just Many-to-One. In cases where defining Foreign Key on the child table is odd, should we go for Many-to-Many? For example: Book has many pages. If we define foreign key on the Page model, then the page has one book which is not an intuitive thing to do (or say). OPTION 1: class Book(models.Model): name = models.CharField(max_length=100) date_published = models.DateTimeField(default=timezone.now) class Page(models.Model): page_number = models.IntegerField() page_text = RichTextField() book = models.ForeignKey(Book, on_delete=models.CASCADE) OPTION 2 class Book(models.Model): name = models.CharField(max_length=100) date_published = models.DateTimeField(default=timezone.now) pages = models.ManytoMany(Page) class Page(models.Model): page_number = models.IntegerField() page_text = RichTextField() In option2 I can access the pages of the book by book.pages. In option 1 I don't know how to access the pages, maybe book.pages_set.objects.all() which is not pretty. I asked a fellow programmer and he said just use Many-to-Many. I understand what each approach means and I also understand the difference between the two as to what's happening in the database. My question is what is a better/standard approach. -
How to use the django-rest-captcha in client and server?
The django-rest-captcha docs provide the simple usage of it, but I still have questions, how to use it in detail. in client, there is the example: curl -X POST http:localhost:8000/api/captcha/ | python -m json.tool { 'image_type': 'image/png', 'image_decode': 'base64', 'captcha_key': 'de67e7f3-72d9-42d8-9677-ea381610363d', 'captcha_value': '... image encoded in base64' } we know we can use the captcha_value to generate the image, and send the { username, password, captcha_key, captcha_value (the text of generated image shows) } to server. but the docs do not have a RegisterView example, I do not understand how to use it. At present, my code is like this: serialisers.py: UserModel = get_user_model() class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) def create(self, validated_data): user = UserModel.objects.create( username=validated_data['username'] ) user.set_password(validated_data['password']) user.save() return user class Meta: model = UserModel # Tuple of serialized model fields (see link [2]) fields = ( "id", "username", "password", ) views.py from django.contrib.auth import get_user_model # If used custom user model from .serializers import UserSerializer class CreateUserView(CreateAPIView): model = get_user_model() permission_classes = [ permissions.AllowAny # Or anon users can't register ] serializer_class = UserSerializer how to change my view? -
Django: For each loop with counter that loads queryset in small sets
I am building an online store that displays cards containing products passed into the template as a queryset. The list of products will get large so I want to implement an incremental load that starts with 10 products and there is a button to load 10 more... and that would continue until eventually all the products are displayed. I currently have a for each loop in the template and I was wondering what the best approach would be to add some sort of counting mechanism into the loop so that I am able to achieve the incremental load. Any idea how I can do this? views.py def products_page_all(request): resetDefaultFilters() products = Product.objects.order_by('?') args = { 'products': products, } return render(request, 'store/products-page.html', args) products-page.html ... {% for product in products %} <-- I want this to only iterate for 10 products at a time <a href="{% url 'store-view-item' product.product_id %}"> <div class="col-lg-3 col-md-4 col-sm-6 col-xs-4 my-auto"> <div class="card h-100 rounded-0 border-0"> <div class="img-wrapper"> <div class="image"> <img src="{{ product.product_image.url }}"> </div> </div> <div class="card-body text-center"> <h4 class="card-title"> <a id="product-name">{{ product.product_name }}</a> </h4> <p id="seller-name">// {{product.seller.seller_listing_name }} //</p> <p class="card-text" id="product-description">{{ product.description_short }}</p> <h5 id="product-price">${{ product.price | floatformat:2 }}</h5> </div> </div> </div> </a> …