Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
pymysql.err.IntegrityError: (1048, "Column 'dob' cannot be null")
I am trying to use a datepicker for the date of in my forms, i decided to use he input type date which is supported by most some browsers. i keep getting this error anytime i try to create super user or migrate. I have removed my migrations for the app and added them back with python manage.py makemigrations but the problem still persists. i do not want to wipe out the database, i have tried this with postgres(local) and mysql(production) and the error is the same. This is the traceback error. Traceback (most recent call last): File "/home/navararl/virtualenv/repositories/health/3.7/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/home/navararl/virtualenv/repositories/health/3.7/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 73, in execute return self.cursor.execute(query, args) File "/home/navararl/virtualenv/repositories/health/3.7/lib/python3.7/site-packages/pymysql/cursors.py", line 163, in execute result = self._query(query) File "/home/navararl/virtualenv/repositories/health/3.7/lib/python3.7/site-packages/pymysql/cursors.py", line 321, in _query conn.query(q) File "/home/navararl/virtualenv/repositories/health/3.7/lib/python3.7/site-packages/pymysql/connections.py", line 505, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "/home/navararl/virtualenv/repositories/health/3.7/lib/python3.7/site-packages/pymysql/connections.py", line 724, in _read_query_result result.read() File "/home/navararl/virtualenv/repositories/health/3.7/lib/python3.7/site-packages/pymysql/connections.py", line 1069, in read first_packet = self.connection._read_packet() File "/home/navararl/virtualenv/repositories/health/3.7/lib/python3.7/site-packages/pymysql/connections.py", line 676, in _read_packet packet.raise_for_error() File "/home/navararl/virtualenv/repositories/health/3.7/lib/python3.7/site-packages/pymysql/protocol.py", line 223, in raise_for_error err.raise_mysql_exception(self._data) File "/home/navararl/virtualenv/repositories/health/3.7/lib/python3.7/site-packages/pymysql/err.py", line 107, in raise_mysql_exception raise errorclass(errno, errval) pymysql.err.IntegrityError: (1048, "Column 'dob' cannot be null") The above exception was the direct cause of the following exception: Traceback (most recent … -
csrftoken in django rest framework - sending through HTTPIE
I'm trying to login through the http form, from DRF: > https://my.site.io/api-auth/login/ Using httpie, i generate a session.json to get the CSRFToken: $ http --session=why -h https://my.site.io/api-auth/login/ Referrer-Policy: same-origin Server: nginx/1.18.0 Set-Cookie: csrftoken=dT2UuBjp7Xei2iqzmD9A9lNNaTZO8ZHHPh098I8mV27v56E0jePTPgQ0KC3LDmpE; expires=Thu, 02 Dec 2021 15:32:49 GMT; Max-Age=31449600; Path=/; SameSite=Lax Vary: Cookie X-Content-Type-Options: nosniff I use the csrftoken from cookies and : http --session=why -h POST https://my.site.io/api-auth/login/ username=user password=pass X-CSRFToken:dT2UuBjp7Xei2iqzmD9A9lNNaTZO8ZHHPh098I8mV27v56E0jePTPgQ0KC3LDmpE -p Hh This is the out put (With both request and response headers): POST /api-auth/login/ HTTP/1.1 Accept: application/json, */*;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Content-Length: 49 Content-Type: application/json Cookie: csrftoken=dT2UuBjp7Xei2iqzmD9A9lNNaTZO8ZHHPh098I8mV27v56E0jePTPgQ0KC3LDmpE Host: my.site.io User-Agent: HTTPie/2.3.0 csrfmiddlewaretoken: dT2UuBjp7Xei2iqzmD9A9lNNaTZO8ZHHPh098I8mV27v56E0jePTPgQ0KC3LDmpE HTTP/1.1 403 Forbidden Connection: keep-alive Content-Length: 3366 Content-Type: text/html Date: Thu, 03 Dec 2020 15:33:37 GMT Referrer-Policy: same-origin Server: nginx/1.18.0 X-Content-Type-Options: nosniff X-Frame-Options: DENY I tried to use X-CSRFToken instead of csrfmiddlewaretoken I can perform the login through a browser, if a browser is working, i don't see as it can be a problem from the Django Rest Framework configuration. Maybe i'm doing something wrong with httpie What can it be? Thanks in advance. -
Postgres-alpine can not connect to Django project container
I am using CentOS 8 and GitLab ci/cd and I'm trying to deploy a Django project, I don't have any idea why the Django container can not connect to Postgres container, you can see all of the configurations below: .env POSTGRES_DB = somthing POSTGRES_USER = user POSTGRES_PASSWORD = pass POSTGRES_HOST = db POSTGRES_PORT = 5432 .env.db POSTGRES_DB=somthing POSTGRES_USER=user POSTGRES_PASSWORD=pass POSTGRES_PORT = 5432 deploy.sh #!/usr/bin/env bash ssh -o StrictHostKeyChecking=no something@my_ip<< 'ENDSSH' cd some-thing/ docker-compose down git pull https:/user:pass@gitlab.com/neo1992/something.git docker login -u user -p pass registry.gitlab.com docker pull registry.gitlab.com/neo1992/some-thing:latest docker-compose up -d ENDSSH docker-compose version: "3.8" services: api: image: registry.gitlab.com/neo1992/something:latest build: context: . container_name: api command: bash -c 'python manage.py migrate --noinput && python manage.py makemigrations && python manage.py migrate --noinput && python manage.py collectstatic --noinput && gunicorn something.wsgi:application -b 0.0.0.0:8000 --capture-output --log-level=info' volumes: - static_volume:/home/something/some-thing/static - media_volume:/home/something/some-thing/media ports: - "8000:8000" depends_on: - db env_file: .env db: image: postgres:12.0-alpine container_name: db volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.db ports: - "5432:5432" nginx: build: ./nginx container_name: nginx ports: - "80:80" volumes: - static_volume:/home/something/some-thing/static - media_volume:/home/something/some-thing/media depends_on: - api volumes: postgres_data: static_volume: media_volume: Django DB settings: Django setting: from envparse import env env.read_envfile() DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": env("POSTGRES_DB", default=""), "USER": env("POSTGRES_USER", … -
Streaming a zip file in Python3
In my Django project, I have large zip files I need to send to a user for them to download. These files can be up to 10Gb big at some points. The files are already in zip format, and I don't want to extract them. Instead, I would like to send say 100mb of the file at a time, wait for the frontend to receive them, and then ask for the next 100mb until the file has been completely read. I can handle the collection and download on the frontend, but how can I perform this request in Django? Disclaimer: I'm a frontend developer, and very new to python. -
why do double quotes inside double quotes work in django
In a html file in django why does this: <link rel="stylesheet" href="{% static "myapp/style.css"%}" /> work and produces the same result as: <link rel="stylesheet" href="{% static 'myapp/style.css'%}" /> -
which framework is better Spring MVC or Django?
Which framework is better Spring MVC or Django, and why? I have a confusion on which is better and if someone has basic idea of both the frameworks then which one should he use for future -
How to restrict form validation for users under 18 years of age in Django
I have a form that allows users to update their birthday on their profile. I only want the form to validate if the user is at least 18 years of age. Here's what I've tried: models.py class Profile(models.Model): birthday = models.DateField() forms.py from django import forms from datetime import date from .models import Profile class ProfileUpdateForm(forms.ModelForm): birthday = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'})) def clean_birthday(self): dob = self.cleaned_data['birthday'] age = (date.today() - dob).days / 365 if age < 18: raise forms.ValidationError('You must be at least 18 years old') return dob class Meta: model = Profile fields = ('birthday',) views.py @login_required def update_my_profile_view(request): profile = Profile.objects.get(user=request.user) if request.method == 'POST': form = ProfileUpdateForm(request.POST or None, instance=profile) if form.is_valid(): form.save() return redirect('users:my_profile') else: form = ProfileUpdateForm() context = { 'form': form, } return render(request, 'users/my_profile.html', context) At the moment if I enter a date which is less than 18 years from the current day the date is simply not displayed. What I want instead is for the form to become invalid and show the user an error. How can I achieve this please? -
Create object in model having foreigkey relation
I want to create an entry in this Something model in python manage.py shell using this Someting.objects.create(discussion_title="General", user_username="admin", content="Hello") models example class Discussion(models.Model): title = models.CharField(max_length=255, unique=True, blank=False,) users = models.ManyToManyField(User, blank=True, ) class Something(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) discussion = models.ForeignKey(Discussion, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) content = models.TextField(unique=False, blank=False) I am getting this error TypeError: Something() got an unexpected keyword argument 'discussion_title' -
Django key value pair to template
I am new to Django, and learning it for a school project. Part of the project is to have a time scheduler. I tought it was best to do with a key - value database structure, so I did. Now I am struggeling with getting it in to my template. This is my models.py key-value model: class generalSetting(models.Model): key = models.CharField(max_length=200, unique=True, null=True) value = models.CharField(max_length=200, null=True) def __str__(self): return self.key views.py: def timetable(request): generalSettings = generalSetting.objects.all() return render(request, 'VulnManager/timetable.html', {'generalSettings':generalSettings}) Here is the table on which I want to have the data <table id="tablePreview" class="table table-borderless table-hover"> <!--Table head--> <thead> <tr> <th></th> <th>Monday</th> <th>Tuesday</th> <th>Wednesday</th> <th>Thursday</th> <th>Friday</th> <th>Saturday</th> <th>Sunday</th> </tr> </thead> <!--Table head--> <!--Table body--> <tbody> <tr> <th scope="row">Scan?</th> <td><select class="form-control" id="scanMonday" disabled="true"><option>Yes</option><option>No</option></select></td> <td><select class="form-control" id="scanTuesday" disabled="true"><option>Yes</option><option>No</option></select></td> <td><select class="form-control" id="scanWednesday" disabled="true"><option>Yes</option><option>No</option></select></td> <td><select class="form-control" id="scanThursday" disabled="true"><option>Yes</option><option>No</option></select></td> <td><select class="form-control" id="scanFriday" disabled="true"><option>Yes</option><option>No</option></select></td> <td><select class="form-control" id="scanSaturday" disabled="true"><option>Yes</option><option>No</option></select></td> <td><select class="form-control" id="scanSunday" disabled="true"><option>Yes</option><option>No</option></select></td> </tr> <tr> <th scope="row">Time begin</th> <td><input type="text" id="startMonday" onchange="validateHhMm(this);" value="{{generalSettings(key='startMonday')}}" readonly /></td> <td><input type="text" id="startTuesday" onchange="validateHhMm(this);" value="9:00" readonly /></td> <td><input type="text" id="startWednesday" onchange="validateHhMm(this);" value="9:00" readonly /></td> <td><input type="text" id="startThursday" onchange="validateHhMm(this);" value="9:00" readonly /></td> <td><input type="text" id="startFriday" onchange="validateHhMm(this);" value="9:00" readonly /></td> <td><input type="text" id="startSaturday" onchange="validateHhMm(this);" value="" readonly /></td> <td><input type="text" id="startSunday" onchange="validateHhMm(this);" value="" … -
how to call django url with javascript?
i am first time using javascript. i want to know how can i use django urls in javascript. i have a problem with using django url link in javascript. i want to render product-detail page and product-update page using django url in javascript. index.js const Story = document.getElementById('approvedList'); const url = 'http://localhost:8000/api/approved/'; getPosts = () => { axios.get(url) .then((res) => { Story.innerHTML = ''; res.data.map((object) => { document.getElementById(".detaillink").onclick = function () { var detailLink = document.attr('id') location.href = "{% url 'detail' pk=object.pk %}" }; document.getElementById(".updatelink").onclick = function () { var updatelLink = document.attr('id') location.href = "{% url 'update' pk=object.pk %}" }; Story.innerHTML += ` <tr> <td>${object.id}</td> <td><a href="#" class="detailLink">${object.title}</a></td> <td> <div class="table-btns"> <a href="" class="updatelink"> Update </a> </div> </td> </tr> `; }) }) .catch(error => console.log(error)) }; getPosts(); setInterval(getPosts, 3000) -
when do you use quotes in django [closed]
I’m learning django and am a little confused about the use of quotes. It seems that you can use double quotes inside of double quotes instead of the standard double quote single quote paradigm. Also, it seems that some references to urls get quoted and others do not. Can someone point me to the documentation on the use of quotes when coding in django? -
Store data in session for Anonymous User in Django
I need to store token in session for Anonymous User. In one view the data is stored and I can see it in request. But in another request session is empty, but keys are equal. I store data as it in docs: request.session['token'] = token Also session in request in view where data was added: {'_SessionBase__session_key': '6isiuup8xdq7nfr34cmog78t6lkc13p3', 'accessed': True, 'modified': True, 'serializer': <class 'django.core.signing.JSONSerializer'>, 'model': <class 'django.contrib.sessions.models.Session'>, '_session_cache': {'access_token': 'access-sandbox-1d05b2ac-81b4-4126-a57a-7c0ba916252e'}} After that, in another view: {'_SessionBase__session_key': '6isiuup8xdq7nfr34cmog78t6lkc13p3', 'accessed': False, 'modified': False, 'serializer': <class 'django.core.signing.JSONSerializer'>} In settings: INSTALLED_APPS = [ ... 'django.contrib.sessions', ... ] MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', ... ] I read all docs and still can't find the reason of such strange behavior. Or may be I don't understand smth. -
Django Ajax how would i delete the comment using ajax instead of a normal request?
I have code set up so that users can delete comments on an article. However currently, when they delete the comment it will refresh the page and take them back to the top. I'm trying to implement Ajax so that when they delete the comment it'll do it without a page refresh. This is the code I have currently for deleting a comment. index.py <form action="{% url 'add-delete-view' %}" method="POST" class="ui form"> {% csrf_token %} <input type="hidden" name="comment_id" value="{{c.id}}"> <button type="submit" onClick="deleteComment({{c.id}})" id= "{{c.id}}" class="ui primary button c_edit{{c.id}}" name="submit_d_form">delete</button> urls.py path('deleteComment/', views.delete_comment, name='add-delete-view') views.py @login_required def delete_comment(request): comment_obj = Comment.objects.get(id=request.POST.get('comment_id')) comment_obj.delete() return redirect('index') I've attempted to try and implement Ajax but I'm just feeling hopeless in trying to get it work. In index.py I've added function: function deleteComment(comment_id) { var action = confirm("Are you sure you want to delete this comment?"); var comment = $(this) if (action != false) { $.ajax({ method: 'DELETE', url: '{% url "add-delete-view" %}', success: function (data, textStatus, jqXHR) { comment.remove(); }, }); } } But I'm just not sure where to go next or if this will even work. Any help or code would be greatly appreciated. It feels like this simple concept is very … -
CKEditor custom config not working, And it has different options inside and outside of admin panel
based on customizing CKEditor editor I declared a custom config in settings.py: CKEDITOR_CONFIGS = { 'awesome_ckeditor': { 'toolbar': 'Basic', 'toolbar_CustomToolbarConfig': [ {'name': 'clipboard', 'items': ['Bold', '-', 'Undo', 'Redo']}, {'name': 'paragraph', 'items': ['NumberedList', 'BulletedList', '-', 'BidiLtr', 'BidiRtl', '-', 'spellchecker' ]}, ], }, } this config is used in models.py: description = RichTextField(config_name='awesome_ckeditor', blank=True) in html file I use ckeditor in this way: <form action="{% url 'contact' %}" method="POST"> {% csrf_token %} <div> <textarea name="message" id="message" class="form-control"></textarea> </div> </form> <script type="text/javascript" src="{% static "ckeditor/ckeditor-init.js" %}"></script> <script type="text/javascript" src="{% static "ckeditor/ckeditor/ckeditor.js" %}"></script> <script src="//cdn.ckeditor.com/4.15.0/full/ckeditor.js"></script> <script> CKEDITOR.replace( 'message'); CKEDITOR.config.allowedContent = true; CKEDITOR.config.removeFormatAttributes = ''; </script> this config is not working. how to load it? before declaring this config, I was getting different editor options inside admin panel and outside ot it: inside admin panel: and outside it: how to fix this config so all pages have same config? -
Django&React, "detail": "Authentication credentials were not provided. (CSRF)
] ------ react ------ csrftoken.js import axios from 'axios'; import React from 'react'; function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].replace(' ', ''); if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } export const CSRFToken = () => { const csrftoken = getCookie('csrftoken'); console.log('token : ' + csrftoken); return( <input type="hidden" name="csrfmiddlewaretoken" value={csrftoken}/> ) }; export default CSRFToken; module.js const getplayerEpic = (action$, state$) => { return action$.pipe( ofType(GET_player), withLatestFrom(state$), mergeMap(([action, state]) => { console.log(state.CSRFToken.props.value) return ajax.get('/api/player/', {headers: {'X-CSRFToken': state.CSRFToken.props.value }} ).pipe( map(response => { const player = response.response; return getplayerSuccess({player}); }), catchError(error => of({ type: GET_player_FAILURE, payload: error, error: true, }) ) ); }) ); }; ------ django(python) ------ view.py class Listplayer(generics.ListCreateAPIView): permission_classes = [djangomodelpermissions, ] queryset = playerList.objects.all() serializer_class = playerListSerializer settting.py ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'post', 'rest_framework', 'polls.apps.PollsConfig', 'notes', 'knox', 'patientList', 'hospital', 'doctor', 'diagnosis', 'diagnosis.core', 'fundusList', 'users', ] REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 10, 'DEFAULT_AUTHENTICATION_CLASSES': ('knox.auth.TokenAuthentication',), 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ] … -
django urls exceptions NoReverseMatch
Good day, I have got a Django project where I want to link to order_detail but I get this error: django.urls.exceptions.NoReverseMatch: Reverse for 'orderdetail' with arguments '('',)' not found. 1 pattern(s) tried: ['orders/myorder/detail/(?P<order_id>[0-9]+)$'] models.py from datetime import timezone from django.contrib.auth.models import User # Create your models here. from django.db import models from django.forms import ModelForm from django.urls import reverse from shop.models import Product from decimal import Decimal from django.core.validators import MinValueValidator, MaxValueValidator from coupons.models import Coupon class Order(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() address = models.CharField(max_length=250) phone_number = models.CharField(max_length=20) city = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) braintree_id = models.CharField(max_length=150, blank=True) reference_id = models.DateTimeField(auto_now_add=True, blank=True) coupon = models.ForeignKey(Coupon, related_name='orders', null=True, blank=True, on_delete=models.SET_NULL) discount = models.IntegerField(default=0, validators=[ MinValueValidator(0), MaxValueValidator(100) ]) class Meta: ordering = ('-created',) def __str__(self): return self.first_name def get_absolute_url(self): return reverse('orders:orderdetail', args=[self.id]) def get_total_cost(self): total_cost = sum(item.get_cost() for item in self.items.all()) return total_cost - total_cost * (self.discount / Decimal(100)) def delivery_fee(self): fee = 500 return fee def get_total_after_delivery(self): total = self.get_total_cost() + self.delivery_fee() return total class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='order_items', on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) def __str__(self): … -
Cannot resolve keyword 'articles' into field.Choices are: Choices are: author, caption,id etc
I am trying to relate articles for the user.Here are my codes: Models.py class User(AbstractUser,PermissionsMixin): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) email = models.CharField(max_length=255,unique=True) username =models.CharField(max_length=80,unique=True,default='SOME STRING') USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() class Meta: verbose_name = _('user') verbose_name_plural = _('users') class Article(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='articles') caption = models.CharField(max_length=250) Serializers.py class UserSerializer(serializers.ModelSerializer): articles_set = serializers.SerializerMethodField() def get_articles_set(self, user): return ArticleViewSerializer(Article.objects.filter(articles__author=user), many=True).data class Meta: model = User fields = ('id','email','username','articles_set') class ArticleViewSerializer(serializers.ModelSerializer): author = UserSerializer(required=False,read_only=True) class Meta: model = Article fields = ('id','author','caption') def create(self, validated_data): return Article.objects.create(**validated_data) Now the issue here is that whenever i try to relate article to a user,i face with this problem Cannot resolve keyword 'articles' into field. Choices are: author, author_id, caption, comments, id How can i solve this problem? -
Django + Ajax. Data submitted two times in database when I click on button at first time
I use django for backend. Data submitted two times when I click button at first time and data submit one time when I clicked button second time and send response two time also. I am not know more about Jquery or Ajax.I need only one time data submit in database. views.py: @require_POST def checkAns(request,pk,ans,user): if request.method == 'POST': question = Question.objects.get(pk=pk) if ans == question.answer_hidden: message = 'Correct' fetch_name = Register.objects.get(name=user) user_data = SubmitAnswer.objects.get_or_create(name=fetch_name) score_in = SubmitAnswer.objects.get(name=fetch_name) score_in.score += question.point score_in.save() else: message = "False" ctx = {'message': message} return HttpResponse(json.dumps(ctx), content_type='application/json') question.html: **Other stuff like question,radio button,etc** <button type="submit" class="btn btn-primary" id="b1" onclick="getans()">click</button> <p id="userans"></p> <script> $(document).ready(function () { $('#b1').on('click', function (e) { const id = document.getElementById('question_id').className const ans = document.getElementById('userans').innerText const user = document.getElementById('session').innerText $(".rb").show(); $(".rb").attr("disabled", true); $.ajax({ type: "POST", url: `http://127.0.0.1:8000/checkAns/${id}/${ans}/${user}/`, data: { 'csrfmiddlewaretoken': '{{ csrf_token }}' }, dataType: "json", success: function (response) { console.log(response) }, error: function (rs, e) { if(rs.status === 404){ alert("Please, Select Appropriate Option") } else{ alert("sorry, Something went wrong!!!") } } }) }); }); </script> <script type="text/javascript"> function getans(e){ document.getElementById("userans").innerHTML = ""; var e = document.getElementsByTagName("input"); for(i = 0; i<=e.length; i++){ if(e[i].type == 'radio') { if(e[i].checked){ document.getElementById("userans").innerHTML = e[i].value } } } … -
Invalid symlink "venv/bin/python3"
I'm trying to upload my Django code to Heroku but I am getting a build error.. === Fetching app code failed. =!= Invalid symlink "venv/bin/python3". Cannot point outside the working directory My Pipfile is name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] [packages] django = "~=3.1.0" whitenoise = "==5.1.0" gunicorn = "==19.9.0" psycopg2-binary = "==2.8.5" pillow = "==7.2.0" django-debug-toolbar = "==2.2" environs = {version = "==8.0.0", extras = ["django"]} django-storages = "*" boto3 = "*" [requires] python_version = "3.8" Is anyone able to help me please? -
How can I storage IP addresses any time someone logs in my app? Django
My goal si to storage Ip addresses and make an alert if in the next login the ip address of that person isn't the same. How can I do? -
Django tests are not working but views do
I'm trying to test to insert data into db to test if My views are working. What could i do to see what's happening inside the page? I've one error, when i try to assert if data that I've sent to My form exists. The stranger thing is that when i run My application with runserver, everything works fine, but when i'm in test, the view doesn't work. -
Return Full image Url in Django Rest Framework For Image
I am facing problem in returned image url, which is not proper. My return image URL is "/media/slider_image/image/slider_image_4ea48daf-477d-4f00-93cb-7ac87c6f4002.JPG", but actual URL expected from serializer is http://127.0.0.1:8000/media/slider_image/image/slider_image_4ea48daf-477d-4f00-93cb-7ac87c6f4002.JPG Here is my snippet of my Code that I have tried. class ListSliderSerializer(SliderSerializers): images = serializers.SerializerMethodField('get_images') def get_images(self, instance): return [slider_image.image.url for slider_image in instance.slider_image.all()] class Meta(SliderSerializers.Meta): fields = ( 'images', 'section', 'tag', ) what should i return in return [slider_image.image.url for slider_image in instance.slider_image.all()] to get full url for my image? -
docker-compose Vue Connection Reset Error
I am trying to start my Vue.js and Django Application with docker-compose. I can access the Django server, but the Vue frontend answers with Error: The connection was reset. Here are my Files: Dockerfile-django: FROM alpine:latest RUN apk add --update python3 py3-pip WORKDIR /app/backend COPY . . RUN pip3 install -r requirements.txt RUN python3 manage.py makemigrations RUN python3 manage.py migrate EXPOSE 8000 CMD [ "python3", "manage.py", "runserver", "0.0.0.0:8000" ] Dockerfile-vue: FROM alpine:latest RUN apk add --update nodejs npm WORKDIR /app/frontend COPY . . RUN npm install --save axios @vue/cli bootstrap-vue v-tooltip @popperjs/core jquery @vue/test-utils jest RUN npm audit fix RUN npm run build EXPOSE 8080 CMD [ "npm", "run", "dev" ] docker-compose.yml: version: "3.8" services: django-server: build: context: "./backend" dockerfile: "Dockerfile-django" ports: - "8000:8000" container_name: app-backend vue-ui: build: context: "./frontend" dockerfile: "Dockerfile-vue" ports: - "8080:8080" container_name: app-ui Both containers start fine and as I said, I can access the Django server just fine. Only the frontend seems to be the problem. -
Django reload current page using a button
Is there actually any way to simply reload the page in Django I'm currently viewing, preferably at the template with a button? Why do I need this: My website displays messages and I simply just want to give the user the ability to click on a button to make the message disappear. To make a message disappear I have to reload the current page ... Implementing this is JS is not an option! Thanks and kind regards -
TypeError at /cart/ 'Product' object is not subscriptable
I'm creating cart model in RESTful API project. For each product in request by using for statement I want to save each product, cauz in one request may appear more than one product in cart. Below is my serializers.py: from rest_framework import serializers from main.serializers import ProductDetailsSerializer from main.models import Cart, Product, CartProduct # создаем сериализатор orderproduct class CartProductSerializer(serializers.ModelSerializer): class Meta: model = CartProduct fields = ('product', 'count') class CartProductRepresentationSerializer(serializers.ModelSerializer): id = serializers.IntegerField(source='product.id') title = serializers.CharField(source='product.title') class Meta: model = CartProduct fields = ('id', 'title', 'price', 'count', 'product') class AddProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('id') class CartSerializer(serializers.ModelSerializer): items = CartProductSerializer(many=True, write_only=True) # здесь мы добавляем этот продукт заказа class Meta: model = Cart fields = ('count', 'items') # передаем все эти поля сюда def get_total_cost(self, obj): return obj.get_total_cost() # здесь мы добавляем total cost (def get_total_cost(self. obj)) def create(self, validated_data): request = self.context.get('request') items = validated_data.pop('items') cart = Cart.objects.create(**validated_data) if request.user.is_authenticated: cart.user = request.user cart.save() for product in items: product = product['product'] # print(product) product_id = request.GET.get('product') CartProduct.objects.create(cart=cart, product_id=product_id, price=product.price, count=product['count']) product.save() def to_representation(self, instance): representation = super().to_representation(instance) representation['user'] = instance.user representation['product'] = CartProductRepresentationSerializer(instance.products.all(), many=True, context=self.context).data return representation Here is the models. I create Cart and CartProduct …