Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
trying to show the full blog on a new html page after clicking on read more button in the blog card in django
I am working on a blogging website in django. I have a few blogs and I am loading them in the card from my database.My card has a read more button(To go to new HTML page and dynamically fetch the contents of the particular blog). Instead of creating a new html page for every blog I am using a single html page to show the contents of the blog from the read more button clicked on card. but I am getting the following error: Reverse for 'post_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P[-a-zA-Z0-9_]+)\/$'] Request Method: GET Request URL: http://127.0.0.1:8000/blogs/ Django Version: 2.2.6 Exception Type: NoReverseMatch Exception Value: Exception Location: C:\django\lib\site-packages\django\urls\resolvers.py in_reverse_with_prefix, line 673** Thanks alot in advance models.py class blog(models.Model): STATUS_CHOICES=( ("scholarship","Scholarship"), ("examination","Examination"), ("career","Career"), ("fellowship","Fellowship") ) blog_image=models.ImageField(upload_to='blog_media',default="") blog_title=models.CharField(max_length=300) slug = models.SlugField( max_length=200, unique=True) blog_type = models.CharField( max_length=50, choices=STATUS_CHOICES, default="scholarship" ) blog_author_name=models.CharField(max_length=200) blog_content=models.CharField(max_length=5000) publish_date=models.DateField() urls.py: urlpatterns = [ path('',views.index,name='home'), path('blogs/',views.blogs,name='blogs'), path('about/',views.about,name='about'), path('admissions/',views.admissions,name='admissions'), path( '<slug:slug>/', views.PostDetail.as_view(), name='post_detail' ),] views.py class PostDetail(DetailView): #my model name is blog model = blog #this is the html page on which I want to show the single blog data template_name = 'buddyscholarship_html/post_detail.html' code for loading the dynamic data from django in html in a … -
How To Fix QueryDict object is not callable in Django?
When i add the recaptcha in my site i'm getting this error please help me! This is error i'm getting again and again I Want to Fix My This Issue: TypeError at /accounts/register 'QueryDict' object is not callable Request Method: POST Request URL: http://127.0.0.1:8000/accounts/register Django Version: 2.2 Exception Type: TypeError Exception Value: 'QueryDict' object is not callable Exception Location: D:\Learning\Work\Djngo\todo_app\todo\views.py in signup, line 24 Python Executable: C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.0 Python Path: ['D:\\Learning\\Work\\Djngo\\todo_app', 'C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip', 'C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs', 'C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\lib', 'C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\\Python37-32', 'C:\\Users\\Lenovo\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages'] Server time: Tue, 3 Dec 2019 08:58:29 +0000 But I Can't Here is my views.py def signup(requests): ############################### if requests.method == 'POST': reg = register(requests.POST) ############ clientKey = requests.POST['g-recaptcha-response'] secretKey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' captchaData = { 'secret': secretKey, 'response': clientKey } r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=captchaData) response = json.loads(r.text) verify = response['success'] print('Result: ' + verify) if reg.is_valid(): user = reg.save(commit=False) user.set_password(User) user.save() messages.success(request, 'You Are SuccessFully Registerd!') else: print(reg.errors) else: reg = register() return render(requests,'signup.html',{'reg':reg,}) Any Help Will Be Appreciated! Thanks! -
Best Django 2 tutorial series on youtube in english
I am looking for the best Django 2.0+ tutorial series on youtube. Help me with your thoughts. Thanks, in advance -
When i tried to run auth login api getting error : The current path, api/auth/login/, didn't match any of these
When i tried to run api http://127.0.0.1:8000/api/auth/login/, It gives me this error : Using the URLconf defined in djangoproject.urls, Django tried these URL patterns, in this order: admin/ api/(?P<version>(v1|v2))/ ^ ^users/$ [name='user-list'] ^ ^users\.(?P<format>[a-z0-9]+)/?$ [name='user-list'] ^ ^users/(?P<pk>[^/.]+)/$ [name='user-detail'] ^ ^users/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='user-detail'] ^ ^$ [name='api-root'] ^ ^\.(?P<format>[a-z0-9]+)/?$ [name='api-root'] ^auth/ The current path, api/auth/login/, didn't match any of these. Can anyone please check my urls.py and help me why i am getting this error ? urls.py from django.contrib import admin from django.urls import path, re_path,include from rest_framework import routers from django.conf.urls import url, include from trialrisk.views import UserViewSet router = routers.DefaultRouter() router.register(r'users', UserViewSet) urlpatterns = [ path('admin/', admin.site.urls), re_path('api/(?P<version>(v1|v2))/', include('trialrisk.urls')), url(r'^', include(router.urls)), url('^auth/', include('rest_auth.urls')), ] -
Why won't my UserCreationForm render in chronological order?
I want the form to show Username Email Password Password(2) At the moment, it is showing Username Password Password (2) Email I am trying to follow this tutorial https://www.youtube.com/watch?v=q4jPR-M0TAQ. I have looked at the creators notes on Github but that has not helped. I have double checked my code and cannot see any daft typos. Can anyone provide any insight? from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect ('blog-home') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form':form}) -
Mongodb with django?
If I use mongodb in django project with the help of djongo third-party api should I have to use commands migrate and makemigrations again n again when ever I make changes in my models?? -
Need WhatsApp chat Compatibility confirmation with ReactJS & Django
I am developing an ecommerce Web App using React & Python Django. I need to know whether GupShup API would be compatible with the above Technology Stack. -
Django Blogg App using Heroku: SyntaxError at / invalid syntax (parser.py, line 158)
I am a beginner programmer and I followed a django blog tutorial to deploy an app to Heroku. I have been stuck on the problem for quite a while now. This did not pop up on my localhost but after I deployed this app to heroku, now there is a syntax error. Can anyone help me? Environment:[enter image description here][1] Request Method: GET Request URL: https://mynewdjangoblogapp.herokuapp.com/ Django Version: 2.2.7 Python Version: 3.6.9 Installed Applications: ['blog.apps.BlogConfig', 'users.apps.UsersConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages'] Installed Middleware: ('whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware') Template error: In template /app/blog/templates/blog/base.html, error at line 0 invalid syntax 1 : {% load static %} 2 : 3 : 4 : 5 : 6 : 7 : 8 : 9 : 10 : Traceback: File "/app/.heroku/python/lib/python3.6/site-packages/django/template/base.py" in _resolve_lookup 829. current = current[bit] During handling of the above exception ('ImageFieldFile' object is not subscriptable), another exception occurred: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 145. response = self.process_exception_by_middleware(e, request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 143. response = response.render() File "/app/.heroku/python/lib/python3.6/site-packages/django/template/response.py" in render 106. self.content = self.rendered_content File "/app/.heroku/python/lib/python3.6/site-packages/django/template/response.py" in rendered_content 83. content = template.render(context, self._request) File "/app/.heroku/python/lib/python3.6/site-packages/django/template/backends/django.py" in render 61. return … -
Django QuerySet filter get queryset by id and other column(s)
I am trying to get my user instance as well as my team members' user instances in the same query. Unfortunately, I am getting an empty query set. I am trying this : users = User.objects.filter(invited_by=request.user.id, id = request.user.id) -
rendering forms for django PolymorphicModel
Hello I am asking this coz av been stack for over 2 weeks now trying to figure out how to do it right, I hope I get help. I have a Django model that I implemented PolymorphicModel my issue is I made the forms and the forms work fine when posting the first product but posting the second product, The first product is asking for a form model to render it yet am not trying to edit it. maybe my code will explain what am tring to say my main model class Product(PolymorphicModel): product_name = models.CharField(max_length=100) product_features = models.TextField(max_length=500, blank=True, null=True) product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE, null=True) post_date = models.DateTimeField() first child class PhoneTablets(Product): screen_size = models.DecimalField( "Screen size", max_digits=4, decimal_places=2, ) battery_type = models.CharField( "Battery type", max_length=200 ) battery_capacity = models.PositiveIntegerField(null=True, help_text="Battery capacity in mAh", ) second child class LaptopComputers(Product): size = models.PositiveIntegerField(null=True) weight = models.PositiveIntegerField(null=True, ) battery_type = models.PositiveSmallIntegerField(null=True, ) refurbished = models.BooleanField() my forms look like this PhonesTabsForm = polymorphic_modelformset_factory(Product, fields=product_fields, formset_children=( PolymorphicFormSetChild(PhoneTablets, fields=product_fields + ['screen_size', 'battery_type', 'battery_capacity', 'ram_storage', 'internal_storage']), )) LaptopsCompsForm = polymorphic_modelformset_factory(Product, fields=product_fields, formset_children=( PolymorphicFormSetChild(LaptopComputers, fields=product_fields + ['size', 'weight', 'battery_type', 'refurbished', 'operating_system', 'processor', 'processor_speed', 'battery_capacity', 'ram_storage', 'internal_storage'], ), )) my view is a conditional view class … -
Atom `script` add-on doesn't recognize Django Model/settings when running a script
It seems I run into some dependencies issues when trying to run a python script within my Django based web application using the atom add-on script. I would like to run the following script using the Atom script add-on: feeder.py: import zmq import time from time import sleep import uuid from models import AccountInformation context = zmq.Context() zmq_socket = context.socket(zmq.PULL) zmq_socket.bind("tcp://*:32225") time.sleep(1) while True: try: msg = zmq_socket.recv_string() data = msg.split("|") print(data) if (data[0] == "account_info"): version = data[1] DID = uuid.UUID(data[2]) accountNumber = int(data[3]) broker = data[4] leverage = data[5] account_balance = float(data[6]) account_profit = float(data[7]) account_equity = float(data[8]) account_margin = float(data[9]) account_margin_free = float(data[10]) account_margin_level = float(data[11]) account_currency = data[12] feed = AccountInformation( version=version, DID=DID, accountNumber=accountNumber, broker=broker, leverage=leverage, account_balance=account_balance, account_pofit=account_profit, account_equity=account_equity, account_margin=account_margin, account_margin_free=account_margin_free, account_margin_level=account_margin_level, account_currency=account_currency ) feed.save() # Push data to account information table else: print("no data") except zmq.error.Again: print("\nResource timeout.. please try again.") sleep(0.000001) Unfortunately it raises the following error: Traceback (most recent call last): File "C:\Users\Jonas Blickle\Desktop\dashex\Dashboard_app\feeder.py", line 5, in <module> from models import AccountInformation File "C:\Users\Jonas Blickle\Desktop\dashex\Dashboard_app\models.py", line 7, in <module> class AccountInformation(models.Model): File "C:\Program Files\lib\site-packages\django\db\models\base.py", line 103, in __new__ app_config = apps.get_containing_app_config(module) File "C:\Program Files\lib\site-packages\django\apps\registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "C:\Program Files\lib\site-packages\django\apps\registry.py", line … -
Compare two different classes based on their values
i'm trying to compare two variables based on their actual values but it's just not working and i thing it's because they are from different classes here's an example : models = Model_info.objects.all() m = 'X-POWER 3' for model in models: if m == model: check = 'accepted' print(check) break else: check = 'rejected' print(check) print(f'final resulte is {check}') knowing that the value of variable "m" do exist in the queryset "models" and : type(m) = < class 'str' > type(model) = < class 'application.models.Model_info' > So is their any method to compare the value of two variables no matter what class they belong to. -
Exception happened during processing of request from ('127.0.0.1', 57015)
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine Not Found: /favicon.ico Exception happened during processing of request from ('127.0.0.1', 57015) Traceback (most recent call last): File "C:\Users\Gautam Ankul\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "C:\Users\Gautam Ankul\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Users\Gautam Ankul\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 720, in init self.handle() File "C:\Users\Gautam Ankul\PycharmProjects\Projects\venv\lib\site-packages\django\core\servers\basehttp.py", line 171, in handle self.handle_one_request() File "C:\Users\Gautam Ankul\PycharmProjects\Projects\venv\lib\site-packages\django\core\servers\basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Users\Gautam Ankul\AppData\Local\Programs\Python\Python37\lib\socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine Not Found: /favicon.ico Exception happened during processing of request from ('127.0.0.1', 57015) Traceback (most recent call last): File "C:\Users\Gautam Ankul\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "C:\Users\Gautam Ankul\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Users\Gautam Ankul\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 720, in init self.handle() File "C:\Users\Gautam Ankul\PycharmProjects\Projects\venv\lib\site-packages\django\core\servers\basehttp.py", line 171, in handle self.handle_one_request() File "C:\Users\Gautam Ankul\PycharmProjects\Projects\venv\lib\site-packages\django\core\servers\basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Users\Gautam Ankul\AppData\Local\Programs\Python\Python37\lib\socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your … -
Migrating the data from MySQL to PostgreSQL facing with DATA ERROR
there is an error facing in retrieving the data from URL and parsing the data and storing it. It is retrieving only a few counts of data and throwing a data error in the terminal after the last feed It's like ( functions.py) -
How To Fix UnboundLocalError at /accounts/register In Python Django
I'm trying to add recaptcha3 in my django website but i'm getting this error again and again i don't know how to fix please help me: And Also Please Tell why i'm getting this error so if i get this error again i can fix it I'm Getting This Error: UnboundLocalError at /accounts/register local variable 'data' referenced before assignment Request Method: GET Request URL: http://127.0.0.1:8000/accounts/register Django Version: 2.2 Exception Type: UnboundLocalError Exception Value: local variable 'data' referenced before assignment Exception Location: D:\Learning\Work\Djngo\todo_app\todo\views.py in signup, line 13 Python Executable: C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.0 How To Fix That? Here is my code: views.py def signup(requests): secret_key = settings.RECAPTCHA_SECRET_KEY # captcha verification data = {'response': data.get('g-recaptcha-response'),'secret': secret_key,} resp = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data) result_json = resp.json() print(result_json) if not result_json.get('success'): return render(request, 'contact_sent.html', {'is_robot': True}) ############################### if requests.method == 'POST': reg = register(requests.POST) if reg.is_valid(): user = reg.save(commit=False) user.set_password(User) user.save() else: print(reg.errors) else: reg = register() return render(requests,'signup.html',{'reg':reg,'site_key': settings.RECAPTCHA_SITE_KEY}) signup.html {% extends 'base.html' %} {% block content_block %} <center> <form method="POST" class="signup mt-5"> <div class="form-group"> {% csrf_token %} {{reg.as_p}} <small id="emailHelp" class="form-text text-muted ">We'll never share your email with anyone else.</small> <input type="submit" value="Submit" style="width: 100%;" class="btn btn-dark mt-3"> </div> </form> </center> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" … -
How to embed HTML in SuccessMessageMixin?
How do I embed html code here. I tried using mark_safe, it didn't work class PostCreateView(SuccessMessageMixin, LoginRequiredMixin, CreateView): model = Post form_class = PostForm template_name = 'blogApp/create.html' success_url = '/' success_message = mark_safe( '<strong>%(title)s</strong> Created Successfully') Thank you in advance -
How to make a POST request using jquery and access POST data in a django view?
I have dictionary in javascript something like this: var data = {"name":"nitin raturi"} Now I want this data to be accessed in my django view something like this: def my_view(request): data = request.POST How to send data to my url using jquery? -
'QuerySet' object has no attribute 'images'
I want to retrieve a list of information belonging to a certain field in a database. But , I am getting 'QuerySet' object has no attribute 'images'error. models.py class Business(models.Model): business_name = models.CharField(max_length=50) business_location = models.CharField(max_length=200) business_description = models.TextField() def __str__(self): return self.business_name class BusinessImage(models.Model): business = models.ForeignKey(Business, related_name='images', on_delete =models.CASCADE) image = models.ImageField() views.py def get_data1(request, *args, **kwargs): b= Business.objects.filter(business_name="some-name") image_list = b.images.all() c = {'image_list': image_list} return render(request, "index.html", c) -
djoser activate account by link
How to activate after click on the link send by djoser? my settings ''' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'djoser', 'rest_framework', 'rest_framework_simplejwt', 'data', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES':( 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.SessionAuthentication', ), } EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_HOST_USER = 'technomancer7629@gmail.com' EMAIL_HOST_PASSWORD='naz@technomancer7629' EMAIL_PORT = 587 PROTOCOL = "http" DOMAIN = "127.0.0.1:8000" DJOSER = { 'PASSWORD_RESET_CONFIRM_URL': '/password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': '/username/reset/confirm/{uid}/{token}', 'ACTIVATION_URL': 'activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'SEND_CONFRIMATION_EMAIL':True, 'SERIALIZERS': {}, 'EMAIL':{ 'activation': 'djoser.email.ActivationEmail', }, } ''' urls.py ''' urlpatterns = [ path('admin/', admin.site.urls), path('auth/',include('djoser.urls')), path('auth/',include('djoser.urls.jwt')), path("api/data/",include("data.urls")), ] ''' my email link http://127.0.0.1:8000/auth/users/activate/Mjc/5bx-5f9542251fd9db7e980b error: Using the URLconf defined in startgo1.urls, Django tried these URL patterns, in this order: admin/ auth/ ^users/$ [name='user-list'] auth/ ^users\.(?P<format>[a-z0-9]+)/?$ [name='user-list'] auth/ ^users/activation/$ [name='user-activation'] auth/ ^users/activation\.(?P<format>[a-z0-9]+)/?$ [name='user-activation'] auth/ ^users/me/$ [name='user-me'] auth/ ^users/me\.(?P<format>[a-z0-9]+)/?$ [name='user-me'] auth/ ^users/resend_activation/$ [name='user-resend-activation'] auth/ ^users/resend_activation\.(?P<format>[a-z0-9]+)/?$ [name='user-resend-activation'] auth/ ^users/reset_password/$ [name='user-reset-password'] auth/ ^users/reset_password\.(?P<format>[a-z0-9]+)/?$ [name='user-reset-password'] auth/ ^users/reset_password_confirm/$ [name='user-reset-password-confirm'] auth/ ^users/reset_password_confirm\.(?P<format>[a-z0-9]+)/?$ [name='user-reset-password-confirm'] auth/ ^users/reset_username/$ [name='user-reset-username'] auth/ ^users/reset_username\.(?P<format>[a-z0-9]+)/?$ [name='user-reset-username'] auth/ ^users/reset_username_confirm/$ [name='user-reset-username-confirm'] auth/ ^users/reset_username_confirm\.(?P<format>[a-z0-9]+)/?$ [name='user-reset-username-confirm'] auth/ ^users/set_password/$ [name='user-set-password'] auth/ ^users/set_password\.(?P<format>[a-z0-9]+)/?$ [name='user-set-password'] auth/ ^users/set_username/$ [name='user-set-username'] auth/ ^users/set_username\.(?P<format>[a-z0-9]+)/?$ [name='user-set-username'] auth/ ^users/(?P<pk>[^/.]+)/$ [name='user-detail'] auth/ ^users/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='user-detail'] auth/ ^$ [name='api-root'] auth/ ^\.(?P<format>[a-z0-9]+)/?$ [name='api-root'] auth/ ^jwt/create/? [name='jwt-create'] auth/ ^jwt/refresh/? [name='jwt-refresh'] auth/ ^jwt/verify/? [name='jwt-verify'] api/data/ The current path, auth/users/activate/Mjc/5bx-5f9542251fd9db7e980b, didn't match any of … -
Python - Multiple type users with custom user model in django-allauth
I'm working on a project using PythoN(3.7) & Django(2.2) in which I have to create 4 different types of users with different fields but they will share some common fields like title & name etc. But I also need to use email as the username and need to provide different signup form but one login form. I'm currently using django-allauth to implement my user management and setup the email as the username. Here's what I did: From models.py: class CustomUser(AbstractUser): # add common fields in here def __str__(self): return self.email From forms.py: class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = '__all__' class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ('username', 'email', 'address') But i'm really confused how can I setupt he multiple type users as I need the following types of users: Personal Account - below 18 Personal Account - above 18 Parent Account Coach Account Admin 'Someone suggest that I should create separate apps for all type of users like personal, parent & coach and then add django-allauth within these apps and I will share the same login page in the parent app. But I don't know how it can be implement? How can I achieve this … -
Django 2.1.5 migration does not happen with makemigrations command
In our Django project(Django 2.1.5), every time we try to run the project we have to give the '--noreload' command in addition to the runserver command, else the project returns an error as, ValueError: signal only works in main thread We are using Django signals to communicate between the apps created in Django and Web-sockets in Threading aysnc-mode to connect between the other services involved in the project. When we try to deploy the project in Jenkins, this becomes a problem and we are using Nginx as the webserver for host the application. Is there any possibility to solve the issue of '--noreload' and run the application normally? We are not sure if its because of the same problem referred above but we have a problem when trying to migrate the changes in the Models in Django, it always returns No changes Detected After a quick internet search, we did the migrations by mentioning the app names and it did work, yet the terminal stays still after the migrating and waits to manually terminate the process. Is there a possible solution to overcome this? and also we would like to know where we go wrong -
Python/Django filter rows with max value in a group
I saw multiple answers on this, but none of the suggested solutions helped me. Model describes production plans for various units. Production plans are updated hourly. Each production plan is called 'layer' as they 'stack' upon each other during the day. Naturally, next 'layer' is one hour shorter than previous. Model is as follows: class PlanData(models.Model): plan_type = models.ForeignKey(PlanType, on_delete = models.CASCADE) # we only need type 2 here plan_ident = models.ForeignKey(ObjectConfig, on_delete = models.CASCADE) # decribes production unit plan_for_day = models.DateField() # the day of production cycle layer = models.IntegerField(null = True) #'layer' production plan from specified hour to then of the day. # layer 1 contains 24 values, layer 10 - 14 values hour = models.IntegerField() # hour of production val = models.FloatField(blank = True, null = True) # how much the unit should produce at that hour What I need is to filter PlanData by getting those where layer is maximum by grouping by plan_ident and hour. What I'm trying to do could be done in SQL like select a.plan_ident, a.hour, a.layer, a.val from dbo.asbr_plandata a inner join ( select max(layer) 'mlayer',plan_ident_id, hour from dbo.asbr_plandata where datediff(day,plan_for_day,getdate()) = 0 and plan_type_id = 2 and plan_ident_id in (24) … -
Why file upload is not working in Django after directed from other url?
I want to do a simple web applications to let user to choose a task, where one of the tasks require file upload. In home, user is prompted to select task 1 or 2. After 2 is selected, it will enter another page to prompt user to upload file. I tried to follow a tutorial online for file upload but it does not work the way I wanted. In views.py, I have the following functions: def home(request): return render(request,'home.html') def choice(request): name1=request.GET['name_1'] name2=request.GET['name_2'] if request.GET['choice']=='1':return render(request, "train.html",{"name1":name_1, "name2":name_2}) elif request.GET['choice']=='2':return render(request, "train.html",{"name1":name_1, "name2":name_2}) def predict(request): if request.method=="POST": document=request.FILES['document'] print(document.name) print(document.size) return render(request,'predict_home.html') For the urlpattern in urls.py, urlpatterns=[ path('',views.home,name='home'), path('choice',views.choice, name='choice'), path('predict',views.predict,name='predict'), ] The home.html is to prompt user to select task: <h2>Select a Task:</h2> <form action="choice"> <select name="choice"> <option value="1" selected >Train new model</option> <option value="2" >Prediction</option> </select> <br><br> System 1 is used to predict system 2 <br> Enter the name of system 1:<br> <input type="text" name="name1"><br> Enter the name of system 2:<br> <input type="text" name="name2"><br> <input type="submit"> </form><br><br> </form> The predict.html is the GUI to prompt user to upload file: <br><h3>{{name_1}} is used to predict {{name_2}}</h3> Upload profiler logs:<br> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="document"><br><br> … -
How to serialize update on DRF with a modified listField
I have a serializer like this: class Serializer(serializers.ModelSerializer): main_field = ListField(child=serializers.CharField(), required=True) fields = ( "main_field", "field_a", "field_b", "field_c", ) def update(instance, validated_data): data = deepcopy(validated_data) instance.filter(main_field=data.pop("main_field")).update(**data) return validated_data The thing is that when i update, then i call this return on my view: return Response(status=status.HTTP_200_OK, data=serializer.data) that's when serializer.data fails to be called because it was expecting all the fields, not just the partial ones. logic: When i update i have to update all the fields on the rows called by the main_field list. So all of them should be grouped by the main_field list with the same other fields. im using django 1.11 (can not do anything about that tbh). -
How to pass a list from template( html) to view in Django?
How to pass a list from template( html) to view in Django ? I need to pass a list from template to a view using url <div class="media-option btn-group shaded-icon"> {% with uplist=group_list %} <button class="btn btn-small" id="button2"> <a href="{% url 'upload_all_to_group' uplist %}"> <i class="icon-plus">Proceed</i> </a> </button> {% endwith %} </div> Here uplist a list, i need to pass it into the view function (upload_all_to_group). Another problem is , How to specify in urls.py for request matching. url(r'^auth_app/upload_all_to_group/(?P(.*))/$', views.upload_all_to_group, name="upload_all_to_group"), I tried this method. but it's not working. IndexError at /auth_app/auth_app/upload_all_to_group/[['user1', 'RND1', '17-11-2019', 'cc'], ['user3', 'RND2', '08-02-2018', 'ncv'], ['user1', 'group1', '02-02-2018', 'sf'], ['user23', 'RND3', '16-12-2019', 'der'], ['user2', 'RND3', '25-06-2018', 'ddd']]/ This was the error , while pushing this method . How to handle the list in url pattern and view ? Thanks in advance !