Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can i create unit tests a view that returns data in json in django
I was wondering how I can create unit tests for a view like this. I have several of these in my project. def json_list_user(request): data = list(Us.objects.values()) return JsonResponse(data, safe=False) -
Django: Handle migrations created in site-packages for a custom Group field
I require a description field added to the django.contrib.auth.models.Group, so I used this solution (if there is a better way please let me know): from django.contrib.auth.models import Group Group.add_to_class('description', models.TextField(max_length=250, default="")) Unfortunately this creates a migration in: site-packages/django/contrib/auth/migrations/0013_group_description.py This is the migration: class Migration(migrations.Migration): dependencies = [ ('auth', '0012_alter_user_first_name_max_length'), ] operations = [ migrations.AddField( model_name='group', name='description', field=models.TextField(default='', max_length=250), ), ] This can't be checked into source code since it's in the python site-packages location. I managed to find the MIGRATION_MODULES setting, but unfortunately I don't wish to move all of the auth app's migration to a new dir (django comes with 12 migrations already for auth, and may ship more in the future. No idea how to solve this problem. It really makes deployment a nightmare. -
ModuleNotFoundError when starting celery in Django project
I have a Django project structure like this (not showing all the files/folders): myproj/ ├── __init__.py ├── config/ │ ├── __init__.py <-- imports `celery_app` as per docs │ ├── settings/ │ │ ├── __init__.py │ │ └── base.py │ ├── celery.py <-- defines `app = Celery("myproj")` │ └── wsgi.py ├── myapp1/ └── myapp2/ I have a docker-compose.yml that sets up web and worker services, and the worker service is something like: worker: build: context: "." target: "app" command: celery -A config worker -l info entrypoint: [] But whatever I try for the -A when starting celery I get ModuleNotFound. I've tried config, myproj.config and myproj. I've tried adding --workdir=/path/to/myproj, but no joy. -
difficulties in python and django integration
Traceback (most recent call last): File "C:\Users\lanje\PycharmProjects\newenv\DjongoProject\lib\site-packages\django\db\utils.py", line 113, in load_backend return import_module("%s.base" % backend_name) File "C:\python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'mypackage' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\lanje\PycharmProjects\newenv\connectivitty\manage.py", line 22, in <module> main() File "C:\Users\lanje\PycharmProjects\newenv\connectivitty\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\lanje\PycharmProjects\newenv\DjongoProject\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\lanje\PycharmProjects\newenv\DjongoProject\lib\site-packages\django\core\management\__init__.py", line 420, in execute django.setup() File "C:\Users\lanje\PycharmProjects\newenv\DjongoProject\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\lanje\PycharmProjects\newenv\DjongoProject\lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "C:\Users\lanje\PycharmProjects\newenv\DjongoProject\lib\site-packages\django\apps\config.py", line 304, in import_models self.models_module … -
using request.user shows the data that user is created in a application How can i show those data to others user's
I created q and a platform for university students and successfully implemented like functionality in it, and now i want to shows the number of like in the user profile, I also successfully added the number of likes to every user profile, but the problem was only the user that get likes from the answer model can see the number of likes in his profile, How can i allowed other's user's to see the number of likes in his profile, when someone likes his answer in a application, i knew using request.user shows only the content that user own in the application, but does'nt how to shows those likes to other. user profile template: <br> <br> <div class="container"> <div class="row justify-content-center"> <div class="col"> <div class="text-center"> <span class="badge bg-secondary">{{number_of_likes}}</span> <br> <br> <a href="" class="btn btn-primary"> Number Of Votes: </a> <br> </div> </div> </div> </div> my views: def public_profile(request, slug): profile = get_object_or_404(Profile, slug=slug) number_of_likes = Like.objects.filter(post__user=request.user).count() context = { 'profile':profile, 'number_of_likes':number_of_likes } return render(request, 'public_profile.html', context) def like_answer(request, pk): answer = get_object_or_404(Answer, pk=pk) Like.objects.get_or_create(post=answer, user=request.user) return redirect('view-Question', answer.post.slug) my models: class Answer(models.Model): user = models.ForeignKey(User, blank=False, null=False, on_delete=models.CASCADE) answer = RichTextField(blank=False, null=False) post = models.ForeignKey(Question, blank=False, null=False, on_delete=models.CASCADE) def __str__(self): return … -
Why am I getting this error when using collectstatic?
settings.py ... STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'StaticFiles') ] STATIC_ROOT = os.path.join(BASE_DIR, 'Assets/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'Assets/res') ... When I run py manage.py collectstatic. I get the following message in the terminal:- You have requested to collect staticfiles files at the destination location as specified in your settings: C:\Users\91788\OneDrive\Desktop\Projects\DebsocWebsite\staticfiles This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: no CommandError: Collecting staticfiles files cancelled. (debsoc) C:\Users\91788\OneDrive\Desktop\Projects\DebsocWebsite>py manage.py collectstatic You have requested to collect staticfiles files at the destination location as specified in your settings: C:\Users\91788\OneDrive\Desktop\Projects\DebsocWebsite\staticfiles This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: The message in the terminal just doesn't matches with my settings.py configuration of static files. What's the fix for it? -
Django Viewset ADD header to requests
I have two APIs that talk to each other. One API is on DRF, where it needs to take a one-time generated token and pass it with every request to the second API. I can find ways to add headers to the response, but I don't see anyway with a Viewset to pass a token into the header of ALL my requests. I can only find default_response_headers but default_request_headers doesn't exist. I'm also only finding how to respond with a token and take in a request with a token. To clarify, I do not need to get a request header, I need to add a request header with every request on my Django project. Django REST API ---- request w/ token ----> other system -
Python requests makes a lot of post requests, what should I do?
The project is written in Django. There is a function in views.py that should make a POST request to the API of one site. But for some reason the script does not work correctly, the update is very slow, and a ConnectionError is thrown. But the POST request is sent several times, and eventually creates several records in the database on the site. There don't seem to be any cycles. What's wrong? views.py: @login_required(login_url='login-main') def send_program_to_orchard(request, orchard_pk, pk, user_pk): services.send_program_to_orchard(orchard_pk, pk) return redirect(request.path) services.py: def make_json(program_id): program = Program.objects.get(id=program_id) program_substances = ProgramSubstance.objects.filter(program=program) response = { 'program_number': program.number, 'program_substances': [] } for each in program_substances: response['program_substances'].append({'date': each.date.isoformat(), 'substance': each.substance, 'dose': float(each.dose), 'measurement': each.measurement, 'comment': each.comment}) return json.dumps(response) def send_program_to_orchard(orchard_pk, program_pk): orchard = Orchard.objects.get(id=orchard_pk) headers = {'Authorization': f'Token {orchard.API_token}'} data = {'data': make_json(program_pk)} requests.post(orchard.program_API, headers=headers, data=data) -
logger.info() is not showing message in log file in Django project
I am learning django logging . log files are generating but I am not showing the required message i want to show in log file. here is my code the code in views.py file: ``from asyncio.log import logger from django.shortcuts import render from django.http import HttpResponse Create your views here. import logging, traceback logger = logging.getLogger('django') def home(request): logger.info('Some Message') return render(request, 'home.html')`` the code in setting is here: `` import os LOGGING ={ 'version':1, 'loggers':{ 'django':{ 'handlers':['file'], 'level':'DEBUG' } }, 'handlers':{ 'file':{ 'level':'INFO', 'class':'logging.FileHandler', 'filename':'./logs/debug3.log', 'formatter':'simple' } }, 'formatters':{ 'simple':{ 'format':'{levelname} {asctime} {module} {process:d} {thread:d} {message}', 'style':'{', } } } `` -
Postman works in form data but not in raw or on my server for that matter
So the first piece of code is the backend end point and second is the front end. It does not send the token to an email address on the server or using Postman raw data. But it does send a token using form-data. Any ideas I'm new to this. thanks class RegisterView(View): def post(self, request, *args, **kwargs): data = request.POST.get('email') check_if_email_exists = [] for email in Registration.objects.all().values_list('email', flat=True): check_if_email_exists.append(email) if data in check_if_email_exists: return JsonResponse('Email already provided', safe=False, status=200) else: new_user = Registration.objects.create(email=data) new_user.save() content = {'code': new_user.code} send_mail( "Thanks for Registering", f'Here is your signup Token:{content}', 'djangod192@gmail.com', [data], fail_silently=False, ) return JsonResponse(content, status=201) const SignUpStep1 = () => { const navigate = useNavigate(); const [email,setEmail] = useState(""); const dispatch = useDispatch(); const url = "https://motion.propulsion-learn.ch/app/api/auth/registration/"; const updateEmail = (event) => { setEmail(event.target.value); } const sendVerificationCode = (event) => { event.preventDefault(); if (email.length > 0) { const data = { email: email }; const fetchConfig = { method: 'POST', headers: new Headers({ "Content-Type": "application/json", }), body: JSON.stringify(data), }; fetch(url,fetchConfig) .then((response) => { return response.json(); }) const action = { type:"setEmail", payload:email }; dispatch(action) navigate("/SignUpStep2") }else{ alert("please enter email address"); } } -
How to save mapped values based on Foreign key (amount can vary)
I am programming a product listing tool and I need to map product attributes from my own products to for example Amazon's product attributes. Which attributes are required is defined through the product category. So I have my own Article which is mapped to the given Amazon product category and based on the category i need to create depending fields (choosable set of fields). Have a look add my models: from django.db import models from Article.models import Article class AmazonCategory(models.Model): category = models.CharField(max_length=255,unique=True) attribute = models.ManyToManyField(to='AmazonAttribute',through='AmazonCategoryToAmazonAttribute') class AmazonAttribute(models.Model): attribute = models.CharField(max_length=255) class AmazonAttributeValue(models.Model): attribute = models.ForeignKey(AmazonAttribute,on_delete=models.CASCADE) value = models.CharField(max_length=255) class AmazonCategoryToAmazonAttribute(models.Model): category = models.ForeignKey(AmazonCategory,on_delete=models.CASCADE) attribute = models.ForeignKey(AmazonAttribute,on_delete=models.CASCADE) required = models.BooleanField() class AmazonArticle(models.Model): article = models.ForeignKey(Article,on_delete=models.CASCADE) category = models.ForeignKey(AmazonCategory,on_delete=models.CASCADE) I will give a detailed example. I have a Product on my personal system called "Brush" and it is in the category "Art" which I have personally assigned. Now I created the categories and values for categories tables for Amazon (they are given AmazonCategory) already and I can map my article with the Amazon category "Toys | Toys and Babys | Toy". I have also stored the information in my database that the category "Toys | Toys and Babys | Toy" require … -
Datatables| Django, sorting, paging and searching with DRF
I have a Datatable that's working perfectly, and I wanted Server-side process to be true and not client-side. But when I enable server-side the sorting, paging and search became faulty. TestCase: https://codepen.io/TheNerdy97/pen/gOvNeeo?html-preprocessor=pug I'm using this module https://github.com/izimobil/django-rest-framework-datatables For seamless integration between Django REST framework and Datatables. I did as the doc said but it still won't work as expected. models.py from unittest.util import _MAX_LENGTH from django.db import models #from django.utils.translation import gettext as __ # Create your models here. class Fresh(models.Model): code = models.CharField(("code"), max_length=255) orbs = models.IntegerField(("orbs")) orbs_display = models.CharField(('orbs_display'), max_length=255) price = models.IntegerField(("price")) price_display = models.CharField(('price_display'), max_length=255) images = models.CharField(("images"), max_length=10000000) date = models.CharField(("date"), max_length=255) class Meta: ordering = ['code', 'orbs', 'price'] def __str__(self): return self.code views.py from django.shortcuts import render from accounts.models import Fresh, Orbs from rest_framework import viewsets from accounts.serializers import FreshSerializer from django.core import serializers # Create your views here. def index (request): return render(request, 'index.html') class FreshViewSet(viewsets.ModelViewSet): queryset = Fresh.objects.all().order_by('price') serializer_class = FreshSerializer urls.py import accounts from . import views from django.urls import path, include, re_path from rest_framework import routers from main import views from rest_framework import routers router = routers.DefaultRouter() router.register(r'fresh', views.FreshViewSet) router.register(r'orbs', views.OrbsViewSet) urlpatterns = [ path('', views.index, name='index'), path('fresh', views.fresh, name='fresh'), … -
django-picklefield changes structure after upgrade
I'm migrating a Django app from 1.11.16 to 4.0.5 and django-picklefield will be migrated also from 2.0 to 3.1 . A django object has the following line: from picklefield.fields import PickledObjectField class A(models.Model): ... log_list = PickledObjectField(default=list) . Using the old code (1.11.16) and the new code (4.0.5) results a totally different result for the query: #old Obj.objects.get(id=4737).log_list [{u'date': datetime.datetime(2022, 6, 27, 12, 54, 50, 746392), u'message': u'Fetching trademark search started', u'typ': u'info'}, {u'date': datetime.datetime(2022, 6, 27, 12, 54, 53, 423384), u'message': u'Fetching trademark search finished', u'typ': u'info'}] #type == list #new Obj.objects.get(id=4737).log_list gAJdcQEofXECKFgEAAAAZGF0ZXEDY2RhdGV0aW1lCmRhdGV0aW1.... #so it results exactly what is stored in the db. #type == str With picklefield version 3.1 is there anything else I need to do / change to have the behaviour than with version == 2.0 ? What should I do with the new setup to get the list instead of the str? -
Page not found (404) Django after deleting object
After i delete an object of my table, with a delete button, I get the an 404 Page not found error. Here is my code: views.py: def deleteAction(request, i): y = get_object_or_404(Literatur, pk=i) y.delete() return HttpResponseRedirect(reverse('literatur:index')) urls.py urlpatterns=[ path('deleteAction/<int:i>/', views.deleteAction, name="deleteAction"), ] models.py class Literatur(models.Model): name = models.CharField(max_length=100) jahr = models.IntegerField() autor = models.CharField(max_length=100) auflage = models.IntegerField(default=1) verlag = models.CharField(max_length=100) ort = models.CharField(max_length=100) isbn = models.IntegerField() def __str__(self): return f"{self.name} {self.jahr} {self.autor} {self.auflage} {self.verlag} {self.ort} {self.isbn}" -
Django Rest Framework static file blocked by CORS
Can someone help me, because I can't do anything with CORS. I have DRF server with corsheaders installed. The settings are INSTALLED_APPS = [ ... 'corsheaders', ... ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_HEADERS = ('Access-Control-Allow-Origin', 'Access-Control-Allow-Credentials', 'Authorization', 'Content-Type', 'Cache-Control', 'X-Requested-With', 'x-csrftoken') What am I trying to achieve is to get an image from server to crop it in React. So I get the name of the image in the server response, I show it on the page with no ploblem, but when I'm trying to get it like this: let img = new Image(); img.crossOrigin = 'Anonymous'; img.src = "http://127.0.0.1:8000/static/images/" + props.image.picname; setImage(img); I'm getting an error that access to the image is blocked. I've tried to run server as python manage.py runserver --nostatic and modify urls.py with those lines: if settings.DEBUG: from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns += staticfiles_urlpatterns() But it didn't help. How should I manage this since I have no request to the image, I just open it. Why showing the image on the page is ok to CORS and trying to get it by JS from the same page is such a big problem? -
django sitemap for static react routes (error : NoReverseMatch at /sitemap.xml/)
i want to implement sitemap for static react routes and I get this error: Reverse for 'contact' not found. 'contact' is not a valid view function or pattern name. I added a list of my react routes REACT-ROUTES in settings.py and append them to urlpatterns in the root urls.py file settings : INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.sitemaps', 'rest_framework', . . ] SITE_ID = 1 TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'ess')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] REACT_ROUTES = [ 'contact', 'politique-de-confidentialite', 'mentions-legales', 'cookies', . . ] STATIC_URL = '/static/' STATIC_ROOT = basepath + '/app/static' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'ess', 'static')] urls : from django.conf import settings from django.contrib.sitemaps.views import sitemap from .sitemaps import StaticViewSitemap react_routes = getattr(settings, 'REACT_ROUTES', []) sitemaps = { 'static': StaticViewSitemap } urlpatterns = [ path('sitemap.xml/', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), re_path(r'^$', TemplateView.as_view(template_name='index.html')), ] for route in react_routes: urlpatterns += [ re_path('{}'.format(route), TemplateView.as_view(template_name='index.html')) ] sitemaps.py : from django.contrib.sitemaps import Sitemap from django.urls import reverse class StaticViewSitemap(Sitemap): def items(self): return ['contact'] def location(self, item): return reverse(item) I don't know what I am missing, please help -
Im trying to implement a delete button using django and vue js
Im trying to implement a delete button using django and vue js but im running into an error 500 and i cant seem to understand why ? i know it means my call isn't working go from here <button class="button is-success" @click="deleteTest()"> Yes, Delete</button> to here deleteTest() { axios.post('/app/api/testzone_delete/' + this.TestCategory_id + '/') .then((response) => { console.log(response) this.showDialog = false }) .catch((function (error) { console.log(error ) })) } } }) </script> then like its django it goes through url.py path('api/testzone_delete/<int:individualtestzone_id>/', api_delete_test, name='api_delete_test'), and finally in the api.py from django.http import JsonResponse from django.views.decorators.csrf import csrf_exempt from .models import TestCategory from django.contrib import messages @csrf_exempt def api_delete_test(request, individualtestzones_id): individualtestzone = request.user.TestCategories.all().get(pk=individualtestzones_id) individualtestzone.delete() return JsonResponse({'success': True}) im pretty new to django and can't seem to see why it does not work -
DRF Model Permission denying access to authenticated user
I'm getting a permission denial error but, if I'm understanding things correctly, the permissions should already have been assigned. class UserList(generics.ListCreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [DjangoModelPermissions] class UserDetail(generics.RetrieveUpdateDestroyAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [DjangoModelPermissions] I've tried some different permission classes so far, but except for just bypassing it entirely with AllowAny nothing seems to have worked. -
Choose Front-end and Backend for multipurpose website( Social Network + ecommerce (like facebook has Market)
I have been reviewing the suggestion of using Django for backend(api) and using Reactjs for front-end. These can help the platform run smoothly, fast and secured.However, I would like to know your suggestion of choosing technologies for building that platform (social network and ecommerce at same domain) -
How do i become a forex web application developer [closed]
i am web developer with intermediate knowledge in Python, Django , javascript, Html and css. i will like to start building web applications for forex trading but i dont't have any idea on how to start and i haven't seen any tutorials on it. Any idea will be appreciated thanks. -
Not able to apply redis lock on celery workers
I am trying to replace django memcache’ to redis lock and getting Connection reset error` -
How to filter comparing two informations from the same Django model
I have a MedicalCertificate model like this: class MedicalCertificate(models.Model): needs_leave = models.BooleanField() date = models.DatetimeField() days_off = models.IntegerField() And I need to filter the active medical certificates, which are: date + days_off >= datetime.now() I tried to use F(), but not success. Ex.: from django.db.models import F certificates = { 'needs_leave': True, 'days_off__gte': datetime.datetime.now() - F('externalsystemmedicalcertificates__date') } queryset = MedicalCertificate.objects.filter(**certificates) Any idea how to proceed? -
Python3 import error smart_unicode django
This is my first time ever trying to run a py script I have a script to auto import to android studio some translations. I installed python 3.10.5 and pip and trying to run a script. I have this import from django.utils.encoding import smart_str, smart_unicode When i try to run it, I get the error ImportError: cannot import name 'smart_unicode' from 'django.utils.encoding' (C:\Users\a816353\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\encoding.py) I have tried some suggestions but I cant figure out what to do. -
How to perfom CRUD Operation in Flutter & Postgres
I want to perfom CRUD Operation Postgres but with a flutter app, so that my Django app can share data with Flutter. -
Python Django convert timestamp from UTC to local timezone
Im am working with Django + DRF, to develop a REST API. I have configured the django settings to work with the timezone support on: USE_I18N = True USE_L10N = True USE_TZ = True As previously mentioned, my database is receiving and storing data in UTC. My problem is that for some users (each user has their configuration) I must return responses in their time zone (usually in UTC-3 or UTC-2). I was reading several posts and tried several combinations of: astimezone and normalize without succes. I attach my attempts: timezone_arg = pytz.timezone('America/Buenos_Aires') print(ts_a, ts_b) ts_a = ts_a.astimezone(timezone_arg) ts_b = ts_b.astimezone(timezone_arg) print(ts_a, ts_b) utc = pytz.timezone('UTC') ts_a = timezone_arg.normalize(ts_a.astimezone(utc)) ts_b = timezone_arg.normalize(ts_b.astimezone(utc)) print(ts_a, ts_b) I am getting the following: 2022-06-17 05:39:09 2022-06-17 05:46:49 2022-06-17 05:39:09-03:00 2022-06-17 05:46:49-03:00 2022-06-17 05:39:09-03:00 2022-06-17 05:46:49-03:00 I understand that django is interpreting that what I am telling it is that the timestamps are already in UTC-3... and it is normalizing them to UTC. But what I want is to cast from UTC to UTC-3. My input/output should be: 2022-06-17 05:39:09 2022-06-17 05:46:49 2022-06-17 02:39:09 2022-06-17 02:46:49 Since I don't only work with the time zone of Argentina (UTC-3), I can't compute a timedelta of 3 …