Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Try to create a database with python Django and use it with React! Db does not display on my react wep app
I tried to use React and Python for creating a web app. I used Python and Django to create a DB which do not appear on my React website. All of this was made on a local server. To verify that my code work, I simultaneously start localhost 3000 and localhost 127.0.0.1.8000. I verify all the files and could not see the problem. In my console appear only this error: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0. GitHub repository-https://github.com/margelatufml/Problem-React-Python -
Invalid connection string attribute in Django
DATABASES = { "default": { "ENGINE": "mssql", "NAME": " DJANGOOSQL", "USER": "sa", "PASSWORD": "Daytek00", "HOST": "LAPTOP-KBFP4DGE", "PORT": "", "OPTIONS": {"driver": "ODBC Driver 11 for SQL Server", }, }, } -
WARNING: No metadata found in ./venv/lib/python3.9/site-packages on PyCharm
Let's point out I have I have not added any environment variables or touched the python paths. The environment variables, I used where added beforehand from another heroku branch. I was adding AWS_Software in the Project.settings, along with other software recommended by Django guide for heroku. when it needed to import storages when I ran pip freeze > requirements.txt this pops up: WARNING: No metadata found in ./venv/lib/python3.9/site-packages WARNING: No metadata found in ./venv/lib/python3.9/site-packages WARNING: No metadata found in ./venv/lib/python3.9/site-packages WARNING: No metadata found in ./venv/lib/python3.9/site-packages Never ever had this issue until now, committing too github and pushing to heroku has no problems. I don't want to mess around with the python files. I tried updating Pip and Django in the Python interpreter. Not luck with Django when getting to install on requirements.txt(below) asgiref==3.4.1 boto3==1.18.5 botocore==1.21.5 certifi==2021.5.30 charset-normalizer==2.0.3 click==8.0.1 dj-database-url==0.5.0 Django==3.2.5 django-admin-honeypot==1.1.0 django-heroku==0.3.1 django-storages==1.11.1 gunicorn==20.1.0 idna==3.2 Pillow==8.3.0 psycopg2==2.9.1 pytz==2021.1 requests==2.26.0 sqlparse==0.4.1 urllib3==1.26.6 whitenoise==5.3.0 Any possible solutions? -
How do I set a default user for blog posts in Django?
My Blog model has a User field like following: from django.contrib.auth.models import User class Blog: author = models.ForeignKey(User, on_delete = models.CASCADE, related_name='blog', default=User('monty')) This works as in I can see 'monty' set as a default user in the admin interface when I create a blog post. However, when I make migrations, I get the following error: ValueError: Cannot serialize: <User: > There are some values Django cannot serialize into migration files. I also tried this: default=User.objects.filter(username='monty')) and that returns a slightly different error when I make migrations: ValueError: Cannot serialize: <User: monty> There are some values Django cannot serialize into migration files. Anyone know how do I get past this error? -
POST and GET Method in Django api including Django ManyToManyField
I have a model that includes the ManyToManyField field and I have to use this model in Django API (POST(Saving Data) and GET Method) Here is my code: models.py class medDetails(models.Model): name=models.CharField(max_length=1000) notes=models.CharField(max_length=1400) duration=models.CharField(max_length=100) serve=models.CharField(max_length=100) Where I am calling medDetails model as a ManyToManyField medicine = models.ManyToManyField(medDetails) serializers.py class ReportsSerializer(serializers.ModelSerializer): class Meta: model = report fields = ('id','user', 'patient','medicine','description', 'created', 'time') class medDetailsSerializer(serializers.ModelSerializer): class Meta: model = report fields = ('id','name', 'notes', 'duration', 'serve') views.py create = report.objects.create(user=user, patient=patient,medicine=request.data['medicine'],description=des,created=datetime.date.today(), time=str(datetime.datetime.now().hour) +':'+ str(datetime.datetime.now().minute)) Error Coming: Direct assignment to the forward side of a many-to-many set is prohibited. Use medicine.set() instead. -
Django runserver isn't updating after .py file changes
I am learning django and using manage.py runserver for a live server. When I make changes to html and css files in my project, I only have to refresh the web page to see the changes, but when I make changes to the .py files (views.py or urls.py for example) I have to stop and restart the live server manually before refreshing the web page to see the changes. Is there a setting that I can change to avoid this manual reset? I am using visual studio code in windows and the actual command I'm using is: python manage.py runserver -
Celery task doesn't save model
I have post_save signal, that holds task.delay(). Task contains some code, that ends with saving model. I handled recursion and I know, that task is succeeded. The problem is, in my task I change one field of a model, in logs of task I see correct info, but when I go to db or in Django admin, field contains info like "before celery task". So the question is, what's wrong. If need, can provide code. Code throws no exceptions. -
How to add custom select input options in a form in Webflow
I'm trying to create a table as a select input field in Webflow as the following: but I couldn't find any option to do that in Webflow, the options are showing like that: So is there a way to do it or should I use Django or React libraries to do it later in the implementation? -
Django test MEDIA return 404 whereas browser return 200
I'm trying to check default media file availability with django test but it's appear that is not working. By referring to this post my code bellow : @override_settings(DEBUG=True) class Test_ProfileMedia(TestCase) : def setUp(self) : self.client = Client(HTTP_HOST = '127.0.0.1:8000') self.password = F.password() self.profile = ActiveProfile(password = self.password) self.user = self.profile.account self.client.login( username = self.user.username, password = self.password ) print("") print("MEDIA_URL: " + settings.MEDIA_URL) print("MEDIA_ROOT: " + settings.MEDIA_ROOT) def test_profile_home_default_image_GET(self) : response = self.client.get(self.profile.image.url) self.assertEquals(response.status_code, 200) Test Result : test_profile_home_default_image_GET (core.tests.test_media.Test_ProfileMedia) ... MEDIA_URL: /media/ MEDIA_ROOT: /mnt/c/Users/CallMarl/Wsl/dev/website/application/media Not Found: /media/default/default_profile.png FAIL By standard client : curl http://127.0.0.1:8000/media/default/default_profile.png --output download % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 135k 100 135k 0 0 12.0M 0 --:--:-- --:--:-- --:--:-- 12.0M If anyone can help me understand my mistake. -
Creating a monthly table with a fix first column
I’m new to Django, Did a couple of tutorials (Django official documentation and Tango with Django), but a can’t find a solution to my problem. I want to create a table (Canvas) that: • Is created monthly. • Has a fix first column. • Allow the frontend users to create these monthly tables and add, edit and delete the data. Here is an example of the table: enter image description here I just need some guidance as where to start in term of: • How my database table should look like • How to create table forms PS: Sorry for the English, I’m Algerian. -
Different OpenCV augmentation output in local webcam and web app webcam
I'm trying to apply this image augmentation project in a web app. I tried this locally in my laptop and it worked well, but when I load it on my web app it failed to output the same result. I tried to print out the outputs in my terminal and it seems like it's working fine. class VideoTest(object): def __init__(self): self.cap = cv2.VideoCapture(0) self.cards = Card.objects.get(id=2) self.target_image = cv2.imread(self.cards.card_image.path) self.video = cv2.VideoCapture(self.cards.card_video.path) def __del__(self): self.cap.release() def get_frame(self): success, webcam_input_image = self.cap.read() success, video_image = self.video.read() hi, wi, ci = self.target_image.shape video_image = cv2.resize(video_image, (wi, hi)) detection = False frame_counter = 0 orb = cv2.ORB_create(nfeatures=1000) kp1, des1 = orb.detectAndCompute(self.target_image, None) target_image = cv2.drawKeypoints(self.target_image, kp1, None) augment_image = webcam_input_image.copy() kp2, des2 = orb.detectAndCompute(webcam_input_image, None) webcam_image = cv2.drawKeypoints(webcam_input_image, kp2, None) if detection == False: self.video.set(cv2.CAP_PROP_POS_FRAMES, 0) frame_counter = 0 else: if frame_counter == self.video.get(cv2.CAP_PROP_FRAME_COUNT): self.video.set(cv2.CAP_PROP_POS_FRAMES, 0) frame_counter = 0 success, video_image = self.video.read() video_image = cv2.resize(video_image, (wi, hi)) bf = cv2.BFMatcher() matches = bf.knnMatch(des1, des2, k=2) good = [] for m, n in matches: if m.distance < 0.75*n.distance: good.append(m) img_features = cv2.drawMatches(target_image, kp1, webcam_image, kp2, good, None, flags=2) print('len good', len(good)) if len(good) > 30: detection = True src_points = np.float32([kp1[m.queryIdx].pt for m … -
No module named 'rest_framework_simplejwt'
I am trying to connect rest_framework_simplejwt, i am using official documentation but i have error: No module named 'rest_framework_simplejwt' I am using django 3.1. I installed all need modules If i am starting my programm by command: "docker-compose run server poetry add djangorestframework-simplejwt" all working, but how can i start without this? I need to use "fab dev" settings.py only need: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework_simplejwt.authentication.JWTAuthentication', ), } installed_apps.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'rest_framework', 'rest_framework_simplejwt', ] LOCAL_APPS = [ ] INSTALLED_APPS += LOCAL_APPS LOCAL_MIGRATIONS = [app_path.split('.')[1] for app_path in LOCAL_APPS] MIGRATION_PATH = 'config.migrations.' MIGRATION_MODULES = {app_name: MIGRATION_PATH + app_name for app_name in LOCAL_MIGRATIONS} urls.py from django.conf import settings from django.contrib import admin from django.urls import include, path from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, ) urlpatterns = [ path('admin/', admin.site.urls), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] if settings.DEBUG: import debug_toolbar from django.conf.urls.static import static urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += [ path('__debug__/', include(debug_toolbar.urls)), ] -
Django Form does not Render in web page
I am trying to create a post edit page in Django, but when I test it the form does not render, only the submit button. There are no input fields displayed on the page. There are no errors given when I run the server or load the page. Here is my code: View: @login_required def updateview(request, pk): if request.method == "POST": instance = get_object_or_404(Listing, tag=pk) updateform = ListingUpdateForm(request.POST, instance=instance) if updateform.is_valid(): updateform.save() listing = updateform.instance messages.success(request, "New Listing Created") return redirect(reverse('main:listingdetails', kwargs={'pk': listing.tag})) else: messages.error(request, 'Please correct the error below.') updateform = ListingUpdateForm return render(request, "main/createlisting.html", context={"updateform":updateform}) Template: {% block content %} <form enctype="multipart/form-data" method="post"> {% csrf_token %} {{updateform}} <button type="submit">post</button> </form> {% endblock %} Form: class ListingUpdateForm(forms.ModelForm): countryList = (("US", "United States"), ("UK", "United Kingdom")) country = forms.ChoiceField(choices=countryList) class Meta: model = Listing fields = ('title', 'description', 'price', 'country') Thanks for any help. -
after implementing channel in django different requests are mixing up response with each other( windows OS )
i have implemented channel for sockets implementaion but now the requests are mixing up their responses with each other. and i dont know why this is happening. for example if i have two ajax requests that runs asynchronous than the response of first ajax request is received by second ajax request and the first one returns error as its response was taken by the second one. for example (first ajax request): function Weeks(){ $.ajax({ url:'/en/logistics/changeWeek/08-02-2021/Api', method:'GET', // async: false, success: function(result){ console.log(data) activeDate = new Date((result.seconds)*1000) dateNumber = activeDate.getDay() week_start = activeDate.addDays(-dateNumber) week_end = activeDate.addDays(6-dateNumber) depolyedDates = result.deployedDates depolyedDates = depolyedDates.map(element => new Date((element)*1000).getTime()/1000) readyDates = result.readyDates readyDates = readyDates.map(element => new Date((element)*1000).getTime()/1000) today = new Date((result.today)*1000) console.log(today) create_week() } }) } (second ajax request) function getDrivers(params,page){ $.ajax({ url:"/en/logistics/drivers/Api/resfresh"+ "?params=" + encodeURI(JSON.stringify(params)), // async: false, method:"GET", success: function(data){ console.log(data) drivers = data.drivers driverCurrentPage = page driverLastPage = data['last_page'] if (!driverActive && drivers.length > 0){ activeDriverTab(drivers[0].id ) } createDriverDiv() }, error:function(e){ console.log(e) } }) } when these requests are made this is what i get: and it is received by this response should have been received by the weeks ajax request instead it was send to drivers one if you can … -
Django many foreign table queries despite `select_related`
I'm trying to join A parent and 2 child tables in django. I can see that each time a list view is run, there are 50 queries (the page size) executed on the ChildB table. I thought that I could improve performance using the select_related method, but it seems not to be taken into account. Using prefetch_related the behaviour is as expected. Why is select_related not taken into account? select_related for Django 2.2 (which I'm using) prefetch_related Models: class Parent(models.Model): id = models.AutoField(primary_key=True) uuid_a = models.ForeignKey(ChildA, db_column='uuid_a', db_index=True, default=None, editable=False, null=True, on_delete=models.DO_NOTHING, primary_key=False, related_name='result_suppliers', unique=True,) uuid_b = models.ForeignKey(ChildB, db_column='uuid_b', db_index=True, default=None, editable=False, null=True, on_delete=models.DO_NOTHING, primary_key=False, related_name='duns_suppliers', unique=True,) class ChildA(models.Model): # ss uuid = models.CharField(primary_key=True, editable=False, max_length=36, db_index=True) class ChildB(models.Model): # sd id = models.AutoField(primary_key=True, editable=False) Serializers: class ChildAListSerializer(serializers.ModelSerializer): class Meta: model = ChildA fields = ['uuid', ] # others class ChildAListSerializer(serializers.ModelSerializer): class Meta: model = ChildB fields = ['uuid', ] # others class ParentListSerializer(serializers.Serializer): uuid_a = ChildAListSerializer() uuid_b = ChildBListSerializer() last_sync = serializers.DateTimeField() # others class Meta: model = Parent fields = '__all__' view: class ParentListView(ListAPIView): """ List view for deduplication suppliers screen """ filter_backends = [filters.DjangoFilterBackend] filterset_class = DeduplicationParentFilter pagination_class = LimitOffsetPagination page_size = 30 max_page_size = 30 pk_field … -
ERROR: No module named 'encodings' when deploying django using wsgi on amazon linux 2
For the past few days, I have been referring to Stackoverflow to solve my problem. Im hosting Django application using WSGI on Amazon Linux 2. I'm using pyenv for multiple python versions here. And the python version is 3.7.10. Below is my Apache Conf and wsgi.py. WSGI config for mysite project. It exposes the WSGI callable as a module-level variable named application. For more information on this file, see https://docs.djangoproject.com/en/3.2/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_wsgi_application() <VirtualHost *:80> ServerName wsgi.iamvishnu.xyz #DocumentRoot /var/www/html #for django LoadModule wsgi_module modules/mod_wsgi_python3.so Alias /static/ /home/mod-wsgi/mysite/static/ <Directory /home/mod-wsgi/mysite> Require all granted <Directory /home/mod-wsgi/mysite/mysite> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess mysite user=mod-wsgi group=mod-wsgi python-home=/home/mod-wsgi/mysite:/home/mod-wsgi/.pyenv/versions/virtualenv/bin/python WSGIProcessGroup mysite WSGIScriptAlias / /home/mod-wsgi/mysite/mysite/wsgi.py Below is the error im getting from apache error log Current thread 0x00007fd4b2087240 (most recent call first): [Tue Aug 03 05:27:15.145298 2021] [core:notice] [pid 24159] AH00052: child pid 24229 exit signal Aborted (6) Fatal Python error: initfsencoding: unable to load the file system codec ModuleNotFoundError: No module named 'encodings' Current thread 0x00007fd4b2087240 (most recent call first): [Tue Aug 03 05:27:16.147167 2021] [core:notice] [pid 24159] AH00052: child pid 24230 exit signal Aborted (6) Fatal Python error: initfsencoding: unable to load the … -
Django runserver shows no output
Why would python manage.py runserver 8765 run properly such that I can visit the site at localhost:8765 and it renders everything correctly but I see no activity being registered on the server itself? My runserver session is stuck as follows: (qux) (main *%) python manage.py runserver 8765 Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). August 03, 2021 - 08:51:23 Django version 3.2, using settings 'qux.settings.dev' Starting development server at http://127.0.0.1:87650/ Quit the server with CONTROL-C. It prints nothing further like [03/Aug/2021 19:26:59] "GET / HTTP/1.1" 200 32663 NO output. NOTHING. I tried changing verbosity. No effect. I can find no reference to something like this either. When does this happen, and why? How does one resolve this? -
django template conditional extend
I have a very specific issue. I'm using a maintenance mode to get a built-in 503 view. I can customize the template in any way I want. I got it working, however I want the template to extend the admin base template when the request.path is /admin. When it isn't it should extend the normal base template. I tried it with this: {% if '/beheerpaneel' in request.path %} {% extends "admin/index.html" %} {% else %} {% extends "base.html" %} {% endif %} but that gives me a template syntax error, because the extend tag must be first. After some googling it seems I need to handle this in the view.. but there is no view, its built-in. Anyone know a way around this? In the future I also wanna do this with the 404 and 500 pages etc. -
How to get the logged-in user from other view function?
I am using django-rest-knox with token authentication, and an abstract user model. In the project, I have a class based view to create (POST)some model instances and I need to know who is the logged-in user so I can assign it to the model instance customer field. -
Auth0 login from Django gives cant reach this page error?
I am using Auth0 as an authentication service provider in my Django Application, everything seems to work fine until I press the login button it takes me to the link:- https://none/authorize?client_id=None&redirect_uri=http%3A%2F%2F127.0.0.1%3A8000%2Fcomplete%2Fauth0%2F%3Fredirect_state%3Dq0DAeE22cHQ9pahVC0uZF6AyMDdbI7l9&state=q0DAeE22cHQ9pahVC0uZF6AyMDdbI7l9&response_type=code on this link I get the following error:- enter image description here I am not sure what is causing this error. Here is some mre information :- Browser = Microsoft Edge and Google Chrome OS = Windows 11 Pro 2021 Python = v3.9.6 Django = v3.2.6 I hope I have provided sufficient information. -
How to get/refer a user id in Django dynamically?
I have a questionnaire page that works fine. I like to get a feedback to a page about which the user has filled out the questionnaires. I can make it manually if I add the user_name_id but I don't know how to get it dynamically. views.py @user_passes_test(lambda u: u.is_superuser) def index(request): viselkedestipus = Viselkedestipus.objects.all() //this generats me the list of the users stressz_teszt = Stressz_teszt.objects.filter(user_name_id=???) //this is where I need a solution template = loader.get_template('stressz/index.html') context = { 'viselkedestipus': viselkedestipus, 'stressz_teszt': stressz_teszt, } return HttpResponse(template.render(context, request)) html {% for item in viselkedestipus %} <div class="card my-2"> <div class="card-header h3"> {{ item.user_name }} </div> <div class="card-body"> <h5 class="card-title"></h5> <div class="row"> <div class="col-md-6"> <p class="card-header">User: {{ item.user_name }}</p> <p class="card-header">Kitöltés dátuma: {{ item.date }}</p> <p class="card-header">User id: {{ item.user_name_id }} </p> </div> <div class="col-md-6"> <h5>Tesztek:</h5> Viselkedéstípus: {% if item.vis01a %} <i class="fas fa-check fa-2x text-success"></i> {% else %} <i class="far fa-bell fa-lg text-warning"></i> {% endif %} {% for i in stressz_teszt %} //this is where I need the data of the specific user but I always get the datae of the logged in user Stressz-szint: {% if i.stressz_v01 %} <i class="fas fa-check fa-2x text-success"></i> {% else %} <i class="far fa-bell fa-lg text-warning"></i> … -
Django + Okta + django_saml2_auth Forbidden (CSRF cookie not set.) 403
Created a saml application in Okta for local testing. Django side I'm using plugin django_saml2_auth (https://github.com/fangli/django-saml2-auth) to authenticate with Okta. When I open the application from Okta app, Django throws below error; Forbidden (CSRF cookie not set.): / [03/Aug/2021 12:45:23] "POST / HTTP/1.1" 403 2870 Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for “same-origin” requests. Actually home page ('/') doesn't have any forms for csrf verification, but okta tries POST on '/' and that fails at csrf. Followed this link https://github.com/fangli/django-saml2-auth/issues/30#issuecomment-438056798 and added "requestable urls" in okta but issue remains same. Okta configuration GENERAL Single Sign On URL http://127.0.0.1:8000/ Requestable SSO URLs URL Index http://127.0.0.1:8000/ 0 http://127.0.0.1:8000/saml2_auth/acs/ 1 http://127.0.0.1:8000/accounts/login/ 2 Recipient URL http://127.0.0.1:8000/ Destination URL http://127.0.0.1:8000/ Audience Restriction http://127.0.0.1:8000/saml2_auth/acs/ Am I missing anything? Is there any other saml plugin I can use for django + Okta integration? -
Using RotatingFileHandler and TimedRotatingFileHandler simeltaneously in Django
I've a scenario in Django where I need to rotate log files on daily basis but also to rotate the log file if the file crosses a particular size limit. It seems that I cannot use RotatingFileHandler and TimedRotatingFileHandler simultaneously. Can anybody please help me with a solution? -
Call a shared task in Django project from another project
Let's say I have a Django project A. It has an app B. B has a shared task in tasks.py called C. I have another non-django project from which I want to trigger this shared task C. They both use common broker RabbitMQ. From the documentation and other sources all I am able to find is send_task which I am not able to get to work. A.B.tasks.C @shared_task(queue="queue_name", autoretry_for=(Exception,), default_retry_delay=30, max_retries=3) def C(**kwargs): print(kwargs) Calling through: celery_app.send_task('A.B.tasks.C', kwargs={'message': 'message'}, queue='queue_name') The task is received by project A but not processed. [2021-08-03 12:19:20,189: WARNING/MainProcess] Received and deleted unknown message. Wrong destination?!? The full contents of the message body was: body: [[], {u'message': u'message'}, {u'chord': None, u'callbacks': None, u'errbacks': None, u'chain': None}] (100b) {content_type:u'application/json' content_encoding:u'utf-8' I think send_task is supposed to work for named tasks only. So, how do I achieve this for shared tasks? -
Django AllAuth - how to get SocialApp object by SocialAccount?
Is it possible to query a corresponding SocialApp from SocialAccount instance? Or to get all SocialAccounts of a particular SocialApp ? I was thinking about doing this: SocialApp.objects.get(provider=social_account.provider) But I think it can return multiple SocialApp objects. Is there a way to get the corresponding SocialApp ?