Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 ! -
Why my background picture is not loading in my webite?
this one is snipsets of my css file body { background-image: url(../img/backgroung.jpg); color: #333333; margin-top: 5rem; } this one is my settings.py file STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' CRISPY_TEMPLATE_PACK = 'bootstrap4' LOGIN_REDIRECT_URL = 'blog-home' LOGIN_URL = 'login' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('DB_USER') EMAIL_HOST_PASSWORD = os.environ.get('DB_PASSWORD') this one is my base.html file <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.0/css/bootstrap.min.css" integrity="sha384- SI27wrMjH3ZZ89r4o+fGIJtnzkAnFs3E4qz9DIYioCQ5l9Rd/7UAa8DHcaL8jkWt" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'stripes_blog/main.css' %}"> {% if title %} <title> STRIPES - {{ title }} </title> {% else %} <title> STRIPES </title> {% endif %} </head> I tried everything and still it's not working, i don't know where am i lacking behind. -
TypeError: 'method' object is not subscriptable Python/django
I have a test case that is returning the following error. Traceback Traceback (most recent call last): File "/usr/lib/python3.7/unittest/mock.py", line 1255, in patched return func(*args, **keywargs) File "/dir/to/project/Anwser/qanda/tests.py", line 29, in test_elasticsearch_upsert_on_save q.save() File "/dir/to/project/Anwser/qanda/models.py", line 40, in save elasticsearch.upsert(self) File "/dir/to/project/Anwser/qanda/service/elasticsearch.py", line 54, in upsert doc_type = question_dict['_type'] TypeError: 'method' object is not subscriptable Here is the function that lives inside elasticsearch.py def upsert(question_model): client = get_client() question_dict = question_model.as_elastic_search_dict doc_type = question_dict['_type'] del question_dict['_id'] del question_dict['_type'] response = client.update( settings.ES_IDENX, question_dict, id=question_model.id, body={ 'doc': doc_type, 'doc_as_upsert': True, } ) return response As i have read other threads about similar issues, i came to a conclusion that the problem relies in __getItem(self)__ of the object that is calling the function. Since the function should return a dictionary, it returns a method instead. Here is the function inside of model. def as_elastic_search_dict(self): return { '_id': self.id, '_type': 'doc', 'text': '{}\n{}'.format(self.title, self.question), 'question_body': self.question, 'title': self.title, 'id': self.id, 'created': self.created, } TestCase: class QuestionSaveTestCase(TestCase): """ Testing Question.save() """ @patch('qanda.service.elasticsearch.Elasticsearch') def test_elasticsearch_upsert_on_save(self, ElasticSearchMock): user = User.objects.create( username='unittest', password='unittest' ) question_title = 'Unit test' question_body = 'Some unit test' q = Question(title=question_title, question=question_body, user=user) q.save() self.assertIsNotNone(q.id) self.assertTrue(ElasticSearchMock.called) mock_client = ElasticSearchMock.return_value mock_client.update.assert_called_once_with( settings.ES_IDENX, id=q.id, … -
Can I get all flags, switches and samples in django waffle in one call?
I need to get all configured properties in the user context. I was wondering if there was a more efficient way of getting all of them at once, the documentation of waffle didn't seem to mention any such facility -
Every day reset a field to "0"
I need that every day at 00:00am, reset a studied_today field to 0. original code: models.py from django.db import models from django.conf import settings class Studied(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) studied_today = models.IntegerField(default=0) def __str__(self): return self.collection.title I try it: $ pip install schedule after, I change the original code: from django.db import models from django.conf import settings import schedule class Subscription(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING) studied_today = models.IntegerField(default=0) def __str__(self): return self.collection.title def job(): studied_today = 0 schedule.every().day.at("00:00").do(job) What did I do wrong and how can I do this? Any suggestion? -
How to custom folder structure in django using unipath library
enter image description here import os,sys from unipath import Path Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file))) PROJECT_DIR = Path(file).ancestor(2) PROJECT_APPS = Path(file).ancestor(2) sys.path.insert(0, Path(PROJECT_APPS, 'apps')) -
Grading System in Django
Is there any Source code in Django that the teachers gives grade to their students? please send link. cause I am now done in file maintenance in admin site, and now I am doing teacher user where the teacher will give grades to their students this is the model of file maintenance class configuration(models.Model): Pending_Request = [ ('Active', 'Active'), ('Inactive', 'Inactive'), ] Description = models.CharField(max_length=500, null=True) Status = models.CharField(max_length=500, null=True, choices=Pending_Request, blank=True) def __str__(self): suser = '{0.Description}' return suser.format(self) class gradeScalesSetting(models.Model): Pending_Request = [ ('Active', 'Active'), ('Inactive', 'Inactive'), ] configuration_select = models.ForeignKey(configuration, related_name='+', on_delete=models.CASCADE, null=True) NumberOfGrades = models.IntegerField(blank=True, null=True) Rounding = models.CharField(max_length=500, null=True) Precision = models.IntegerField() Status = models.CharField(max_length=500, null=True, choices=Pending_Request, blank=True) def __str__(self): suser = '{0.configuration_select}' return suser.format(self) class gradescale(models.Model): Pending_Request = [ ('Active', 'Active'), ('Inactive', 'Inactive'), ] configuration_select = models.ForeignKey(configuration, related_name='+', on_delete=models.CASCADE, null=True) Display_Sequence = models.IntegerField() Symbol = models.CharField(max_length=500, null=True) LowerLimit = models.FloatField() GPAValue = models.FloatField() Description = models.CharField(max_length=500, blank=True) Status = models.CharField(max_length=500, null=True, choices=Pending_Request, blank=True) def __str__(self): suser = '{0.Description}' return suser.format(self) class gradingCategories(models.Model): Pending_Request = [ ('Active', 'Active'), ('Inactive', 'Inactive'), ] Display_Sequence = models.IntegerField() CategoryName = models.CharField(max_length=500, null=True) PercentageWeight = models.FloatField() Calendar = models.BooleanField(null=True, blank=True) MaximumItemsPerPeriod = models.IntegerField(blank=True, null=True) Status = models.CharField(max_length=500, null=True, choices=Pending_Request, blank=True) def … -
Heroku seems to be stripping out the JSON from POST requests
I can run my code locally and it works just as I want, but when I run it in Heroku it returns NoneTypes for everything and seems like it has no data in the request. from django.shortcuts import render from rest_framework import generics from rest_framework.response import Response from rest_framework.reverse import reverse from rest_framework.decorators import api_view import psycopg2 @api_view(['GET', 'POST']) def testVert(request): user = request.data.get('username') password = request.data.get('password') response = { "user": user, "pass": password } return Response(data=response) #request.readline() The readline also works on my local computer, but not on Heroku. I'm wondering if maybe there are some Heroku settings or if I need to look for the data elsewhere after it goes through Heroku's stuff. Thanks for any help! -
django how to show list of category in blog and by clicking category show specific list of category
I have tried many ways i am new to django, but i couldn't able to solve that show list of specific category post from category section in html slider this how actually i wanted and clicking go to desire list of category post i did able to go to category list from post category but **couldn't able to go from category slider in index page ** how can i do that this style is working to go specific category but i also wanted do like above image models.py class Category(models.Model): title = models.CharField(max_length=20) thumbnail = models.ImageField() detail = models.TextField() def __str__(self): return self.title def get_absolute_url(self): return reverse('post-category', kwargs={ 'pk': self.pk }) class Post(models.Model): title = models.CharField(max_length=100) overview = models.TextField() featured = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True) #content = HTMLField() user = models.ForeignKey(Author,on_delete=models.CASCADE) thumbnail = models.ImageField() category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.title views.py class IndexView(TemplateView): model = Post model = Recipe model = Category template_name = 'shit.html' context_object_name = 'queryset' def get_context_data(self, **kwargs): recents = Post.objects.order_by('-timestamp')[0:4] recipe = Recipe.objects.filter()[0:2] category = Category.objects.all()[0:4] context = super().get_context_data(**kwargs) context['recents'] = recents context['recipe'] = recipe context['category'] = category return context class PostCategory(ListView): model = Post template_name = 'cat.html' def get_queryset(self): self.category = get_object_or_404(Category, pk=self.kwargs['pk']) … -
How to show popup "Success" or "Error" after I clicked the update button in which it is a modal
I am working on this employee registration project and Im not exactly sure how to implement this one on django. How could I show popupbox or like a small modal box "Success" or "Error" after I clicked the update button? It would be success if they have input all the necessary details on the modal. And error if they forgot to enter some details. Here is the views.py def save_employee_update(request): print(request.POST) emp_id = request.POST['employee_id'] fname = request.POST['first_name'] midname = request.POST['middle_name'] lname = request.POST['last_name'] pr_address = request.POST['present_address'] pm_address = request.POST['permanent_address'] zcode = request.POST['zipcode'] bday = request.POST['birthday'] email = request.POST['email_address'] pagibig = request.POST['pagibig_id'] sss = request.POST['sss_id'] tin = request.POST['tin_id'] sg_pr_id = request.POST['solo_parental_id'] # rg_sched = request.POST['reg_schedule'] usid = request.POST['userid'] defpass = request.POST['default_pass'] ustype = request.POST['user_type'] # j_title = request.POST['JobTitle'] employee = Employee.objects.get(employee_id=emp_id) employee.first_name = fname employee.middle_name = midname employee.last_name = lname employee.present_address = pr_address employee.permanent_address = pm_address employee.zipcode = zcode employee.birthday = bday employee.email_address = email employee.pagibig_id = pagibig employee.sss_id = sss employee.tin_id = tin employee.solo_parental_id = sg_pr_id # employee.reg_schedule = rg_sched employee.userid = usid employee.default_pass = defpass employee.user_type = ustype # employee.JobTitle = j_title employee.save() return render(request, 'index.html') Here is the modal <!-- Modal --> <div class="modal fade" id="employee.employee_id_{{ employee.employee_id }}" … -
Unable to connect to cloudamqp
I’m using python pika to connect to RabbitMQ but I keep getting an error: ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it My configuration is: am_url = 'amqp://xxxxxx:xxxxxxxxx@xxxxxx.rmq.cloudamqp.com/xxxxxxxx' url = os.environ.get('CLOUDAMQP_URL', am_url) params = pika.URLParameters(url) connection = pika.BlockingConnection(params) Am I configuring it wrong? -
django oauth toolkit with python social auth for android user from social platform
So i am using django-oauth-toolkit in order to provide oauth2 authentication for my android application. Now i have to implement social(facebook, google) authentication. And my workflow should be like when user hits signup with facebook button it does authorize successfully thanks to python social auth. So as it is supposed to be, python social auth does create user and it is fine. Now, this case works fine on side of web user. Problem is how can i handle android user tries to login with facebook?, Do i have to pass facebook authorization token to oauth toolkit? -
webpack font names rename to new name and in browser get not found error
I am using webpack with Django. in my .scss file: @font-face { font-family: 'Lato'; src: url(fonts/lato/Lato-Regular.ttf) format('truetype'); } @font-face { font-family: 'Lato Black'; src: url(fonts/lato/Lato-Black.ttf) format('truetype'); } after it in console: 06e1c8dbe641dd9dfa4367dc2a6efb9f.ttf 586 KiB [emitted] 3b0cd7254b3b6ddb8a313d41573fda8b.ttf 600 KiB [emitted] 6d4e78225df0cfd5fe1bf3e8547fefe4.ttf 593 KiB [emitted] 72c6dd530f0acc74b5286a7dcfa9e2d8.ttf 589 KiB [emitted] a54bddbc1689d05277d2127f58589917.ttf 570 KiB [emitted] bundle.js 595 KiB main [emitted] main and finally in the browser, I am getting an error like this: test_page:1 GET http://127.0.0.1:8000/static/b23d682ec78893e5b4598ecd6dfb1030.ttf net::ERR_ABORTED 404 (Not Found)