Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix Django Summernote using relative path for src url in image integration?
I am new to the Django framework, and inherited a projet which I am trying to fix. Right now my project runs in a docker at url localhost:8000 until deployment in on a remote server. I have the django-summernote extension installed for fancy text editing and image integration, but it doesn't work as expected: Summernote Editor in Django admin works fine, and correctly displays uploaded images But on my content pages, the html integration of my provides an incorrect src url (which return an error ofc) src="/media/django-summernote/2022-02-27/90a1f1ec-ed16-4cc2-a9f8-b0bb30ea4ab8.png" The expected html integration should be : src="http://localhost:8000/media/django-summernote/2022-02-27/90a1f1ec-ed16-4cc2-a9f8-b0bb30ea4ab8.png" I checked and the image file does exist in the folder, the expected url below does actually shows the picture alright as well. The rest of the website uses images integration just fine when not related to summernote. I figure this has something to do with settings.py or even router (which tbh is still a bit complex in my head). settings.py MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') urls.py urlpatterns = [ ... path("summernote/", include("django_summernote.urls")), ] -
Is there a way to put JSON data to django models?
So what I want to do here is that take a CSV file as input from an HTML form, then convert the CSV to JSON and put the JSON values into a Django model. Is there a way to do this? Any help would be appreciated. Thank you in advance! -
Default permissions for files that are automatically created in a Linux directory
I have a problem with an application developed in python using the django framework, it uses the FPDF library to export a file which is then used by the application to attach it to an automated email. When this app exports the PDF and saves it to the media directory, the file doesn't inherit permissions from its parent directory and only has read/write permissions, this doesn't allow Django to find the file so it can be attached to the mail. I was searching on the internet and found people with the same problem, they were recommended to use the ACL configuration to manage default permissions, I tried many times with different methods but it did not work. I don't know what I could have done wrong (I kept having the same error). Dfter having made the ACL configuration the files continued to be exported with the same permissions and when applying the command chmod 777 -R * these did not change their permissions, I had to disable the ACL configuration for it to allow me to apply that command. This is the error that appears: Internal Server Error: /treasury/sendMailsSupplierView/SBOJOZF Traceback (most recent call last): File "/var/www/johannasenvironment/venvjoh/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner … -
python Django returing <WSGIRequest: GET'> instead of data
I some have trouble representing API data to my templates. Some info: The API data is send to context_processors.py in my app dir. from ttn.context_processors import my_function while True: my_function(SomeClass().return_data()) time.sleep(5) and here is my context_processors funtion: def my_function(complex_data): all_data = complex_data return {'data': all_data} complex_data looks like: {0:{}, 1{}} etc.. Here is where I want to represent the data in my base.html: <div class="div-side"> {% if data %} <p>{{data}}</p> # this one return wsgirequest: get /myapp/ <ul> {% for dicts in data %} <li>dicts</li> # just for test {% for d in dicts %} <li>{{ d.name }} <span>{{d.someDigit|floatformat:'2'}}</span> <span>{{d.somePercent|floatformat:'2' }} %</span> </li> {% endfor %} </ul> {% endfor %} {%else%} <p>no info</p> {%endif%} </div> My views which render to base.html: def home_page(request): a = len(get_news_objects()) return render(request, 'base.html', {'a': a} ) Basically I'm not able to represent my data at my .html page because context_processors.py, returns this "wsgirequest: get /myapp/". What am I missing? How can I send the data instead of wsgirequest: get /myapp/ ? From my settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', 'project.context_processors.my_function', # ], }, }, ] -
nuxtjs auth not calling server after successful login
I'm trying to set up social logins with nuxt and django, as far as I understand it works like this: user clicks on "login with google" google returns a code nuxt calls a view on my server and sends that code the server sends the code to google which responds with the user info my server registers the user (or logs him in), generates a token and sends it back to nuxt nuxt authenticates the user I can see the google login page properly, I can click on my account, but then my local nuxt page refreshes and I don't see any request being made to my server. Is my understanding of the flow wrong? Here's my setup in nuxt: google: { clientId: '<secret_key>', codeChallengeMethod: '', responseType: 'code', redirectUri: 'http://localhost:3000/', endpoints: { token: 'social-login/google/', // some backend url to resolve your auth with google and give you the token back userInfo: 'user-info/' // the endpoint to get the user info after you received the token }, } And I'm trying to login with: this.$auth.loginWith('google') EDIT: if it helps, I'm trying to follow this guide: https://medium.com/swlh/how-to-build-google-social-login-in-django-rest-framework-and-nuxt-auth-and-refresh-its-jwt-token-752601d7a6f3 -
Is there any way to get back to a page from which it was redirected to in django?
Detailed Explanation: Suppose there is an html page in django named as Page 1 and the other one as Page 2 which is a login page. Now there is a button on both of these pages. The button on Page 1 redirects to the page for login. Is there any way to get back to that page from where this page i.e. Page 2 is redirected from? Please Note: The login page i.e. the Page 2 is simply redirected to a Account.html page, I want to set a condition so that it will redirect back to previous page, i.e., from where the Page 2 was redirected from. -
table diagnostic_patient has no column named test_id
I tried to post multiple instance in one post request.But got this error table diagnostic_patient has no column named test_id.From selected key the id will save into test_id column and name will be save in test_name column. models.py class Test(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=6, decimal_places=0) def __str__(self): return self.name class Patient(models.Model): name = models.CharField(max_length=100) email = models.EmailField(max_length = 254) age = models.DecimalField(max_digits=6, decimal_places=0) gender = models.CharField(max_length=100) phone = models.DecimalField(max_digits=6, decimal_places=0) test_id = models.IntegerField() test_name = models.CharField(max_length=100) t = models.ForeignKey(Test, on_delete=models.CASCADE, related_name='selected') total_price = models.DecimalField(max_digits=6, decimal_places=0) advance = models.DecimalField(max_digits=6, decimal_places=0) due = models.DecimalField(max_digits=6, decimal_places=0) role = models.CharField(max_length=100,default='Patient') serializers.py class TestSerializer(serializers.ModelSerializer): class Meta: model = Test fields = ['id', 'name','price'] class PatientSerializer(serializers.ModelSerializer): selected = TestSerializer(many=True) class Meta: model = Patient fields = ['name', 'email', 'age', 'gender', 'phone', 'selected', 'total_price', 'advance', 'due', 'role'] def create(self, validated_data): tracks_data = validated_data.pop('selected') a = Patient.objects.create(**validated_data) for track_data in tracks_data: Patient.objects.create(**track_data) return a json post data: { "name":"df", "email":"d@gmail.com", "age":"21", "gender":"Male", "phone":"234", "total_price":86, "advance":0, "due":86, "selected":[ {"id":8,"name":"sdf","price":34}, {"id":9,"name":"dg","price":52} ] } -
Remove HTML tags in Django messages
Basically I have a view with Django where I add some messages like this: from django.contrib import messages def myView(request): #some stuff messages.error(request, "My message here") return render(request, "myApp/myTemplate.html", context = data) And then I print them in the template like this: {% if messages %} {% for message in messages %} <div>{{ message }}</div> {% endfor %} {% endif %} But the problem is that the messages framework is adding HTML tags to the message and when the message is printed, the <ul> and <li> tags are added. So after the template is rendered it looks like this: <div><ul class="errorlist"><li>My message here</li></ul></div> I would like to know if there is a way to avoid the message getting these html tags added. Also, I would need it outside of the template too, so in the unit tests I can do something similar to: messages = list(response.context["messages"]) self.assertEquals(len(messages), 1) self.assertEquals(str(messages[0]), 'My message here') Is there any way to achieve this? Currently using Python3 and Django 4 Note that I would like to completely avoid the framework to add the tags, so I do not need to use striptags filter. -
Django Can't access URL Pk from FormView Class
I am putting together a simple medical-related project that includes allowing user to order lab tests on a patient. From the patient screen they select Order Tests. The UrlPattern, which includes the Patient pk, brings up the OrderTestsView which is a FormView. The kwargs in this view have no pk even though it is in the Url. I use a FormView because I need to access the list of tests selected in the Forms MultipleModelsChoice. But I need the patient information before the Order form is selected because I have to display who the patient is at the top of the order screen. Normally I would use get_context_data to do all of this, but the kwargs are blank. Not sure why FormView ignores the pk parameter, but how do I fix this? urls.py path('order-tests/<pk>/', OrderTestsView.as_view(), name='order-tests'), forms.py class TestOrderForm(forms.Form): choice = forms.ModelMultipleChoiceField(Universal_Test_File.objects.all().order_by('test_name'), to_field_name="service_id") view.py class OrderTestsView(FormView): model = Universal_Test_File form_class = TestOrderForm success_url = '/list_tests/' template_name = "lab/order_tests.html" patient = get_object_or_404(Patient, pk) ***## CANNOT ACCESS PK*** def form_valid(self, form): choice = form.cleaned_data.get("choice") if choice: for test in choice: print(test.service_id, test.test_name) -
MultiValueDictKeyError at /authors/postform/
i have bulit a books management app in django-rest framework with UI in html css and bootstrap. But when i'm trying to add new authors to the database doing a post request i'm getting this multivalue dict error even though i checked the name in the form. traceback Environment: Request Method: POST Request URL: http://127.0.0.1:8000/authors/postform/ Django Version: 3.2.9 Python Version: 3.9.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'genebox', '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 "C:\Python39\lib\site-packages\django\utils\datastructures.py", line 76, in __getitem__ list_ = super().__getitem__(key) During handling of the above exception ('Name'), another exception occurred: File "C:\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Online Test\GeneBOX full stack (27th)\myproject\genebox\views.py", line 58, in author_save name = request.POST['Name'] File "C:\Python39\lib\site-packages\django\utils\datastructures.py", line 78, in __getitem__ raise MultiValueDictKeyError(key) Exception Type: MultiValueDictKeyError at /authors/postform/ Exception Value: 'Name' ```urls.py``` urlpatterns = [ path('', views.home, name='home'), path('authors/', views.Author_list, name='all_author'), path('authors/postform/', views.author_save, name='authsave'), path('books/', views.Book_list, name='all_books'), path('authorcsv/', views.author_csv, name='author_csv'), path('bookcsv/', views.book_csv, name='book_csv') ] models.py class Authors(models.Model): Gender_choice = ( ('M', 'Male'), ('F', 'Female'), ('Other', 'Others'), ) Name = models.CharField(max_length=70) Age = models.IntegerField() Gender = models.CharField(max_length=20, choices=Gender_choice) Country … -
getting AttributeError 'str' object has no attribute 'data' when makinh request to Django-based Server from Flutter application
Hello fellow developers! I am trying to make a request to my Django-based server. lets first look at the endpoints that are causing trouble url.py path("getBookings/<str:Role>/<str:id>/", views.getBookings), path("archiveBooking/<str:Role>/<str:id>/", views.archiveBooking), these endpoints work fine when I make a request to them via localhost i.e. when I run the server with python manage.py runserver they also work fine when I try to make a request via my heroku-deployed application. But when I try to make a request via flutter, the following error shows up, I/flutter (10506): Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python39.zip', '/app/.heroku/python/lib/python3.9', '/app/.heroku/python/lib/python3.9/lib-dynload', '/app/.heroku/python/lib/python3.9/site-packages'] I/flutter (10506): Server time: Sun, 27 Feb 2022 12:53:22 +0000 I/flutter (10506): Installed Applications: I/flutter (10506): ['django.contrib.admin', I/flutter (10506): 'django.contrib.auth', I/flutter (10506): 'django.contrib.contenttypes', I/flutter (10506): 'django.contrib.sessions', I/flutter (10506): 'django.contrib.messages', I/flutter (10506): 'django.contrib.staticfiles', I/flutter (10506): 'fyp_api.apps.FypApiConfig', I/flutter (10506): 'rest_framework'] I/flutter (10506): Installed Middleware: I/flutter (10506): ('whitenoise.middleware.WhiteNoiseMiddleware', I/flutter (10506): 'django.middleware.security.SecurityMiddleware', I/flutter (10506): 'django.contrib.sessions.middleware.SessionMiddleware', I/flutter (10506): 'django.middleware.common.CommonMiddleware', I/flutter (10506): ' here is my views.py code for the two concerned endpoints: @api_view(['GET']) def getBookings(request, Role, id): #Data = request.data #Role = Data['role'] #Role = request.META.get('HTTP_ROLE') BSerializer = '' if(Role == 'expert'): try: #eID = Data['eID'] eID = id #eID = request.META.get('HTTP_EID') expertExists = Experts.objects.filter(expertID = eID).exists() if(expertExists): exp = Experts.objects.get(expertID = eID) … -
SQL - How do I create a linkage table?
I'm building the following data model in Django / SQL Table 1 (Entity) - things that can do things Entity ID: Enum: (Person, or Business) Table 2 (Person) Entity ID: Person ID: Firstname Lastname Table 3 (Ltd Co.) Entity ID: Ltd Co. ID: Company Name Company No. I'm trying to link a Person, who has a Limited Co., with an Agent (who is also a Person) that also has a Limited Co. So 4 different entitites, two of which are type Person, and two of which are type Limited Co. Do I need another Linkage Table? E.g. Profile Person Profile Ltd Co Agent Person Agent Ltd Co Entity 1: Type Person Entity 3: Type Business Entity 2: Type Person Entity 4: Type Business Q. How do I create this Linkage Table in a Django Model / or SQL? Q. Is a Linkage Table the right approach? -
Django form buttons
I have an order form that should display product sizes as buttons, but the buttons do not register to be selected unless a user clicks exactly on the letter for the size ('S', 'M', etc.) in the exact center of the button. Clicking the space between the letter and the border of the button marks it as selected, but when you click Add to cart, it deselects itself. class OrderForm(forms.Form): def __init__(self, instance, *args, **kwargs): super(OrderForm, self).__init__(*args, **kwargs) self.instance = instance self.fields['size'] = forms.ModelChoiceField( queryset=self.instance.sizes.all(), widget=forms.RadioSelect()) The HTML is as follows: {% for choice in order_form.size %} <button type="button" class="size-btn">{{ choice }}</button> {% endfor %} Sizes is a simple model: class Size(models.Model): size = models.CharField(max_length=10) def __str__(self): return self.size This way the rendered HTML is a mess: <button type="button" class="size-btn"> <label for="id_size_0"> <input type="radio" name="size" value="2" id="id_size_0" required>S </label> </button> How do I fix the buttons so that they get selected even if clicked outside of the very center, in the size letter? Thanks. -
(mismatching_state) CSRF Warning! State not equal in request and response in django and google-api
I'm creating a web page in django which uses google api in order to send a pdf file to google drive. Everything was working perfectly on my local machine but as soon as i put it on production i got an error ((mismatching_state) CSRF Warning! State not equal in request and response.) as you can see down below. Here is the function which sends the request: def send_drive(file_name, file_path): CLIENT_SECRET_FILE = '/home/djuka/reusabletechnologies/project_app/reBankMini/reBankMiniApp/client_secret_156600557463-8e2qka5c4t646t7t4ksmbluo3aovv4q6.apps.googleusercontent.com.json' API_NAME = 'drive' API_VERSION = 'v3' SCOPES = ['https://www.googleapis.com/auth/drive'] service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES) # Upload a file file_metadata = { 'name': file_name, 'parents': ['1WpY7cw3S5RAPvCfFyPMDkw0I3vIZfQ_c'] } media_content = MediaFileUpload(file_path, mimetype='application/pdf') file = service.files().create( body=file_metadata, media_body=media_content ).execute() print(file) And Create_Service() function is in Google.py: import pickle import os from google_auth_oauthlib.flow import Flow, InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.http import MediaFileUpload, MediaIoBaseDownload from google.auth.transport.requests import Request from datetime import datetime def Create_Service(client_secret_file, api_name, api_version, *scopes): print(client_secret_file, api_name, api_version, scopes, sep='-') CLIENT_SECRET_FILE = client_secret_file API_SERVICE_NAME = api_name API_VERSION = api_version SCOPES = [scope for scope in scopes[0]] print(SCOPES) cred = None pickle_file = f'token_{API_SERVICE_NAME}_{API_VERSION}.pickle' # print(pickle_file) if os.path.exists(pickle_file): with open(pickle_file, 'rb') as token: cred = pickle.load(token) if not cred or not cred.valid: if cred and cred.expired and cred.refresh_token: cred.refresh(Request()) … -
How to get exact value of choice field in django
I have a choice field in Django model ) COMMITTEE_STATUS = ( ("p", "Pending"), ("a", "Active"), ("c", "Completed"), ) but the issue is when I am accessing these data in template I am getting p,a and c instead of actual peening, active and complete -
Finding api documentation flask
Have been given the task to ID all APIs in the source code since the previous dev was fired immediately..now i know that flask or django have certain templates to define API and specify parameters so i intend to write a script to simply look for such patterns , recursively across folders ..is the community aware of any tools / projects which do this across programming languages.. please nite, iam NOT speaking of swagger or api documentation..this tool NEEDs to be able to scan through code and generate necessary API docs -
Cannot assign "<User: Euler>": "Article.authorr" must be a "User" instance
I want to change the model field from the charfield to the user's forignkey And I do not want my information to be deleted First I added the fields, then I transferred the data, then I deleted the previous fields def change_names_of_field(apps, schema_editor): Article = apps.get_model('blog', 'Article') article = Article.objects.all() for s in article: **s.authorr = User.objects.get(username=s.author)** if Category.objects.filter(title=s.category).values_list("title", flat=True) == []: Category.objects.create(title=s.category) s.categoryy = Category.objects.filter(title=s.category) s.update = s.created s.published = s.created s.status = "p" s.save() class Migration(migrations.Migration): dependencies = [ ('blog', '0002_alter_article_created'), ] operations = [ migrations.AddField( model_name='Article', name='authorr', field=models.ForeignKey(User,on_delete=models.CASCADE,null=True), preserve_default=False, ), ... ... ... migrations.RunPython( change_names_of_field, ), ... ... ... -
bad request in django when unity send it but its OK when is use postman
I develop a service for our online games. when I'm testing by Postman everything is OK but when I'm tried test by end-user application djago send Bad_request 400 40. what happened ?! -
How to create ManyToMany object in django view?
I am trying to create product api. Here I have delivery_option filed which has a manytomamy relation with my product. when I am trying to create product I am getting some error like TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use delivery_option.set() instead. How to create the many to many field in django? @api_view(['POST']) @permission_classes([IsVendor]) def vendorCreateProduct(request): data = request.data user = request.user.vendor print(data['deliveryOption']) product = Product.objects.create( user=user, name=data['name'], old_price = data['price'], discount = data['discount'], image = data['avatar'], countInStock = data['countInStock'], subcategory = Subcategory.objects.get_or_create(name=data['subcategory'])[0], description=data['description'], delivery_option = data['deliveryOption'], ) serializer = ProductSerializer(product, many=False) return Response(serializer.data) -
GKE Django MySQL is not accessible during rolling update
I have Django application deployed in GKE. (Done with this tutorial) My configuration file: myapp.yaml apiVersion: apps/v1 kind: Deployment metadata: name: myapp labels: app: myapp spec: replicas: 3 selector: matchLabels: app: myapp template: metadata: labels: app: myapp spec: containers: - name: myapp-app image: gcr.io/myproject/myapp imagePullPolicy: IfNotPresent --------- - image: gcr.io/cloudsql-docker/gce-proxy:1.16 name: cloudsql-proxy command: ["/cloud_sql_proxy", "--dir=/cloudsql", "-instances=myproject:europe-north1:myapp=tcp:3306", "-credential_file=/secrets/cloudsql/credentials.json"] apiVersion: v1 kind: Service metadata: name: myapp labels: app: myapp spec: type: LoadBalancer ports: - port: 80 targetPort: 8080 selector: app: myapp settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ['DATABASE_NAME'], 'USER': os.environ['DATABASE_USER'], 'PASSWORD': os.environ['DATABASE_PASSWORD'], 'HOST': '127.0.0.1', 'PORT': os.getenv('DATABASE_PORT', '3306'), } Now, when I do rolling update or via kubectl rollout restart deployment myapp or kubectl apply -f myapp.yaml kubectl get pods is in the following state: NAME READY STATUS RESTARTS AGE myapp-8477898cff-5wztr 2/2 Terminating 0 88s myapp-8477898cff-ndt5b 2/2 Terminating 0 85s myapp-8477898cff-qxzsh 2/2 Terminating 0 82s myapp-97d6ccfc4-4qmpj 2/2 Running 0 6s myapp-97d6ccfc4-vr6mb 2/2 Running 0 4s myapp-97d6ccfc4-xw294 2/2 Running 0 7s I am getting the following error for some amount of time during rolling out: OperationalError at / (2003, "Can't connect to MySQL server on '127.0.0.1' (111)") Please advise how can I ajust settings to have rollout without a downtime/this error -
How to solve Django send_mail schedule problem?
I am using Pythonanywhere (PA) and like to use the PA's task scheduler to send scheduled emails. I made a ne file called: weeklyemailmm.py. The email settings in the setting.py works with other emailing stuff on my site. What am I doing wrong? I ty to use the code below: from django.core.mail import send_mail import datetime from django.conf import settings settings.configure(settings, DEBUG=True) today = datetime.date.today() weekday = today.weekday() subject = 'New weekly email' message = 'Hi there!' if (weekday == 2): try: send_mail( 'Subject here', 'Here is the message.', 'from@gmail.com', ['to@gmail.com'], fail_silently=False, ) print('It is Wednesday, email sent') except: print('It is not Wednesday') else: print('Email does not sent') On this way I always get It is not Wednesday. If I delete the try-except part and outdent it says: RecursionError: maximum recursion depth exceeded while calling a Python object If I delete the settings.configure(settings, DEBUG=True) that could be possibly wrong it say: django.core.exceptions.ImproperlyConfigured: Requested setting EMAIL_BACKEND, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
hi please help im trying to create a form view
hi everyone as i said im trying to create a Formview wait.. first at all where should i create the Meta class because i saw a page first where it create the Meta class inside the models but the i saw another page where it says that i should create in my forms so i did that also and then i say another page where it say that it must register the models in admin because i also hade that error where it show an error if i mis an s in Meta class models descibtion so heres my error: File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/core/checks /registry.py", line 77, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/core/checks /urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/core/checks /urls.py", line 23, in check_resolver return check_method() File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/urls/resolvers.py", line 446, in check for pattern in self.url_patterns: File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/urls/resolvers.py", line 632, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/laboratory-01/.local/lib/python3.9/site-packages/django/urls/resolvers.py", line 625, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", … -
How to post PDF to an API in Django?
I create a project with Django. I need a PDF upload page for my project. I created a form for that. class PDFTestForm(forms.ModelForm): pdf = forms.FileField(label=_(u"Please Upload the PDF file"), required=False) class Meta: model = TestPDF fields = ('pdf',) But I need the post the PDF to a API. This API is not related to my project. def mytestview(request): form = PDFTestForm(request.POST, request.FILES) if request.method == 'POST': if form.is_valid(): pdf = form.save() r = "https://api.myaddress.com/pdf" else: messages.error(request, 'Please, upload a valid file.') context = { 'form': form } return render(request, 'testthat.html', context) How can I post my uploaded PDF to this API address? -
React Multiselect package is sending [object, Object] instead of key and value
I am trying to pass data in my django backend from react frontend. I am able to pass the data using some Multiselect from react. But the problem is I am sending label and value but when I try to print my data in frontend and check the data what it is passing I got the result like [object Object] instead of [mylabel MyValue] and I just want to pass the option value. I am new to react so don't know much about setState things. Can someone help me to do this? Or any other easy way to pass multiple data in my api it would be much appreciated like I select HD and SD then in my backend I should get both value. #This is my react code check the deliveryOption, setDeliveryOption import axios from "axios"; import React, { useState, useEffect } from 'react' import { LinkContainer } from 'react-router-bootstrap' import { Table, Button, Row, Col, Form } from 'react-bootstrap' import { useDispatch, useSelector } from 'react-redux' import { Link } from 'react-router-dom' import FormContainer from '../components/FormContainer' import { MultiSelect } from "react-multi-select-component"; import Select from 'react-select'; const UPLOAD_ENDPOINT = "http://127.0.0.1:8000/api/orders/create/products/"; const options = [ { label: "HD 🍇", … -
How to direct a user from a page in a Django app to a static web page found on the same server
Assume that I have my Django app running at '/var/project/my_django_project/' and I want to direct the user to '/var/project/static_website/index.html' when a button is clicked in a template located at '/var/project/my_django_project/templates/my_template.html'. How can I achieve this?