Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Having problems installing django in a new virtual env
(DJANGO~1) C:\Users\NIKITA PRO\Desktop\my_django_stuff\DJANGOBASICS>pip install django Requirement already satisfied: django in c:\users\nikita pro\desktop\my_django_stuff\djangobasics\lib\site-packages (3.0.4) Requirement already satisfied: sqlparse>=0.2.2 in c:\users\nikita pro\desktop\my_django_stuff\djangobasics\lib\site-packages (from dj ango) (0.3.1) Requirement already satisfied: pytz in c:\users\nikita pro\desktop\my_django_stuff\djangobasics\lib\site-packages (from django) (2019 .3) Requirement already satisfied: asgiref~=3.2 in c:\users\nikita pro\desktop\my_django_stuff\djangobasics\lib\site-packages (from djang o) (3.2.3) -
Using %(class)s in a 'default' field
I know when you have a foreign key/many to many relation, it is advisable to use related_name='%(app_label)s_%(class)s_related', or something similar. I have a scenario where I want to set the field value to a value based on the current class. Essentially what I want to do is something like this: class Parent(models.Model): child_name = models.TextField(default='%(class)s') class ChildA(Parent): . . . class ChildB(Parent): . . . Is this possible at all? -
Modifying data models in order to add sizing and quantity to the product
I wanna be able to choose a size of frame for every bike and every size would have to have its own quantity. What would be the best model to get this to work? Would that be hard to accomplish? I assume that the simplest way would be to put the size in the title and then the quantity of that item? Here's what I currently got in my Models: class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) label = models.ManyToManyField(Label, blank=True) slug = models.SlugField(unique=True) description = models.TextField() class Bike(models.Model): item = models.OneToOneField(Item, on_delete=models.CASCADE) category = models.ManyToManyField(Category, blank=True) image = models.ImageField(upload_to='bikes') brand = models.ManyToManyField(Brand) What would have to be done, to get the sizing and quantity to work? -
Django modelformset_factory not saving POST data to database
I am trying to use a modelformset_factory formset that will show multiple rows from the same model, and allow adding and/or updating and/or deleting rows. For a long time I was getting ['ManagementForm data is missing or has been tampered with'] error. Then I read some more of the documentation where I'm being told to add "data" at the end of the formset. https://docs.djangoproject.com/en/3.0/topics/forms/formsets/ I'll trust the documentation more than every youtube tutorial I watch...however...not one single tutorial I've found does this lol. Regardless. I've added that to my code in my view, and now I get no error...but I get no posting of data either. Been googling like a mad man to no avail. I'm fairly new to Django and any help would be greatly appreciated. Note, my model has drop down "choices". Not sure if that makes a difference. Everything displays correctly in my template, and my submit button redirects correctly...but no data is written to the database at all. MODEL Discipline_Choices = ( ('Unarmed-Contemporary Violence','Unarmed-Contemporary Violence'), ('Rapier and Dagger','Rapier and Dagger'), ('Broadsword','Broadsword'), ('Quarterstaff','Quarterstaff'), ('Single Rapier','Single Rapier'), ('Small Sword','Small Sword'), ('Knife','Knife'), ) Rank_Choices = ( ('1.0 Certificate of Participation','1.0 Certificate of Participation'), ('1.1 Introductory Combatant','1.1 Introductory Combatant'), ('1.2 … -
Read excel from ui and pass it as dataframe to python
I currently having a choose file option in which a user can upload an excel file. How do i read this excel and pass it as data frame to python via Ajax/JQUERY POST call? HTML <input type="file" class="form-control" id="excel_gsheet" name="excel_gsheet"> Please suggest a workaround for this. I am building this in my Django web app. -
Does values_list prevent you to access to field names?
I'm trying to use {{ field.name }} in my template but I can't get access to it. I'm using values_list. views.py: objects = Ingredient.objects.select_related('stock').filter(account=account, exists=True).values_list('id', 'name', 'stock__stock', 'comments')[:50] template.html: {% for object in objects %} {% for field in object %} {% if field.name != 'id' %} <td>{{ field}}</td> {% endif %} {% endfor %} {% endfor %} As you can assume I'm showing every field in values_list except by id which I'm using only for JavScript functions but I don't want to show it in my for loop iteration. But I can't get access to {{ field.name }}, I tried by printing it in the html but I get nothing. -
How can I configure my Django/Python docker instance so that updates are reflected immediately?
I'm have Docker 2.0/Python 3.7 application, which I load into a docker container, along with its accompanying web and database images (below is the docker-compose.yml file) ... version: '3' services: mysql: restart: always image: mysql:5.7 environment: MYSQL_DATABASE: 'maps_data' # So you don't have to use root, but you can if you like MYSQL_USER: 'chicommons' # You can use whatever password you like MYSQL_PASSWORD: 'password' # Password for root access MYSQL_ROOT_PASSWORD: 'password' ports: - "3406:3406" volumes: - my-db:/var/lib/mysql web: restart: always build: ./web ports: # to access the container from outside - "8000:8000" env_file: .env environment: DEBUG: 'true' command: /usr/local/bin/gunicorn maps.wsgi:application -w 2 -b :8000 depends_on: - mysql apache: restart: always build: ./apache/ ports: - "9090:80" links: - web:web volumes: my-db: Here is the web/Dockerfile that controls the Django portion of the stack ... FROM python:3.7-slim RUN apt-get update && apt-get install RUN apt-get install -y libmariadb-dev-compat libmariadb-dev RUN apt-get update \ && apt-get install -y --no-install-recommends gcc \ && rm -rf /var/lib/apt/lists/* RUN python -m pip install --upgrade pip RUN mkdir -p /app/ WORKDIR /app/ COPY requirements.txt requirements.txt RUN python -m pip install -r requirements.txt COPY entrypoint.sh /app/ COPY . /app/ RUN ["chmod", "+x", "/app/entrypoint.sh"] ENTRYPOINT ["/app/entrypoint.sh"] My question is, … -
Use Saved ModelForm as Foreign Key in New Model Instance Django
I'm trying to pass the primary key of a saved ModelForm instance as the foreign key to a new inquiry instance on Django. I'm not quite sure why its not working. I tried breaking up getting the foreign key id and it returns a number but its still not working. Any insight about what I'm doing incorrectly would be greatly appreciated. Views.py def customer_inquiry(request): submitted = False if request.method == 'POST': form = CustomerForm(request.POST) if form.is_valid(): customer = form.save() identity = customer.pk obj = Customer.objects.get(cust_id=identity) inquiry = Inquiry.objects.create( cust_id = Customer.objects.get(cust_id = obj.pk), inquiry_date = datetime.now) return HttpResponseRedirect('/customer_inquiry/?submitted=True') else: form = CustomerForm() if 'submitted' in request.GET: submitted = True return render(request, 'customer_inquiry.html', {'form': form, 'submitted': submitted}) Model.py inquiry_id = models.AutoField(primary_key=True) cust_id = models.ForeignKey(Customer, on_delete=models.CASCADE) inquiry_date = models.DateField() class Inquiry(models.Model): inquiry_id = models.AutoField(primary_key=True) cust_id = models.ForeignKey(Customer, on_delete=models.CASCADE) inquiry_date = models.DateField() Error Request Method: POST Request URL: http://127.0.0.1:8000/customer_inquiry/ Django Version: 3.0.3 Python Version: 3.8.1 Installed Applications: ['database', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework'] Installed 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'] Traceback (most recent call last): File "/Users/alessandrolou/.local/share/virtualenvs/CascadeBicycleClubCapstone-xHaG2iwn/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/alessandrolou/.local/share/virtualenvs/CascadeBicycleClubCapstone-xHaG2iwn/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/alessandrolou/.local/share/virtualenvs/CascadeBicycleClubCapstone-xHaG2iwn/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in … -
when trying to write your project with registration. I can’t find the link name I tried everythingю Django urls
I have 2 chat and account applications but I don’t understand why urls are not found account.urls app_name = 'account' urlpatterns = [ path('login/', Login_proverka, name='Login'), path('<int:user_id>/profile/', Profil, name='Profil'), path('exit/', Exit, name='Exit'), path('register/', Register, name='Register'), path('<int:user_id>/chat/', include('chat.urls')) ] chat.urls app_name = 'chat' urlpatterns = [ path('', ListCHat, name='ListCHat'), path('<int:chat_id>', Chat, name='Chat'), path('<int:chat_id>/send_message', CreateMessage, name='CreateMessage') ] chat.html <form action="{% url 'chat:CreateMessage' %}" method="post"> {% csrf_token %} <div class="row"> <div class="col"> <textarea class="form-control" id="exampleFormControlTextarea1" rows="3" style="resize: none; margin: 3px; height: 114%; }"></textarea> </div> <div class="col-1"> <button type="button" class="btn btn-primary btn-lg btn-block" style="margin-left: -39%;width: 127%; margin-top: 8%;"><i class="fa fa-hand-peace-o" aria-hidden="true"></i></button> <button type="submit" class="btn btn-primary btn-lg btn-block" style="height: 57%;width: 123%;margin-left: -35%;"> <i class="fa fa-commenting-o" aria-hidden="true"></i> </button> </div> </div> </div> </form> chat.views def CreateMessage(request, chat_id, user_id): if request.method == 'POST': message_text = request.POST['message_text'] try: user_get = Account.objects.get(user_id=user_id) user_name = user_get.user_name except: return HttpResponseNotFound('Пользователь не найден, скорее всего вы пытаетесь зайти туда куда вам не льзя') if request.user.is_authenticated: if request.user.username == user_name: y = Chat_group.objects.get(chat_group_id=chat_id) user_chat = Chat_user.objects.filter(chat_user_id=user_id[0]) name_user = user_chat.chat_user_name last_name_user = user_chat.chat_message_user_last_name x = Chat_message(chat_message_user_name=name_user, chat_message_user_last_name=last_name_user, chat_message=message_text, chat_message_group=y) x.save() return HttpResponseRedirect('/chat/{}'.format(chat_id)) I'm sorry that the names of the changes are so crooked. I’ll be blogging if you tell me where the newcomer made mistakes … -
How to implement different users in django rest framework?
I am building an app using django rest framework and react. I have installed rest auth, all auth for user authentication. When i create a super user from console using manage.py createsuperuser or manually add from django admin panel then i can login from route 'rest-auth/login' & get a generated token. But now i want add a different user called Doctor who can access limited features.I want to register the doctor user from django admin. But here i want to register the doctor by only email address & password not user name & password. So the question is how to make a custom user called doctor in django rest framework. Last thing, i have no user model in models.py cause django rest auth handling all staff about user.Important thing is i want to differ all users by email & user name. If i get the user by username & password then i will assume it as a hospital owner & if i can login using email & password then it will be a doctor. -
Django input box problem, url encoded output
def results(request): inp_value = request.GET.get('get_url', '') return HttpResponse(inp_value) The following functions basically gets the input from the html form which is a text field and submit button. To test it out I enter youtube.com/any_video_link but when I render the inp_value variable it prints out the the slash as "%2F" and = as "%3D" What can I do to get the input in the original format? Thanks in advance -
How do I display same form in multiple pages using a single method in django?
I have a table with atrributes, and I'm displaying each attribute as a checkbox in html view. I want to show them in different pages, but I don't want to make different functions for each category. Is there an efficient way to do so? Here is what I tried so far. def questions(request): # start session page for the user to test questions = Attribute.objects.all() realistic = Attribute.objects.filter(holland_code=1) investigative = Attribute.objects.filter(holland_code=2) artistic = Attribute.objects.filter(holland_code=3) social = Attribute.objects.filter(holland_code=4) enterprising = Attribute.objects.filter(holland_code=5) conventional = Attribute.objects.filter(holland_code=6) left = [realistic, investigative, artistic, social, enterprising, conventional] for attribute in left: # get all the values form the form submitted if request.method == "POST": # THIS WILL GET ALL THE RECOMMENDAITONS rAttributes = request.POST.getlist('realistic') print(rAttributes) return render(request, "main/questions.html", {"questions": attribute}) context = { "questions": realistic, } return render(request, 'main/questions.html', context) This is my html template to display the checkboxes <form action="" method="POST"> {% csrf_token %} <div class="form-check"> {% for question in realistic %} <input type="checkbox" class="form-check-input" id="exampleCheck1" name="realistics" value="{{ question.attribute_name }}"> <label class="form-check-label" for="exampleCheck1">{{ question.attribute_name }}</label> <br> {% endfor %} </div> <input type="submit" class="btn btn-danger" value="Next"> </form> -
attributeerror module django db models has no attribute
Every time showing this problem... attributeerror module django db models has no attribute Please help me. `from django.db import models Create your models here. class Student(models.model): name = models.CharField(max_length = 50) age = models.CharField(max_length = 2)` -
How to set IntegerField's max_value in view
This is my form: class GameForm(forms.Form): bid = forms.IntegerField(widget=forms.NumberInput (attrs={'placeholder': 'bid'})) and I would like to set bid max_value according to request.user's amount of money. -
Continue after |truncatechar or break model.TextField() into multiple parts?
Is there a way to chop text into different bits using django? I have a model field that is a TextField(), and I want to output it into a nicely formatted way, based on certain lengths, and if there have been images uploaded an so forth. Is there a way to take this text: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. and chop it into multiple pieces? I want to be able to do something like this: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do <image> eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea <chart> commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat <link> non proident, … -
Django RunTest() missing 2 required positional arguments: 'connection' and 'testSettings'
I'm trying to pass form data on a create_test template to a run_test template but continually get a positional argument error. It's being caused by the form data not actually posting but I'm not entirely sure how to overcome. It would seem if I were to pass parameters through the URLconf path it wouldn't know what it is because it's not stored in the database. Any help would be appreciated: urls.py: urlpatterns = [ path('', views.TestCreate, name='create_test'), path('run_test', views.RunTest, name='run_test',), ] models.py: class ApiGateway(models.Model): name = models.CharField(max_length=50) gatewayip = models.GenericIPAddressField() def __str__(self): return self.name class ChassisIP(models.Model): name = models.CharField(max_length=50) chassisip = models.GenericIPAddressField() def __str__(self): return self.name forms.py: class SiteForm(forms.Form): chassis = ModelChoiceField(queryset=ChassisIP.objects.order_by('name').values_list('chassisip', flat=True).distinct()) class ApiForm(forms.Form): gateway = ModelChoiceField(queryset=ApiGateway.objects.order_by('name').values_list('gatewayip', flat=True).distinct()) views.py: def RunTest(request, connection, testSettings): # RunTest View Code Here def TestCreate(request): if request.method == 'GET': form1 = ApiForm() form2 = SiteForm() return render(request, 'create_test.html', {'form1' : form1, 'form2' : form2} ) else: if request.method == 'POST': testSettings = TestSettings.IxLoadTestSettings() form1 = ApiForm() if form1.is_valid(): testSettings.gatewayServer = form1.cleaned_data['gatewayip'] form2 = SiteForm() if form2.is_valid(): testSettings.chassisList = form2.cleaned_data['chassisip'] connection = RestUtils.getConnection( testSettings.gatewayServer, testSettings.chassisList, ) return render(request, 'create_test.html', connection=connection, testSettings=testSettings ) template: {% block content %} <h1>Test Create Page</h1> <form method='post'> <h2>Select API Gateway</h2> … -
ERROR:root:code for hash md5 was not found. (get this error upon installing django, creating django project and creating app)
I created a virtualenv with python3 -m venv env, activated env and then went to install django with pip install django and it returned the following error(warning?) but did install django: ERROR:root:code for hash md5 was not found. Traceback (most recent call last): File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module> globals()[__func_name] = __get_hash(__func_name) File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor raise ValueError('unsupported hash type ' + name) ValueError: unsupported hash type md5 ERROR:root:code for hash sha1 was not found. Traceback (most recent call last): File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module> globals()[__func_name] = __get_hash(__func_name) File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor raise ValueError('unsupported hash type ' + name) ValueError: unsupported hash type sha1 ERROR:root:code for hash sha224 was not found. Traceback (most recent call last): File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module> globals()[__func_name] = __get_hash(__func_name) File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor raise ValueError('unsupported hash type ' + name) ValueError: unsupported hash type sha224 ERROR:root:code for hash sha256 was not found. Traceback (most recent call last): File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 147, in <module> globals()[__func_name] = __get_hash(__func_name) File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/hashlib.py", line 97, in __get_builtin_constructor raise ValueError('unsupported hash type ' + name) ValueError: unsupported hash type sha256 ERROR:root:code for hash sha384 was not found. Traceback (most recent call last): File … -
Django full calendar
I'm trying to show the data from model in fullcalendar, here is my code: $(document).ready(function () { $('#calendar').fullCalendar({ events: [ {% for i in eventlist %} { title: "{{i.visit_patient_pesel}}", start: "{{i.visit_start}}", end: "{{i.visit_end}}", }, {% endfor %} ] }); }); The problem is that I've got several errors. In this line {% for i in eventlist %} error is: indentifier or string literal or numeric literal expected (error is highlighted just where % is) and after "for" I've got ": or , exected". Can anyone help? -
Django form values not inserted in sqlite3 database tables
I am a newbie in web development using Django. I have created 3 models and correspondingly their forms. Even makemigrations and migrate commands did not report any problem and tables are also created in the SQLite DB file. But still, values are not getting inserted in the DB file. Empty QuerySet is getting received i.e. <QuerySet []>. Could anyone please let me know why values do not get inserted? Thanks in advance. The program snippet:- model.py class User(models.Model): name = models.CharField(max_length=100, default='ABC') password = models.CharField(max_length=50, default='ABC') def __str__(self): print("self.name:", self.name) return self.name class Faculty_Info(models.Model): fid = models.IntegerField(default='123') fname = models.CharField(max_length=50, default="ABC") femail = models.EmailField(max_length=50, default='abc@gmail.com') fcontact = models.IntegerField(default='123') faddress = models.TextField(max_length=50, default='ABC') fsalary = models.IntegerField(default='123') def __str__(self): return self.fname class Student_Info(models.Model): sid = models.IntegerField(default='123') sname = models.CharField(max_length=50, default='ABC') semail = models.EmailField(max_length=50, default='abc@gmail.com') scontact = models.IntegerField(default='123') saddress = models.TextField(max_length=50, default='ABC') def __str__(self): return self.sname views.py def faculty_info_section(request): faculties = Faculty_Info.objects.all() print("faculties", faculties) return render(request, "faculty_info_section.html", {'faculties': faculties}) def add_faculty(request): if request.method == "POST": faculty_form = Faculty_Info_Form(request.POST) print("faculty_form", faculty_form) if faculty_form.is_valid(): try: faculty_form.save() print("faculty_form:", faculty_form) return redirect('/faculty_info_section') except: pass else: faculty_form = Faculty_Info_Form() print("faculty_form_2", faculty_form) return render(request, 'add_faculty.html', {'faculty_form': faculty_form}) faculty_info_section.html {% for faculty in faculties %} <tr> <td>{{ faculty.fid }}</td> <td>{{ … -
"user with this username already exists" in DRF ModelSerializer if not specified explicitly
I'm trying understand why this error occurs even though I know how to resolve. Just trying to understand DRF and Django better. JSON in this format comes from the FE: { "username": "username_here", "password": "password_here" } I have this view: class UserSigninTokenAPIView(APIView): permission_classes = [AllowAny] serializer_class = UserSigninTokenSerializer def post(self, request): data = request.data serializer = UserSigninTokenSerializer(data=data) if serializer.is_valid(raise_exception=True): new_data = serializer.data return Response(new_data, status=HTTP_200_OK) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) Which uses this serializers: class UserSigninTokenSerializer(ModelSerializer): username = CharField() class Meta: model = USERS fields = [ 'username', 'password', 'id' ] def validate(self, data): username = data['username'] password = data['password'] user_qs = USERS.objects.filter(username__iexact=username) if user_qs.exists() and user_qs.count() == 1: user_obj = user_qs.first() password_passes = user_obj.check_password(password) if password_passes: """ A number of checks here I removed to keep this clean, otherwise would just use /api/token/ to get a token. I want user checks to pass before issuing a token, because having the token is what indicates they are logged in successfully. """ token = RefreshToken.for_user(user_obj) return { 'refresh': str(token), 'access': str(token.access_token) } else: Services.user_attempts(user_obj) raise ValidationError({'error': ''' The credentials provided are invalid. <br>Please verify the username and password are correct. '''}) The username = CharField() seems redundant to me. The documentation says: The … -
get user to model from view/form
I created a simple app where you can create poll, after login and see your polls in view. Everything worked fine when i had Question and Choice in separate views and forms but i wanted to make something where user can add forms by clicking button and i wanted to have Question and Choice forms in one view. I'm not very sure how to do it. I found some tutorial for dynamic forms and i came up with that: forms.py class CreateChoiceForm(forms.ModelForm): choice_0 = forms.CharField(required=True) choice_1 = forms.CharField(required=True) class Meta: model = Question fields = ['question_text'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) choice = Choice.objects.filter( question=self.instance ) for i in range(len(choice) + 1): field_name = 'choice_%s' % (i,) self.fields[field_name] = forms.CharField(required=False) try: self.initial[field_name] = choice[i].choice except IndexError: self.initial[field_name] = "" field_name = 'choice_%s' % (i+1,) self.fields[field_name] = forms.CharField(required=False) def save(self, commit=True): question = self.instance question.author = self.request.user question.question_text = self.cleaned_data['question_text'] question.choice_set.all().delete for i in range(2): choice = self.cleaned_data['choice_text'] Choice.objects.create(question=question, choice=choice) def get_interest_fields(self): for field_name in self.fields: if field_name.startswith('choice_'): yield self[field_name] The problem is that now i've got this error when i'm trying to submit my forms: https://i.imgur.com/uw2e8jM.png Environment: Request Method: POST Request URL: http://127.0.0.1:8000/polls/createPoll/ Django Version: 2.2.5 Python Version: 3.6.10 … -
Does a graphene django Endpoint expects a X-Csrftoken and CsrfCookie at the same time?
Using: Django 3.x [ Django-Filters 2.2.0, graphene-django 2.8.0, graphql-relay 2.0.1 ] Vue 2.x [ Vue-Apollo ] I am testing single page vue app´s with Django, GraphQL & Vue-Apollo. If i use csrf_exempt on my view everything works in the frontend. urlpatterns = [ <...> path("graphql", csrf_exempt(GraphQLView.as_view(graphiql=True))), <...> Now i wanted to CSRF protect my request. Within the process of understanding the CSRF protection, i thought all Django GraphQLView needs is to receive the "value" of the X-Csrftoken in the Request Header. So i focused on sending the csrf Value in different ways...via a single view like this path('csrf/', views.csrf), path("graphql", GraphQLView.as_view(graphiql=True)), or by ensure a cookie with ensure_csrf_cookie Afterwards in my ApolloClient i fetch thes Value and send him back with the request Header . This i what Django prints when i send a GraphQL request from a Django-Vue page. Forbidden (CSRF token missing or incorrect.): /graphql Parallel i always test with thegraphiql IDE and these requests still working. I also print everytime the info.context.headers value of my query resolver. {'Content-Length': '400', 'Content-Type': 'application/json', 'Host': 'localhost:7000', 'Connection': 'keep-alive', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache', 'Accept': 'application/json', 'Sec-Fetch-Dest': 'empty', 'X-Csrftoken': 'dvMXuYfAXowxRGtwSVYQmpNcpGrLSR7RuUnc4IbIarjljxACtaozy3Jgp3YOkMGz', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 … -
Django Form in ListView, error on POST of Form
Im trying to implement a chat-function for my website. In order to do that, i followed the following tutorial: https://channels.readthedocs.io/en/latest/tutorial/ I've then changed the code a little bit in order to implement it. Until here, everything works just fine. Now I want to store the form-data inside of a database, and thats where the problem appears. But first my code: urls.py: from django.urls import path from .views import ChatOverView urlpatterns = [ path('<int:pk>/', ChatOverView.as_view(), name='chat-explicit'), path('', ChatOverView.as_view(), name='chat-home'), ] views.py (theres much code here that is probably not needed for this question, but since i dont know what part of it i can ignore, im just posting the whole file-content): from django.views.generic import ListView from django.views.generic.edit import FormMixin, FormView from django.db.models import Q from django.urls import resolve from django.contrib.auth.models import User from django.shortcuts import get_object_or_404 from .models import Message from .forms import MessageRegisterForm class ChatOverView(ListView, FormMixin): model = Message template_name = 'chat/home-chat.html' form_class = MessageRegisterForm success_url = '/thanks/' def form_valid(self, form): form = self.get_form() if form.is_valid(): data = form.cleaned_data return super().form_valid(form) def get_context_data(self, *args, **kwargs): context = super(ChatOverView, self).get_context_data(*args, **kwargs) messages_raw = reversed(Message.objects.filter(Q(sender=self.request.user) | Q(receiver=self.request.user))) messages = {} for mes in messages_raw: # i am receiver if mes.sender != self.request.user: … -
Keeping track of Push Notifications
I've recently implemented push notifications into my Angular app. Everything works as expected. I ask the user for their permission and send the SubscriptionInfo to my django backend, where I store it in a database for actual notifications. The SubscriptionInfo looks something like this: { "endpoint": "https://fcm.googleapis.com/fcm/send/cbx2QC6AGbY:APA91bEjTzUxaBU7j-YN7ReiXV-MD-bmk2pGsp9ZVq4Jj0yuBOhFRrUS9pjz5FMnIvUenVqNpALTh5Hng7HRQpcUNQMFblTLTF7aw-yu1dGqhBOJ-U3IBfnw3hz9hq-TJ4K5f9fHLvjY", "expirationTime": null, "keys": { "p256dh": "BOXYnlKnMkzlMc6xlIjD8OmqVh-YqswZdut2M7zoAspl1UkFeQgSLYZ7eKqKcx6xMsGK7aAguQbcG9FMmlDrDIA=", "auth": "if-YFywyb4g-bFB1hO9WMw==" } } Now during testing, the backend threw an error 410 GONE when sending the subscription (I dont know why, deleting the row in the backend and re-allowing notifications in the frontend fixed the issue), indicating that the subscription is no longer valid and should be deleted. Of course I have to somehow inform the frontend about this, delete the 'local' notification token and re-ask for permission from the user. Informing the frontend is not a problem, however, as one user can have multiple devices (or browsers) to recieve notifications, I have to somehow check in the frontend, which subscription has to be 'renewed'. Therefore, I thought about using some kind of uid (consisting of the browser name, version etc), however, that presents several issues: What if the browser gets updated? The subscription object should not be affected by this, it would still be valid, … -
How do I tell my serializer it's fine for a field to be blank?
Using Django 2.0, Python 3.7, and the django-phonenumber-field (v 4.0.0) module. I have a model with my phone number field, that I don't want to be required ... from phonenumber_field.modelfields import PhoneNumberField ... class Coop(models.Model): name = models.CharField(max_length=250, null=False) type = models.ForeignKey(CoopType, on_delete=None) address = AddressField(on_delete=models.CASCADE) enabled = models.BooleanField(default=True, null=False) phone = PhoneNumberField(null=True) email = models.EmailField(null=True) web_site = models.TextField() I have created this web/maps/views.py file to handle the POST request ... class CoopDetail(APIView): """ Retrieve, update or delete a coop instance. """ def get_object(self, pk): try: return Coop.objects.get(pk=pk) except Coop.DoesNotExist: raise Http404 def get(self, request, pk, format=None): coop = self.get_object(pk) serializer = CoopSerializer(coop) return Response(serializer.data) def put(self, request, pk, format=None): coop = self.get_object(pk) serializer = CoopSerializer(coop, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) and then I have this web/maps/serializers.py call ... class CoopSerializer(serializers.ModelSerializer): type = CoopTypeField() address = AddressTypeField() class Meta: model = Coop fields = ['id', 'name', 'type', 'address', 'enabled', 'phone', 'email', 'web_site'] def to_representation(self, instance): rep = super().to_representation(instance) rep['type'] = CoopTypeSerializer(instance.type).data rep['address'] = AddressSerializer(instance.address).data return rep def create(self, validated_data): """ Create and return a new `Snippet` instance, given the validated data. """ return Coop.objects.create(**validated_data) def update(self, instance, validated_data): """ Update and return an existing `Coop` instance, …