Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to hash password in Django Backend
If a user signs up on the frontend, the password is hashed just fine but when i try to create a password from Django's backend, the password is saved as plain text. admin.py def save(self, commit=True): # Save the provided password in hashed format user = super(RegisterForm, self).save(commit=False) user.set_password(self.cleaned_data["password"]) if commit: user.save() return user forms.py class RegisterForm(forms.ModelForm): email = forms.EmailField() password = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput) class Meta: model = User fields = ('email',) def clean_email(self): email = self.cleaned_data.get('email') qs = User.objects.filter(email=email) if qs.exists(): raise forms.ValidationError("email is taken") return email def clean_password2(self): # Check that the two password entries match password = self.cleaned_data.get("password") password2 = self.cleaned_data.get("password2") if password and password2 and password != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): user = super(RegisterForm, self).save(commit=False) user.set_password(self.cleaned_data['password']) # user.is_applicant = True user.is_active = True if commit: user.save() return user Please for some assistance. -
messages API twitter Challenge-Response Checks
I've seen that twitter changed their endpoints to get and send direct messages, I noticed from a reply from here that it is a workaround to be able to send messages with well-known libraries such as tweepy, but all I need in this case is to list the messages in my inbox. I've noticed that there is an account activity api which I can use to achieve this goal. But, I do not understand how to implement Challenge-Response Checks, can you provide an example? how twitter checks this? it is through a post request to my site? to what specific URI they do this? I tried sending a pipedream url as webhook (to see what kind of request they were doing, but absolutely no request was shown) -
How to use slicing on queryset for django form?
Let's say I have a django Model Player. Player model has a filed name 'points' a integer field. I need to show top 10 players ordered by points in from.ModelChoiceField. The queryset would be Player.objects.all().order_by('-poinst')[:10] But if I use slicing on queryset which would be set into form field, it raises error when submit button is clicked. Cannot filter a query once a slice has been taken. Any way to solve this? -
displaying data in django template using detail view
i'm having a problem displaying data on DetailView Template , basically wanna display all the data of one project areas and tasks my models looks like that ##models class Project(models.Model): name = models.CharField(max_length=100) ... class Area(models.Model): name = models.CharField(max_length=100) project = models.ForeignKey(Project ,on_delete=models.CASCADE, related_name='areas' ) class Task(models.Model): .... area = models.ForeignKey(Area ,on_delete=models.CASCADE, related_name='tasks' ) #view class ProjectDetailView(DetailView): model = Project template_name = 'project-detail.html' i can display project and areas using the reverse relationship but i'm unable to display tasks on every area . -
django ajax form submit to view without refreshing page
To implement a non-refreshing effect, I decide to use $.post() However, I need to send csrf token also, as a result, I cannot send only input contents of my form. Here's my code at .js, but the JSON.stringify($(this)) gives me things I don't want at the views.py back-end. .js $('#my-form').submit(function(e){ e.preventDefault(); url=$(this).attr('action'); data=JSON.stringify($(this)) $.post(url,{'data':data,'csrfmiddlewaretoken':$( "#csrfmiddlewaretoken" ).val()},function(data_returned){ alert('submit done'); }); }); at my views.py print("data:"+json.loads(str(request.POST['data']))) which gives me something like these: {"0":{"0":{},"1":{},"2":{"0":{},"1":{},"2":{}},"3":{},"4":{},"5":{},"6":{},"7":{},"8":{},"9":{},"10":{},"jQuery112402971640175601502":28},"context":{"0":{},"1":{},"2":{"0":{},"1":{},"2":{}},"3":{},"4":{},"5":{},"6":{},"7":{},"8":{},"9":{}," 10":{},"jQuery112402971640175601502":28},"length":1} Any suggestion? Thanks! -
Django Template Tagging inserting a single value from a ListView
So I am undertaking a website project and I am having some issues with one page. I essentially load NBA teams wins and losses onto a page and make my own makeshift standings ladder. The data loaded from my model is as follows: MODEL.PY from django.db import models from django.utils import timezone # Create your models here. class Team(models.Model): team_name = models.CharField(max_length=500, unique=True, primary_key=True) wins = models.PositiveIntegerField() losses = models.PositiveIntegerField() created_date = models.DateTimeField(default=timezone.now) I use the ListView in my views.py file as follows: VIEWS.PY class LadderListView(LoginRequiredMixin, ListView): #this defaults to looking for the models name html so in this case team_list.html # so i changed it to template_name variable template_name = 'merchbet/ladder_list.html' model = models.Team and render the urls.py file as follows: path('ladder/', views.LadderListView.as_view(), name='ladder_list'), all of this successfully works. When I get to my html code I am able to the teams, and their win/loss records to print to the website with template tagging, but I am looking to inject one line at the bottom which shows the "Last Updated: {{ team.created_date }}. This is not working and I am not getting an errors, the "{{ team.created_date }}" just shows nothing on the url page. I have looked through … -
How do I remove a Posgresql image from a Docker container and install a new one
I'm new to docker and loveing it for the most part. The one thing I DON'T love is replacing a DB. I have a Vue/Django app that I borked the database on. I need to re run the migrations. It's a special case where I need to rebuild the DB for a user account. Regardless, I can't seem to do it. I've followed the instructions here (https://github.com/Radu-Raicea/Dockerized-Flask/wiki/%5BDocker%5D-Remove-all-Docker-volumes-to-delete-the-database) and it looks like it works in that it lists what is removed. But then it doesn't seem to actually remove it. What I want to do is just switch to a new database in the container for Postgresql. Any suggestions? -
How to send extra parameters to the serializer, not included in the model?
I need to send parameters to the serializer that do not exist in the model, so the serializer delete this data I also have a nested serializer with a custom ".create()" function request data = {'data': [{'usuario': 269, 'coworkers': [328, 209], 'inicio': '2019-01-24T23:30:43.926Z', 'estado': 'progress', 'operacion': {'orden': 24068, 'proceso': 'ALEZADO FINAL-TORNO CNC T7 1'}}, {'usuario': 269, 'coworkers': [208, 212], 'inicio': '2019-01-24T23:30:43.926Z', 'estado': 'progress', 'operacion': {'orden': 24067, 'proceso': 'ALEZADO FINAL-TORNO CNC T7 1'}}]} Model: class TiempoOperacion(models.Model): inicio = models.DateTimeField(blank=True, null=True) fin = models.DateTimeField(blank=True, null=True) operacion = models.ForeignKey(Operacion, related_name='tiempos', on_delete=models.CASCADE) cantidad = models.IntegerField(default=0) usuario = models.CharField(max_length=40) motivo_pausa = models.CharField(max_length=140, default=None, null=True) estado = models.CharField( max_length=15, choices=TASKS_STATUS_CHOICES, default=UNACTION, ) Viewset: def create(self, request): datos = request.data.get('listorders') if 'listorders' in request.data else request.data tiemposerializer = TiempoOperacionSerializer(data=datos, many=True, fields=('coworkers', 'operacion')) if tiemposerializer.is_valid(): tiemposerializer.save() return Response(tiemposerializer.data) else: return Response(tiemposerializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializer: def create(self, validate_data): operacion_data = validate_data.pop('operacion') print (f"\n\n validate_data : {validate_data} \n\n") if not operacion_data: raise ValidationError({ 'operacion': 'This field object is required.' }) coworkers = validate_data.get('coworkers') query_operaciones = Operacion.objects.filter(**operacion_data)[:1] if query_operaciones.count() > 0: operacion = query_operaciones[0] else: operacion = Operacion.objects.create(**operacion_data) tiempo_obj = validate_data tiempo = TiempoOperacion.objects.create(operacion=operacion, **tiempo_obj) if coworkers: tiempos_list = [] for coworker in coworkers: tiempo_obj.update({'usuario': coworker}) tiempos_list.append(TiempoOperacion(operacion=operacion, **tiempo_obj)) tiempos = TiempoOperacion.objects.bulk_create(tiempos_list) return … -
ISO 8601 string instead of datetime
I have faced this problem in other projects, but right now we're working in Django / Python with Vue.js and PostgreSQL. Nearly every 'date' field in our model is truly a date, not a datetime. The business users don't care about a time-part, in fact storing any such value is misleading. A good example is the effective date on a tax rate. From the user point of view, it takes effect at midnight on the specified date. If we store this as a Django DateTimeField or DateField, it requires a time-part. It could be 0000h, but the value has no meaning to the business, because they will never need to see or compare anything with the time-part. The Django functionality is great if we want to store a real datetime, put it into the database as UTC, and then display it to users in their local time through the automatic time zone conversion. But we don't. If the effective date is March 1, 2019, it should display as such regardless of the user's timezone. If the date is stored as a datetime (2019, 3, 1, 0, 0, 0) and entered by someone in Vancouver, it will appear as the next … -
How to store results from many TestCases (to one file) in django (unittest)?
I have several test cases which all have a similar tearDown: def tearDown(self): execution_time = time.time() - self.startTime result_list = [self._testMethodName] result = [str(x) for x in sys.exc_info()] if result[0] == 'None': result_list.append('PASS') elif 'Assertion' in result[0]: result_list.append('FAIL') else: result_list.append('ERROR') result_list.append(result) result_list.append(str(execution_time)) TEST_RESULTS.append(result_list) I'm using the tearDown function to store results from each test (in the test case) to a global TEST_RESULTS object (so each TestCase file has a TEST_RESULTS global defined). Then in the tearDownClass function im doing this to store results to csv: @classmethod def tearDownClass(cls): with open ('tests/results/test_case_1_output.csv', 'wr') as resultFile: wr = csv.writer(resultFile) wr.writerows(TEST_RESULTS) To me this is a terrible implementation. Globals defined everywhere and tearDown/tearDownClass implemented over and over again in each test case rather than defined once. Furthermore, I would like to create a test result file which collects results from all test cases. My hunch is this requires defining the file handle at the runner level (or somewhere before the TestCases are being called). This would allow me to reinitialize the csv file at a higher level (rather than arbitrarily in one TestCase). Does anyone have a suggestion on how this can be accomplished? Did not see a way to do this from … -
How to automatically connect to Cloud SQL via the proxy?
I have mySQL database set in settings.py like this: if os.getenv('GAE_APPLICATION', None): # Running on production App Engine, so connect to Google Cloud SQL using # the unix socket at /cloudsql/<your-cloudsql-connection string> DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '/cloudsql/myApp:europe-west1:myApp-instance', 'NAME': 'myApp', 'USER': 'myApp', 'PASSWORD': 'myApp', }} else: # Running locally so connect to either a local MySQL instance or connect to # Cloud SQL via the proxy. To start the proxy via command line: # # $ ./cloud_sql_proxy -instances="myApp:europe-west1:myApp-instance"=tcp:3306 # # See https://cloud.google.com/sql/docs/mysql-connect-proxy DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': '127.0.0.1', 'PORT': '3306', 'NAME': 'myApp', 'USER': 'myApp', 'PASSWORD': 'myApp', }} When I want to run myApp locally I must run first on terminal this command: ./cloud_sql_proxy -instances="myApp:europe-west1:myApp-instance"=tcp:3306 and it's very annoying... there is a way to integrate it inside my code? For example I would put something in my setting that automatically run the command, immediately after the 'else:' But I don't know what I have to write... any idea? Is it possible? -
Tunneling/SSH On digital ocean to improve development process
I don't really know how to phrase my question. I am student developer and working with a non-profit group on my campus. Objective: try to make the development process smoother. Technologies Used: Django, Docker, Front-end techs, other techs Description: I will try to make it as abstract as possible. The software we have has web interface and a mobile app. It has the ability to communicate to the mobile app and prompt: "accept or decline". And it works fine when I host it up on Digital Ocean. Problem: While developing, you can't really test out the communication cuz i am developing on localhost (question 1: how to achieve this on a test server? and for multiple people developing it?). Second is I have to start docker every time I want to develop + push to github + go into docker bash... (question 2: is there a way to automate this? sorta like how you would be able to do react development in real-time?) Sorry if this is a noob question. But any pointers? Anything I can google would be of help. Thanks in advance. -
How to fix "more than one foreign key" Django
I am new to Django (using version: 2.1.5)(Python 3.6) and trying to mess around with some models. I am building a chess database. This relies on 3 models, the players, the game and the moves comprising the game. For each game there is a white player and a black player, both of the class player. This raises an error: : (admin.E202) 'chessengine.Game' has more than one ForeignKey to 'chessengine.Player'. I tried using reference names which removed an earlier related error but will not deal with the one above. //models.py class Player(models.Model): name = models.CharField(max_length=200) birth_date = models.DateField('birthday') def game_count(self): return Player.objects.filter(Games__white_player=self.name).count() + Player.objects.filter(Games__black_player=self.name).count() class Game(models.Model): number = models.IntegerField() date = models.DateField('date played') moves = models.IntegerField() white_player = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='white_player') black_player = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='black_player') result = models.CharField(max_length=8) //admin.py class GameInline(admin.TabularInline): inlines = [MoveInline] model = Game class PlayerAdmin(admin.ModelAdmin): fieldsets = [ ('Player Information', {'fields': ['name', 'birth_date']}), ('Game Information', {'fields': ['date', 'player_white', 'player_black', 'result'], 'classes': ['collapse']}), ] inlines = [GameInline] list_display = ('name', 'birth_date', 'game_count') list_filter = ['name'] -
OneToOneField attribute is linking ID instead of CharField
I have these two models linked by OneToOneField "Father" class: from django.db import models class EmpresaManager(models.Manager): def create_empresa(self): empresa = self.create() return empresa class Empresa(models.Model): codigo = models.CharField(max_length=3, null=False, default='000') nombre = models.CharField(max_length=100, null=False, default='Sin nombre') email = models.EmailField(null=False, default='email@empresa.com') direccion = models.CharField(max_length=100, null=False, default='Sin direccion') localidad = models.CharField(max_length=100, null=False, default='Sin localidad') codDgi = models.SmallIntegerField(null=True) docDgi = models.CharField(max_length=13, null=True) sIva = models.CharField(max_length=1, null=True, default='1') mesCierre = models.IntegerField(null=True, default=0) fecIni = models.DateField(null=True) ruca = models.IntegerField(null=True) novedad = models.CharField(max_length=50, null=True, default='') fecNovedad = models.DateTimeField(null=True) ultVersion = models.CharField(max_length=20, null=True, default='') logo = models.ImageField(null=True) habilitado = models.CharField(max_length=1, null=True, default='S') codEmpresa = models.CharField(max_length=3, null=True) codComp = models.CharField(max_length=3, null=True, default='') def __str__(self): return "%s" % self.nombre objects = EmpresaManager() And the other class: from django.db import models from Empresa.models import Empresa class UsuarioManager(models.Manager): def create_usuario(self): usuario = self.create() return usuario class Usuario(models.Model): empresa = models.OneToOneField( Empresa, on_delete=models.CASCADE, primary_key=False, ) codigo = models.CharField(max_length=10, null=False, default='Sin cod') nombre = models.CharField(max_length=50, null=True) puesto = models.CharField(max_length=50, null=True) password = models.CharField(max_length=100, null=True) rol = models.CharField(max_length=15, null=True, default='') habilitado = models.CharField(max_length=1, null=True, default='S') def __str__(self): return self.nombre objects = UsuarioManager() The problem: I'm trying Usuario.empresa to inherit the value from Empresa.nombre (which is a CharField, for example 'McDonalds'), but it is inheriting … -
NoModuleName 'channels', but I have installed it. Django
Django version 2.1.5 Channels version 2.1.6 Ubuntu 18.0.4 When I run project in pyCharm, it says: Unhandled exception in thread started by <function check_errors. <locals>.wrapper at 0x7f18ecd8eb70> Traceback (most recent call last): File "/home/mercer/venv_linux/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/mercer/venv_linux/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/mercer/venv_linux/lib/python3.6/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/home/mercer/venv_linux/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/home/mercer/venv_linux/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/mercer/venv_linux/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/mercer/venv_linux/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/home/mercer/venv_linux/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked ModuleNotFoundError: No module named 'channels' The module installed (venv) mercer@mercerPC:~/Documents/comet$ pip list | grep channels channels 2.1.6 Here is the installed_apps: INSTALLED_APPS = [ 'channels', 'chat', 'accounts', 'events', ... ] Also I created the routing file and added ASGI_APPLICATION = 'mysite.routing.application' in settings.py -
How to access pdfs with special characters my Django app?
I have a django app, hosted using nginx and gunicorn. One of the features I have is to generate a PDF on the fly, using xhtml2pdf. I can access the pdfs in a url like /pdf/(id)/, but the issue I have is with the filename. The piece of code that is causing the problem is: # generate the pdf. This function has been tested and is not causing the problem pdf = render_to_pdf(template, data) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "cotización_%s.pdf" % (doc_name) content = "inline; filename='%s'" % (filename) response['Content-Disposition'] = content return response From the error log I realized that the issue is the accent on the filename (cotización) File "~/lib/python3.6/site-packages/gunicorn/workers/sync.py", line 182, in handle_request resp.write(item) File "~/lib/python3.6/site-packages/gunicorn/http/wsgi.py", line 333, in write self.send_headers() File "~/lib/python3.6/site-packages/gunicorn/http/wsgi.py", line 329, in send_headers util.write(self.sock, util.to_bytestring(header_str, "ascii")) File "~/lib/python3.6/site-packages/gunicorn/util.py", line 507, in to_bytestring return value.encode(encoding) UnicodeEncodeError: 'ascii' codec can't encode character '\xf3' in position 176: ordinal not in range(128) On my localhost, I can access the pdfs perfectly. But on my server I get a 502 error. If I remove the 'ó', the problem goes away. So my question is, how can I serve pdfs including accents on the filename? NOTE: The … -
User page permissions updating only when server restarts with Django-CMS
Basically, I am having an issue where, I have a page using rest framework that edits user (I am using the default django user app) permissions by changing the groups or changes other minor infos like name and password. However, when I edit a group of a user, and only when I edit them, for some reason, the user permissions only changes when I restart the django server, allowing the user to view django cms pags that he should not see. After the server restarts all permissions works just fine. I already tried to force the permissions to be refreshed like this: for app in settings.INSTALLED_APPS: create_permissions(apps.get_app_config(app.split(".")[-1])) but it didn't work. I actually have no clue whatsoever what the cause of the issue is, so much that I am not sure what code I could put here, so in doubt I will post the rest user serializer: # -*- coding: utf-8 -*- from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): def __init__(self, *args, **kwargs): super(UserSerializer, self).__init__(*args, **kwargs) self.fields['username'].label = u"Usuário" self.fields['password'].label = u"Senha" self.fields['first_name'].label = u"Nome Completo" group_name = serializers.SerializerMethodField() def get_group_name(self, obj): return ", ".join(list(obj.groups.values_list('name',flat=True))) def create(self, validated_data): user = super(UserSerializer, self).create(validated_data) user.set_password(validated_data['password']) user.save() return user def … -
How to convert a queryset in django to json
I´ve seen his question has been answered multiple times for django < 2.xx, but for the current version I am using (2.1) I´been unable to convert my querysets to a json format. I´ve tried serializer using the django rest framework, but so far the only use I was able to implement is to serialize a model, so when my querysets has results from different models that does not work. This has beeing really annoying, In frameworks as Laravel this is supposed to be pretty simple, I would appreciate any help. -
Replacing Django Template Variable with variable created via Javascript
I am very new to Django and Javascript (< 3 weeks!) and have a question that might be stupid so any help would be greatly appreciated. In my current code, I have a table rendered in HTML with the following code: <table border="1" class="dataframe"> <thead> <tr> <th>{{ results.0.columns.1 }}</th> <th>{{ results.0.columns.1 }} </th> <th>{{ results.0.columns.2 }} </th> <th>{{ results.0.columns.6 }} </th> </tr> </thead> <tbody> {% for row in results.0.values %} <tr> <td> {{row.0}} </td> <td> {{row.1}} </td> <td><img src="{{row.2}}" alt="img" height="150"></td> <td> {{row.6}} </td> </tr> {% endfor %} </tbody> </table> As you can see there are numerous areas where I am referencing a django template variable with the format of {{someDjangoVariable}}. However, I'd like to replace these variables with variables that are created in Javascript. I am using Javascript to take some user input which ultimately changes the view of the table. My Javascript is set up as following: <script> function myFunction() { var index = someNumber var string = `results.${index}.columns.0`; document.getElementById('demo').innerHTML = string; } </script> The string variable created in Javascript results in something that completely mimicks the Django template variable. For example, string = results.0.columns.1. However, I'm unsure as to how to pass this string variable into the … -
How to create a particular profile based on user attribute in Django using signals
I have users that are either 'Company' or 'Applicant', each having different attributes. I want to create either a Company Profile or Applicant Profile on sign-up based on the user attribute. Below is the code I'm using in signals.py and it does not work. @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: if sender != User.is_company: Applicant.objects.create(user=instance) else: Company.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): if instance.is_applicant: instance.applicant.save() else: instance.company.save() -
How to doctor my CPU utilization issue, I am using ubuntu ec2 instance with nginx, uwsgi and django
Hello I am running an EC2 ubuntu instance (3 instances to be exact with a loadbalancer) this morning I realized that all 3 of my instances are running at 100% cpu utilization and that worries me, they're usually running below 40% unless I have scheduled task happening all at once. They are all running nginx, uwsgi, celery, and django. This has never happened to me before so I am not sure how I should approach it. What I have done so far: -Restart instances -Stop and start instances -Unload and reload balancers -Restart supervisorctl Usually these actions would regulate my cpu utilization but this time they just keep shooting back up. Any hints where I should start? -
Like button on the list, press effect is always on first one
My problem is that: I can't display buttons that have already been selected ("vote up" or "vote down") - variables in the view code. When I press the button on the last comment, e.g. "vote up". - the 'vote up' button on the first comment is highlighted - which is not sorted out. The problem may be that this is a list and additionally in a view, where the object is already a Post model. My code is below. Here is models of Post and Comment class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = RichTextUploadingField() votes_up = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='up_votes') votes_down = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='down_votes') def __str__(self): return self.text def total_vote_up(self): return self.votes_up.count() def total_vote_down(self): return self.votes_down.count() class Comment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') text = RichTextUploadingField() Here is detail view where I would like to check if comment is liked or not. I pass to context variables. class PostDetail(generic.DetailView, FormMixin): template_name = 'post_detail.html' context_object_name = 'post' model = Post form_class = CommentForm def get_context_data(self, **kwargs): is_voted_up = False is_voted_down = False comments = self.get_object().answers.all() for comment in comments: if answer.votes_up.filter(id=self.request.user.id).exists(): print(answer) is_voted_up = True print(is_voted_up) if answer.votes_down.filter(id=self.request.user.id).exists(): is_voted_down = True context = … -
multiple user authentication
i want to create multiple user authentication there are many groups and each group having multiple user but there is no any signup page admin will add all user, user just login and get its dashboard or homepage. example - groups like - 1. admin 2. saller 3. customer 4. xyz only admin add all user's, if customer group user login than show it's homepage. i have many confusions ... please help me for this task. just give me reference for that, how to do this -
How to set AWS credentials for user www-data for Django app using NGINX
I have a Django app running on a Linux server under NGINX. The "user" for the Django app is www-data. In this app, I try to connect to AWS IOT, and to do that I believe that the AWS boto3 package tries to find the AWS credentials here: ~/.aws/credentials. The problem is that for the user "www-data" there is no such path! When I login to the server (using my real username), and I try to run a script that connects to AWS, it connects just fine. Let's say my username is "joe". There is indeed a file /home/joe/.aws/credentials that contains the correct credentials. This is why the script works fine when I run as user "joe". But when the Django app is running, it doesn't work because there is no login user www-data, ie there is no file /home/www-data/.aws/credentials. I understand that AWS boto3 let's us set an environment variable to specify a non-standard path to the credentials file. This env variable is AWS_CONFIG_FILE. However, I don't know how to set an environment variable in Django for user www-data so that boto3 can now use that environment variable to specify the AWS credentials path. Anyone know how to do … -
How To Update Hidden Field In Django Form
I am trying to figure out the best approach to modifying a hidden django form field. Or if it's even possible. I had my HTML setup to accomplish this very task and it was working perfectly. However, in order to prevent multiple submissions I had to change my HTML and now I am unable to figure out how to pass a value via an HTML button depending on what the user clicks on. Previously, I had two buttons defined as outline below: <button type="submit" class="button1" name="status" value="Saved"><h3 class="txtalgn4">Save</h3></button> <button type="submit" class="button2" name="status" value="Submitted"><h3 class="txtalgn4">Submit</h3></button> As stated above, this worked perfectly for the purpose of passing a value to an attribute for my model. The value of status was saved as expected depending on which button the user clicked on. Now I have updated the buttons to type="button" in response to this issue that I opened up today...How To Prevent Double Submit With Form Validation I tried using the following code: <button type="button" class="button1" name="status" value="Saved"><h3 class="txtalgn4">Save</h3></button> <button type="button" class="button2" name="status" value="Submitted"><h3 class="txtalgn4">Submit</h3></button> And then I also changed the status field to {{ status.as_hidden }} in my HTML to get the value. This only works if I hardcode the status value …