Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What does binascii.hexlify(os.urandom(32)).decode() mean?
I'm trying to develop a function which would refresh token model in django rest framework.They seem to use binascii.hexlify(os.urandom(32)).decode() for generating unique tokens for every user.How does this line ensures that token generated by it will always be unique.Suppose if i want to refresh content of token after every 10 months ,then, will binascii.hexlify(os.urandom(32)).decode() will generate unique key that has not been used by any current user or i need to check whether it is being used or not? -
Django TinyMce was installed but is not working
I've installed django-tinymce and it works on my pc very well. But when I pushed to github, and downloaded to my Mac. When I want to run server it shows error as following: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[1] File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'tinymce' -
Javascript to Django
var upload = function(files) { $.ajax({ type: 'POST', processData: false, contentType: false, cache: false, data: {csrfmiddlewaretoken:'{{csrf_token}}', files:files}, enctype: 'multipart/form-data', url: 'files/', }); } I try to send files to Django but I am getting this error. jquery-3.4.1.min.js:2 POST http://localhost:8000/upload/files/ 403 (Forbidden) -
Django: How to download all files as zip when button is clicked?
I've seen so many answers on how to serve zip files for download in Django but no one is explicitly telling how to call it in the client side. Maybe the answer is too obvious but I really don't get it. I have a datatable and I've included a download button in each row. When the user clicks it, all associated files will be downloaded as zip. Here's my code: In my views.py: def download_zipfile(self, request): filelist = [MyModel.path_to_file1, MyModel.path_to_file2, MyModel.path_to_file3] byte_data = BytesIO() zip_name = "%s.zip" % MyModel.id_no zip_file = zipfile.ZipFile(byte_data, 'w') for file in filelist: filename = os.path.basename(os.path.normpath(file)) zip_file.write(file, filename) zip_file.close() response = HttpResponse(byte_data.getvalue(), content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=%s' %zip_name zip_file.printdir() return response In my urls.py I have: urlpatterns = [ path('download/<int:pk>', download_zipfile, name='download_zipfile'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In my html template I have: <tr id="datarows"> <td>{{ mymodel.data1 }}</td> <td>{{ mymodel.data2 }}</td> <td>{{ mymodel.data3 }}</td> <td> <a href="{% url 'download_zipfile' mymodel.pk %}" target="_blank"> <i class="fas fa-download"></i> </a> </td> </tr> And I keep getting this error: django.urls.exceptions.NoReverseMatch: Reverse for 'download_zipfile' with arguments '('',)' not found. 1 pattern(s) tried: ['download/(?P<pk>[0-9]+)$'] I would really appreciate it if anyone would be able to help. Thanks in advance! -
Retrieve query from django ORM with related fields
I created a Company in my django app, two or more person can login with the same company. I want to show the data of one user of the company to the other user of the company. To simplify: If one user of a company creates an object, then it should be visible to all the users of that company But I am having trouble extracting the data Models.py class ItemBatch(models.Model): uploaded_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='uploaded_by') name = models.CharField(max_length=100) pid = models.IntegerField(blank=True) quantity = models.IntegerField(blank=True) class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='ship_company') class User(AbstractUser): is_supplier = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) email = models.EmailField(default=False) class Company(models.Model): company_name = models.CharField(max_length=255, default=0) company_email = models.EmailField(max_length=255, default=0) company_phone = models.CharField(max_length=255, default=0) company_code = models.IntegerField(default=0) Views.py class allordersview(viewsets.GenericViewSet, mixins.ListModelMixin): queryset = ItemBatch.objects.all() serializer_class = holdSerializer def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) queryset = queryset.filter(uploaded_by_id=request.user) # ??Changes?? . . return Response(serializer.data) How to change the queryset such that it shows all ItemBatch of a Company ?? -
To put or not to put slash ("/") at the end of each url path
I know that using formerly url() there is a difference whether or not I put slash ("/") at the end of a sentence i.e. url(r'^fees_pricer/(?P<product>[\w-]+)/$', views.fees_pricer, name='fees_pricer'), I realized that I got the same result if I write: path('fees_pricer/<slug:prod>', views.fees_pricer, name='fees_pricer'), or path('fees_pricer/<slug:prod>/', views.fees_pricer, name='fees_pricer'), I am wondering if there is a difference or any best practice about putting shlash at the end of each path. Many thanks in advance for your answer. -
Django: How to set choices in a form to a Select widget
I am wondering if someone could help to figure out how to set initial choices to a CharField which has Select widget applied on a form level without overwriting the Meta class data(such as verbose_name coming from model level)? My form looks like that: from django.forms.widgets import Select class AssessmentFormModelForm): def __init__(self, *args, **kwargs): super(AssessmentForm, self).__init__(*args, **kwargs) # Intial choices set here (DOESN'T work) self.fields['test_taker_report_uid'].choices = [('', 'Placeholder')] class Meta: model = Assessment fields = ( 'test_taker_report_uid', ) widgets = { 'test_taker_report_uid': Select2, } I in fact know that I can make it work by removing widgets from Meta and adding it as a: class AssessmentFormModelForm): test_taker_report_uid = ChoiceField( widget=Select, choices=[('', 'Placeholder')] ) def __init__(self, *args, **kwargs): but it is annoying cause it overwrites verbose_name which i have specified on a model level, which i want to keep intact. -
django-paypal showing page not found when trying to checkout
I was able to install django-paypal and also created a sandox account, but the problem is when i try to checkout the process-payment display no page found. I think this have to do with the view.py or maybe the Order. How do i make this work properly? Model.py: class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) billing_address = models.ForeignKey('BillingAddress', on_delete=models.SET_NULL, blank=True, null=True) def __str__(self): return self.user.username def get_total(self): total = 0 for order_item in self.items.all(): total += order_item.get_final_price() return total Views.py: def process_payment(request): order_id = request.session.get('order_id') order = get_object_or_404(Order, id=order_id) host = request.get_host() paypal_dict = { 'business': settings.PAYPAL_RECEIVER_EMAIL, 'amount': '%.2f' % order.get_total().quantize( Decimal('.01')), 'item_name': 'Order {}'.format(order.id), 'invoice': str(order.id), 'currency_code': 'USD', 'notify_url': 'http://{}{}'.format(host, reverse('paypal-ipn')), 'return_url': 'http://{}{}'.format(host, reverse('shop:payment-done')), 'cancel_return': 'http://{}{}'.format(host, reverse('shop:payment-cancelled')), } form = PayPalPaymentsForm(initial=paypal_dict) context = { 'form': form, 'order': order } return render(request, 'process_payment.html', context) -
Django anonymous session issue
I have this anonymous session middleware: from __future__ import unicode_literals from importlib import import_module from django.conf import settings class AnonymousSessionMiddleware(): """This middleware is used for anonymous testing, creates an anonymous session. """ def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = None if not response: response = self.get_response(request) if hasattr(self, 'process_request'): self.process_request(request) return response def process_request(self, request): if not request.user.is_authenticated and not request.session.session_key: engine = import_module(settings.SESSION_ENGINE) request.session = engine.SessionStore() request.session.create() And in my View I want to get the session_key (session_key = request.session.session_key) but it always be None. I think the problem is in my middleware because the def process_request(self, request) method runs after the View. What would be the best solution to launch this method first to create a new session before the View function gets called? -
save some information from form that is images and some other information
this is views.py each = seller(state=state,city=city,full_address=full_address,pro_img=out,username=userName, bedroom_no=bedroom_no,kitchen_img=kithen_img,swimming_img=swimming_img,phone=phone ,email=email,price=price,floor=floor,squre=squre,gerden_img=garden_img) but a problem is occur "getattr(): attribute name must be string" now what i do -
How to change two models using a single foreign key?
So I have a model Part which contains ConnectedTo, which is a models.ForeignKey('self'). This is supposed to function in the same way the naming suggests. If a part is connected to another part, it is listed. My problem comes when dealing with the first object created, and linking objects to parts not yet created. If I have a Part A, then it is connected to nothing because no other objects exist yet. Even though I know it is connected to B which doesn't exist yet. I can create B and refer it to the other part when I create it, but this does nothing to change the ConnectedTo value in A. I could easily write something to change both whenever something is added, but this system is designed to become quite large scale and I feel like I need a more automatic solution before it gets out of hand. -
How Do I open different views based on url in django
I'm just starting to use django so bear with me. I'm currently trying to open different template based on the url I got , for example path("<int:pk>",views.OptionView.as_view(),name = 'eachoption') What I want to do is to open a different view based on the value of the pk I got , I've searched for a while but still got no luck, can anyone help me ? :/ -
Python - Multiple user types implementation in Dajngo 2.2
I'm working on a project using Python(3.7) and Django(2.2) in which I have to implement four types of users as (1): Personal - Below 18 (2): Personal 18 or Above (3): Coach (4): Parent, each user will share some basic fields like First & Lat name, Email, Gender, Account type but also will have different permissions, dashboards and functions and need to provide different signup forms but one login form. Along with that I also need to use the Email as the username for this project. what is a good and scalable approach? any resource or tutorial links will be appreciated. and how can I utilize django-allauth in this scenario? and here's how I was thinking to implement this: class BaseUser(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) is_personal_above_18 = models.BooleanField(default=False) is_personal_below_18 = models.BooleanField(default=False) is_parent = models.BooleanField(default=False) USERNAME_FIELD = 'email' def __str__(self): return self.email + '/s account' class PersonalAccountAbove18(BaseUser): user = models.OneToOneField(BaseUser, on_delete=models.CASCADE, primary_key=True) customer_id = models.BigIntegerField(default=generate_cid()) class PersonalAccountBelow18(BaseUser): user = models.OneToOneField(BaseUser, on_delete=models.CASCADE, primary_key=True) customer_id = models.BigIntegerField(blank=False) class ParentAccount(BaseUser): user = models.OneToOneField(BaseUser, on_delete=models.CASCADE, primary_key=True) customer_id = models.BigIntegerField(default=generate_cid()) The reason to use customer_id in each model is because later we need to connect different accounts, for example if someone wants to create an as … -
How to deploy static files in Django before hosting it anywhere?
I have a Django application which needs to be deployed. Currently, I am not using Heroku or a Linux server to deploy it. However, I am trying to follow along with the Django checklist and ensure whether if it's ready to be deployed. I had done the following in my settings.py module: Set DEBUG = False Allowed_Hosts = ['*'] STATIC_ROOT = os.path.join(BASE_DIR,"staticfiles") This is my settings.py module: """ DJANGO PROJECT """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'SECRET KEY STORED IN ENVIRON VARIABLE' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'main.apps.MainConfig', #placing the Django app here. 'crispy_forms', 'rest_framework', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ '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', ] ROOT_URLCONF = 'main.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'main.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { … -
implementing notification on a django rest api
While building my API, I didn't think about the logic behind notifications. Please, How do I solve a problem like this on a potentially big project? let us assume I have the code below: model.py class Showcase(models.Model): title = models.CharField(max_length=50) description = models.TextField(null=True) skill_type = models.ForeignKey(Skill, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, related_name="Showcases") content = models.TextField(null=True) created_on = models.DateTimeField(auto_now=True) updated_on = models.DateTimeField(auto_now_add=True) voters = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="upvotes") slug = models.SlugField(max_length=255, unique=True) serializer.py class ShowcaseSerializer(serializers.ModelSerializer): user = serializers.StringRelatedField(read_only=True) created_on = serializers.SerializerMethodField(read_only=True) likes_count = serializers.SerializerMethodField(read_only=True) user_has_voted = serializers.SerializerMethodField(read_only=True) slug = serializers.SlugField(read_only=True) comment_count = serializers.SerializerMethodField(read_only=True) class Meta: model = Showcase exclude = ['voters', 'updated_on'] def get_created_on(self, instance): return instance.created_on.strftime("%d %B %Y") def get_likes_count(self, instance): return instance.voters.count() def get_user_has_voted(self, instance): request = self.context.get("request") return instance.voters.filter(pk=request.user.pk).exists() def get_comment_count(self, instance): return instance.comments.count() view.py # SHOWCASE APIView class showcaseCreateViewSet(generics.ListCreateAPIView): ''' Create showcases view. user must be logged in to do this ''' queryset = Showcase.objects.all() serializer_class = ShowcaseSerializer permission_classes = [IsAuthenticatedOrReadOnly] def perform_create(self, serializer): serializer.save(user=self.request.user) class ShowcaseLikeAPIView(APIView): ''' Can like(post) and unlike(delete) the showcases, must be authenticated to do this ''' serializer_class = ShowcaseDetaiedSerializer permission_classes = [IsAuthenticated] def delete(self, request, slug): showcase = get_object_or_404(Showcase, slug=slug) user = self.request.user showcase.voters.remove(user) showcase.save() serializer_context = {"request": request} serializer = self.serializer_class(showcase, context=serializer_context) return … -
In Django rest framework: GDAL_ERROR 1: b'PROJ: proj_as_wkt: Cannot find proj.db '
I am using the versions for my project: Django==2.2.7 djangorestframework==3.10.3 mysqlclient==1.4.5 In my database I work with geometric types, and for this I have configured the library: GDAL-3.0.2-cp38-cp38-win32 To run this library, I have to include these variables in the django properties file: GEOS_LIBRARY_PATH GDAL_LIBRARY_PATH Now on my models, I do the following import: from django.contrib.gis.db import models For types like: coordinates = models.GeometryField (db_column = 'Coordinates', blank = True, null = True) It seems that the queries work correctly, but when creating a new element, I get the following error: GDAL_ERROR 1: b'PROJ: proj_as_wkt: Cannot find proj.db ' But after this error, the object is persisted correctly in the database. I would like to know how to solve this error. I have not found information on the network, I have only tried to declare a new variable in the DJANGO properties file: PROJ_LIB = 'APP / backend / env / Lib / site-packages / osgeo / data / proj / proj.db' But the error still appears, and you may have problems in the production environment in an OpenSuse image Why can't you find proj.db? How do I solve it? -
How to use query value from [[def get_queryset(self)]] and use in all classes
search.html file <div class="content-section"> <h1 class="mb-3">{{ user.username }}</h1> <form method="GET" action="{% url 'doctor:search' %}"> <input name ="q" value="{{request.GET.q}}" placeholder="search.."> <button class="btn btn-success" type="submit"> Search </button> </form> </div> VIEWS.py How can i use [[query = self.request.GET.get('q')_]] once and use it's result in other class? Currently i'm using search.html repeatedly to get query value for all other classes. Where value of query is same for all the classes. class SearchResultsView(ListView): model = User template_name = 'all_users/doctor/search.html' def get_queryset(self): query = self.request.GET.get('q') object_list = User.objects.filter(Q(username__icontains=query)) return object_list class PostCreateView(LoginRequiredMixin, CreateView): template_name = 'all_users/doctor/post_form.html' model = Post fields = ['title', 'content', 'comment'] def form_valid(self, form): query = self.request.GET.get('q') form.instance.author = self.request.user form.instance.patient = User.objects.get(username=query) return super().form_valid(form) -
Best way to change relation of django group and user model?
The default django User and Group model has ManyToMany relationship but I want to change it OneToOne Relation.Is it possible ?What might be the right way to do this? models.py class Group(models.Model): name = models.CharField(max_length=255) permissions = models.ManyToManyField(Permission) user = models.OneToOneField(User,on_delete=models.CASCADE) -
Can't use Javascript in Django
I tried to use java script in django, by following all the instructions and making the necessary changes in the settings.py file as well as using {% load static %} in my .html file. The CSS loads perfectly, but the .js file in the static/js folder does not. {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="{% static 'css/calcu.css' %}"> </head> <form id="calci_form" method="get" action="operation"> <select name="vehicle" id="veh" onChange="hideShow(this.value)"> <option id="ve1" value="none" name="Select" selected="selected"></option> <option id="ve2" value="2">17 </option> <option id="ve3" value="3">18 </option> <option id="ve4" value="4">19 </option> <option id="ve5" value="5">20</option> <option id="ve6" value="6"> 21 </option> </select> <select name="power" id="pwr" onchange="showHide()"> <option id="pw1" value="none" name="Select" selected="selected"></option> <option id="pw2" value="A">A</option> <option id="pw3" value="B">B </option> <option id="pw4" value="C"> C</option> <option id="pw5" value="D">D</option> <option id="pw6" value="E"> E</option> </select> <label class="l1">X</label><input type="text" name="num1" class="tb1" value="{{fvalue}}"> <label class="l2">Y</label><input type="text" name="num2" class="tb2" value="{{svalue}}"> <label class="l3">Z</label><input type="text" id="txt" class="tb3" name="user_input" value={{result}}> <input type="submit" name="sym" class="btn1" value="Calculate"> <!-- <input type="submit" name="mul" class="btn2" value="Calculate"> --> </form> </html> <script src="{% static 'js/script.js' %}"> </script> This is my html file. my js file looks like this function showHide(){ alert(YOO) var x = document.getElementById("veh").options.length var v = document.getElementById("veh") var val = document.getElementById("pwr").value if(v.value == "none"){ return 0 } for(i = 0; … -
Hello, i need a help , i have got error when i install mysqlclient to ubuntu 18.04, my steps of install in down
My Steps 1)python3 -m venv env 2)source env/bin/activate 3)sudo apt-get install python3.7-dev or python3.8 never mind i tried 4)sudo apt-get install libmysqlclient-dev 5)pip install django mysqlclient error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- Command "/home/dastan/projects/crud_add_book/env/bin/python3 -u -c "import setuptools, tokenize;file='/tmp/pip-build-a6zmf3am/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /tmp/pip-eaynvhxp-record/install-record.txt --single-version-externally-managed --compile --install-headers /home/dastan/projects/crud_add_book/env/include/site/python3.6/mysqlclient" failed with error code 1 in /tmp/pip-build-a6zmf3am/mysqlclient/ -
Ping from server (Ubuntu,Nginx,Gunicorn,Django)
I'm developing an app for local use and it needs to communicate with PLC and other devices in local network. Before sending data to PLC I need to know whether it is present in the network, so i tried to use ping. It all worked fine, while developing the app on Windows. Now when the app is on server I'm getting: "[Errno 1] Operation not permitted, /usr/lib/python3.6/socket.py in init, line 144", when trying to use pythonping library from my Django app. Is there some way to change permissions for the app, to make it ping. Or maybe there is some other way to check if some device is present? -
Gunicorn not starting throwing gunicorn.service: Failed with result 'exit-code'. error
I'm trying a deploy simple Django application on DigitalOcean by following this link I follow every work step by step and successfully run that project via Python manage.py runserver were it's not throwing any error but when I try to implement it with gunicorn its throw following error gunicorn.service: Failed with result 'exit-code'. Here is my following configuration sudo nano /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target sudo nano /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=sammy Group=www-data WorkingDirectory=/home/sammy/myprojectdir ExecStart=/home/sammy/myprojectdir/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ myproject.wsgi:application [Install] WantedBy=multi-user.target sudo systemctl status gunicorn.socket ● gunicorn.socket - gunicorn socket Loaded: loaded (/etc/systemd/system/gunicorn.socket; enabled; vendor preset: enabled) Active: active (listening) since Tue 2019-11-26 07:39:39 UTC; 12min ago Listen: /run/gunicorn.sock (Stream) CGroup: /system.slice/gunicorn.socket Nov 26 07:39:39 POS systemd[1]: Listening on gunicorn socket. When I try to start gunicorn it's throwing this error sudo systemctl status gunicorn ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Tue 2019-11-26 07:39:43 UTC; 13min ago Process: 718 ExecStart=/home/pos/env/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock pos.wsgi:application (code=exited, status=1/FAILURE) Main PID: 718 (code=exited, status=1/FAILURE) Nov 26 07:39:43 POS gunicorn[718]: Arbiter(self).run() Nov 26 07:39:43 POS gunicorn[718]: File … -
User creation form in Django
I am taking online Djago class and have no one to ask for help. I would appreciate to get any help and tips. I am learning creating forms (login/singup). So far i did in models.py from django.db import models from django.contrib import auth class User(auth.models.User,auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) In forms.py from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm class UserCreateForm(UserCreationForm): class Meta: fields = ('username','email','password1','password2') model = get_user_model() def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['username'].label = 'Display Name' self.fields['email'].label = 'Email Address' I want to add addtional firelds as surname , however when i add 'surname' in class meta in fields (forms.py) i get error, however the online training says i can easily add additional fields. Could you please tell what i am doing wrong and how i can add this field? -
Log into Chrome Extension without OAuth2
I'm wondering if it's possible to set up secure login authentication in a Chrome extension without OAuth2. I'm considering setting it up as follows: On opening the extension, send a POST to server which returns the CSRF token JavaScript inserts the token into the usual login form (as in Django template) [steps 1 and 2 replace the usual Django template rendering] User provides username and password and submits the form Success/Fail JSON response is returned and handled appropriately CSRF token is stored as a cookie (or in browser storage that Chrome extensions use) to enable automated login until it expires Would be great to hear possible problems/corrections to this approach as well as pointers to relevant resources! -
how to sum data according to date, year and some other category in django
I am new in django and i am stuck in this situation. I am adding student points according to category. Now I am want to show point according to category and month wise.I have attached following image as my expected result. I have tried annotate function but i am not able to solve this problem. Expect Result Models from django.db import models from datetime import datetime # Create your models here. class Teacher(models.Model): full_name=models.CharField(max_length=50) username=models.CharField(max_length=50) password=models.CharField(max_length=50) def __str__(self): return self.full_name class Student(models.Model): classes_name=( ('nur','Nursery'), ('lkg','LKG'), ('ukg','LKG'), ('1','1'), ('2','2'), ('3','3'), ('4','4'), ('5','5'), ('6','6'), ('7','7'), ('8','8'), ('9','9'), ('10','10'), ) full_name=models.CharField(max_length=100) roll_no=models.CharField(max_length=20) class_name=models.CharField(max_length=20,choices=classes_name) def __str__(self): return self.full_name+' '+self.class_name class PointCategory(models.Model): category_name=models.CharField(max_length=100) def __str__(self): return self.category_name class StudentPoint(models.Model): stu_id=models.IntegerField(null=True) teacher_id=models.IntegerField(null=True) point_cat=models.IntegerField(null=True) points=models.IntegerField(null=True) add_date=models.CharField(max_length=50,null=True) assign_date=models.DateTimeField(default=datetime.now) View Code for report def report(request,stu_id): decoded_hand = json.loads(request.session['teacherData']) teach_id=decoded_hand[0]['pk'] month_year=StudentPoint.objects.filter(stu_id=stu_id,teacher_id=teach_id).annotate(month=TruncMonth('assign_date'),year=TruncMonth('assign_date')).values('month','year').annotate(total_points=Sum('points')) all_category=PointCategory.objects.all() return render(request,'teacher/report.html',{ 'month_year':month_year, 'categories':all_category, 'stu_id':stu_id, })