Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CORS issue when posting (react and django)
I've connected react frontend and django rest framework backend app. I've set allow origin things in settings.py that are mentioned when solving CORS issues. and when I'm requesting axios.get in react app, it works fine, but when I'm requesting POST, it returns error "Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/posts' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request." I've put these and middleware setting('corsheaders.middleware.CorsMiddleware',) and installed apps ('corsheaders') in django settings.py. CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_WHITELIST = ( 'http://localhost:3000', ) And this is added to the top of react.js component : axios.defaults.baseURL = 'http://127.0.0.1:8000/api/'; axios.defaults.baseURL = 'http://local:8000/api/'; handleSubmit = (e) => { e.preventDefault(); axios.post('posts', { memo: this.state.memo, }).then(res => { console.log(res); }) .catch(error => { console.log(error) }); It's the error message on the console: Error: Network Error at createError (createError.js:17) at XMLHttpRequest.handleError (xhr.js:80) and It's on the django terminal console: "OPTIONS /api/posts HTTP/1.1" 301 0" -
I Want To Add Permissions To User in Django?
i want to add user profile section for example superuser and simple_user so i can add permissions But When I Submit my Registration Form I Get This Error: AttributeError at /register/ 'User' object has no attribute 'register' How To Fix And Save User Profile Name? Here is my Views.py from django.shortcuts import render , get_object_or_404,redirect from django.utils import timezone from blog.models import * from blog.forms import * from django.contrib.auth.decorators import login_required from django.urls import reverse_lazy from django.contrib.auth.models import User from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import (TemplateView,ListView, DetailView,CreateView, UpdateView,DeleteView) # Create your views here. def user_register(request): if request.method == "POST": reg = register(request.POST or None) if reg.is_valid(): user = reg.save() user.profile = "simple_user" user.set_password(user.password) user.save() else: print(register.errors) else: reg = register() return render(request,"registration/register.html",{'reg':reg}) Here is my Models.py class register(models.Model): user = models.OneToOneField(User,on_delete="Cascade", related_name="profile") Here is my Forms.py class register(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput(attrs={'class':'input-field'})) class Meta(): model = User fields = ('username','email','password') Here is the Error Image: Any Help Appreciated! -
Using only Django 2.2 ORM
I want to use Django with python3 to connect to my Postgresql database. I need only ORM modules of Django. My question is that what is the best project structure to reach my goal? -
How to retrieve data from Serialized Class RestApi
In Login Function the Token is retrieving and i need to Retrieve all details of Client How to Do that ? class Client_view(generics.ListCreateAPIView, generics.RetrieveUpdateDestroyAPIView): authentication_classes = [SessionAuthentication, BasicAuthentication, TokenAuthentication] permission_classes = [IsAuthenticated] queryset = Client.objects.all() serializer_class = ClientSerializer class LoginView(APIView): def post(self, request): serializer = LoginSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data["user"] profile=ClientSerializer django_login(request, user) token, created = Token.objects.get_or_create(user=user) return Response( {"token":Token.key},{"username":user.username}, status=200) class ClientSerializer(serializers.ModelSerializer): class Meta: fields = ['id', 'Name', 'UserName', 'Email', 'Mobile', 'Address'] model = models.Client class LoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, data): username = data.get("username", "") password = data.get("password", "") if username and password: user = authenticate(username=username, password=password) if user: if user.is_active: data["user"] = user else: msg = "User is deactivated." raise exceptions.ValidationError(msg) else: msg = "Unable to login with given credentials." raise exceptions.ValidationError(msg) else: msg = "Must provide username and password both." raise exceptions.ValidationError(msg) return data -
Write data to xls and download it in python
I have successfully created .csv file and now want to create .xls for the same data. After which I want to download it as well. So after creation of csv file from python I am sending response to the ajax function and downloading it from there using jquery. def expense_export(request): print(request.POST) if request.is_ajax(): ids = request.POST.getlist('ids[]') expenses = Expense.objects.filter(id__in=ids) data = [] field = ['SLNO', 'Date of Recording', 'Category', 'Sub Category', 'Invoice Date', 'Invoice No', 'GST No. Mentioned', 'Vendor Name', 'Details', 'Gross Value', 'SGST', 'CGST', 'IGST', 'Total Invoice Value', 'TDS(if any)', 'Net Payble'] field1 = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''] response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="Search Results.csv"' sno = 1 max = 0 for record in expenses: pay_data = [] if record.record: curr = 0 for pay_record in record.record: pay_row = [pay_record['date'], pay_record['amount'], pay_record['mode'], pay_record['ref'], pay_record['bank']] pay_data = pay_data + pay_row curr = curr + 1 if curr > max: max = curr gst_exist = 'No' if record.vendor: if record.vendor.gst_no: gst_exist = 'Yes' igst = int(record.gst) / 100 * record.amount tds = int(record.tds) / 100 * record.amount net_amount = int(record.amount) + int(igst) row = [ sno, record.timestamp.strftime('%d-%m-%Y'), record.expense_name, … -
Populating a django model with data from an external API
I am trying to pull in all the data from an external API to populate my Django Model. i found a similar question here Proper way to consume data from RESTFUL API in django I presume that what i need to do is GET request all of the data, and then POST request all the data to my model? However it doesn't fully answer my question. I would like to load all of the data from the api endpoint. What I have so far. Models.py class Bill(models.Model): STATUS = Choices('Open', 'Closed') Table_ID = models.ForeignKey(Table, default=None, on_delete=models.CASCADE) Bill_Status = models.CharField(choices=STATUS, default=STATUS.Open, max_length=20) Date_close = models.DateTimeField(default=timezone.now) class Bill_Items(models.Model): Bill_ID = models.ForeignKey(Bill, default=None, on_delete=models.CASCADE) Description = models.CharField(max_length=50) Price = models.DecimalField(max_digits=10, decimal_places=2) Payment_Made = models.BooleanField(default=False) Date = models.DateTimeField(default=timezone.now) def __str__(self): return self.Description Views.py from bill.models import Table, Bill, Bill_Items def get_bill_data(request): ##### GETTING THE DATA #### r = requests.get('http://127.0.0.1:8000/api/table1/', data=request.GET) #### POSTING THE DATA #### data = r.json() # Construct the bill attributes dictionary bill_attributes = { "PK": data["PK"], "Description": data["Description"], "Price": data["Price"] } Bill_Item = Bill_Items.objects.create(**bill_attributes) return HttpResponse(r.text) This doesnt seem to work, if anyone has some ideas please let me know. Thanks in Advance -
Django save all data
I have this code in my html <tr> <td colspan="2" style="text-align: center;"><h2 style="font-weight: bold;">Required Documents:</h2></td> </tr>{% for d in doc %} <tr> <td style="text-align: left;"> <input type="file" name="myfile" value="{{d.id}}" style="outline: none;" required/>{{d.Description}}</td> <td></td> </tr> {% endfor %} this is my code in views V_insert_data = StudentsEnrollmentRecord( Student_Users=studentname, Payment_Type=payment, Education_Levels=educationlevel,School_Year=schoolyear ) V_insert_data.save() insert_doc = StudentsSubmittedDocument( Students_Enrollment_Records = V_insert_data, Document = myfile ) insert_doc.save() \model class StudentsSubmittedDocument(models.Model): Students_Enrollment_Records = models.ForeignKey(StudentsEnrollmentRecord, related_name='+', on_delete=models.CASCADE,blank=True,null=True) Document_Requirements = models.IntegerField(null=True,blank=True) Document = models.FileField(upload_to='files/%Y/%m/%d',null=True,blank=True) Remarks = models.CharField(max_length=500,blank=True,null=True) def __str__(self): suser = '{0.Students_Enrollment_Records}' return suser.format(self) How to save all in the database all the required documents that the user input? -
Formik with Django
Hi I have to built an application of inventory and many more like receivable , payable. I am liking for a form library for front end that works well with back end django. Mist of my forms are master detail forms e.g inventory transfer note contains header information about transfer to and from with address. In detail forms have many line items. Each line has many fields that cannot be displayed fully like serial numbers or lot number. I also need auto suggest or list of values functionality on many fields like items, in stock serial numbers. What is the best tools or library to achieve this since I am a beginner in this but have lot of experience in oracle forms. Thanks in advance -
JSON Decode Error:Expecting value: line 1 column 1 (char 0)
I am running a admin website using Django. Trying to login my admin site and i am getting JSON Decode error.The response i am getting is 404 server error. Can anyone help to get out of this? Here is my views.py: def user_login(request): datas= {'log':False} if request.method == "POST": usern=request.POST.get('Username') print(usern) passw=request.POST.get('password') print(passw) response = requests.post(url='http://www.onebookingsystem.com/productionApi/API/Admin/login.php',data={"Username":usern,"password":passw}) print(response) json_data = response.json() print(json_data) if json_data['status'] == 1: user=authenticate(Username=usern,password=passw) login(request,user) range_yearly = 0 range_monthly = 0 respo = requests.get(url='http://www.onebookingsystem.com/productionApi/API/Admin/admin_dashboard.php') data_dash = json.loads(respo.text) The error i am getting is: <Response [404]> Internal Server Error: / Traceback (most recent call last): File "C:\Users\Android V\Anaconda3\envs\djangoenv\lib\site-packages\django\cor e\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Android V\Anaconda3\envs\djangoenv\lib\site-packages\django\cor e\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Android V\Anaconda3\envs\djangoenv\lib\site-packages\django\cor e\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Android V\admin\obs_app\views.py", line 20, in user_login json_data = response.json() File "C:\Users\Android V\Anaconda3\envs\djangoenv\lib\site-packages\requests\m odels.py", line 897, in json return complexjson.loads(self.text, **kwargs) File "C:\Users\Android V\Anaconda3\envs\djangoenv\lib\json\__init__.py", line 354, in loads return _default_decoder.decode(s) File "C:\Users\Android V\Anaconda3\envs\djangoenv\lib\json\decoder.py", line 3 39, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Users\Android V\Anaconda3\envs\djangoenv\lib\json\decoder.py", line 3 57, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) … -
Ensure that urlpatterns is list of path() and/or re_path() instances
(urls.E004) Your URL pattern [.*)$'>] is invalid. Ensure that urlpatterns is a list of path() and/or re_path() instances Why i am getting this error.. My url pattern list is as if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT), -
Django Changes Type of Variable on Override Save Function Call
Django seems to be changing the type of my variable after calling the resizeUplaodedImage method from type str to type Project while overriding the save method. I previously had this method working properly, but then I moved the logic outside of the save method and into another one that is called inside of save. I did this so I could do multiple things before saving but it seems now when I call the resizeUploadedImage method the variable I pass is being changed from a str to a Project. def save(self, *args, **kwargs): if self.image: url = self.image.url surl = url.split('/') fname = surl[-1] print('\t TRYING TO RESIZE IMAGE') print('filename',fname) print('top type', type(fname)) self.resizeUploadedImage(self, fname) # the additional function I wanted to add # self.createThumbnail(self, fname) super(Project, self).save(*args, **kwargs) def resizeUploadedImage(self, fname, *args): '''Resize the image being uploaded.''' print('resize top type', type(fname)) try: im = Image.open(self.image) print(im.size) if im.size > IMAGE_SIZE: im_sized = im.resize(IMAGE_SIZE, Image.ANTIALIAS) image_io = BytesIO() im_sized.save(image_io, im.format) print('resize type', type(fname)) self.image.save(fname, ContentFile(image_io.getvalue(), False)) except IOError as e: print("Could not resize image for", self.image) print(e) When I run this inside the Django shell, it works properly and resizes the image however when I run my tests I get TypeError: … -
How to prevent duplicate data entries in my model after reloading a get request in django
I am trying to load data from an external api into my django model. How can I prevent the data being duplicated each time it is pulled. It is a restaurant POS API and so as a customer orders new items they will get added to the bill JSON Object Example: After ordering drinks the waiter inputs the order to the POS and the API endpoint looks like this: [ { "pk": 1, "Description": "Coca Cola", "Price": "5.95" }, { "pk": 2, "Description": "Water", "Price": "3.50" } ] Then the waiter comes back to take the customers food order and inputs it to the POS, then the api endpoint looks like this: [ { "pk": 1, "Description": "Coca Cola", "Price": "5.95" }, { "pk": 2, "Description": "Water", "Price": "3.50" }, { "pk": 3, "Description": "Pizza", "Price": "12.00" }, { "pk": 4, "Description": "Pasta", "Price": "11.50" } ] I have these tables in my models.py class Restaurant(models.Model): Name Address class Table(models.Model): Restaurant_ID -> (ForeignKey From Restaurant) Table_Number API_Endpoint class Bill(models.Model): Table_ID -> (ForeignKey from Table) Bill_Status -> Binary field Can be 'Open' or 'Closed' Date -> DateTime of bill closed class Bill_Items(models.Model): Bill_Item_ID -> (ForeignKey from Bill) Description Price Payment_Made Date … -
django bootstrap 4 navbar toggler button not working on localhost
I am building a web app with django and bootstrap 4 on localhost. I have loaded the jquery, popper and bootstrap on the end of my body tag on the base.html file. Whiles in mobile screen size, the toggler button doesn't work. It doesn't display my menu or close it. I don't know what the problem is. I have checked other solutions but it still doesn't work. Please help! this is my code ''' {% load static %} <!DOCTYPE html> <html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}"> {% if title %} <title>Django blog - {{ title }}</title> {% else %} <title>Django blog</title> {% endif %} </head> <body> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top"> <div class="container"> <a class="navbar-brand mr-4" href="{% url 'blog-home' %}">Django Blog</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data- target="#navbarResponsive"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarToggle"> <div class="navbar-nav mr-auto"> <a class="nav-item nav-link" href="{% url 'blog-home' %}">Home</a> <a class="nav-item nav-link" href="{% url 'blog-about' %}">About</a> </div> <!-- Navbar Right Side --> <div class="navbar-nav"> {% if user.is_authenticated %} <a class="nav-item nav-link" href="{% url 'post-create' %}">New Post</a> <a class="nav-item … -
Should I use django-allauth or code my own authorization app?
I'm writing a web app and I notice a lot of people use django-allauth for their user authentication. It seems to be the most popular authentication app out there, but I'm wondering if this is the industry standard to use it or if most people code their own authentication apps. I'm also wondering how easy is it to customize, like change the templates, the url paths or the user models to add functionality. Thanks -
Push live HTML content updates using channels
I am attempting to modify the HTML content on a page for all connected users. Currently, when sending a message using the consumer it only sends it to the instance that initiated the initial message calling for the update (i.e. if a user presses a button that changes HTML content by sending a WebSocket event, only the content of their instance of the page is changed). Here is my current consumer: class ScoreConsumer(AsyncConsumer): async def websocket_connect(self, event): print("connected ", event) await self.send({ 'type': 'websocket.accept' }) async def websocket_receive(self, event): print("receive ", event) data = event.get('text', None) print(data) if data: loaded_data = json.loads(data) await self.send({ 'type': 'websocket.send', 'text': loaded_data['message'] }) async def websocket_disconnect(self, event): print("disconnected ", event) and here is the JavaScript (with unnecessary parts omitted) that initiates and handles the messages var loc = window.location; var wsStart = 'ws://' if (loc.protocol == 'https:'){ wsStart = 'wss://'; } var endpoint = wsStart + window.location.host + loc.pathname; var socket = new WebSocket(endpoint); console.log(endpoint); socket.onmessage = function(e){ console.log("Got websocket message " + e.data); var data = e.data; console.log(data); if (data == 'connected') { document.querySelector('#bluescore').innerHTML = "User Connected"; } else { document.querySelector('#redscore').innerHTML = data; } } document.querySelector('#test-button').onclick = function(e) { var message = "Yee"; … -
How to perform batch update in django rest api
table structure cart_id, product_id, quantity,customer_id view class CartUpdateView(generics.UpdateAPIView): queryset = models.Cart.objects.all() serializer_class = CartSerializer def put(self, request, *args, **kwargs): data = request.DATA serializer = CartSerializer(data=data, many=True) if serializer.is_valid(): serializer.save() return Response(status=HTTP_200_OK) else: return Response(status=HTTP_400_BAD_REQUEST) serializers class CartSerializer(serializers.ModelSerializer): class Meta: model = Cart fields = ('cart_id', 'quantity', 'customer_id', 'product_id') model class Cart(models.Model): cart_id = models.IntegerField() product_id = models.IntegerField() quantity = models.IntegerField() customer_id=models.IntegerField() Im trying to update my cart with the data { [cart_id:1, product_id:3, quantity:5,customer_id:2], [cart_id:2, product_id:4, quantity:2,customer_id:2], [cart_id:3, product_id:5, quantity:1,customer_id:2], [cart_id:4, product_id:8, quantity:1,customer_id:2], } So far i did only single row updation. Is there a way to perform bulk update.. Do i need to override any methods..! -
Get Info From Model/Middleware And Pass To A Template
How do I go about passing the reason to banned.html from the UserBanning model from the middleware file? Almost everything works but I can't seem to get the reason from the model to display in the template banned.html and im unsure way so any help will be amazing just got into learning about middleware. Thanks models.py: from django.db import models from django.contrib.auth.models import User from django.conf import settings class UserBanning(models.Model): user = models.ForeignKey(User, verbose_name="Username", help_text="Choose Username", on_delete=models.CASCADE) ban = models.BooleanField(default=True, verbose_name="Ban", help_text="Users Bans") reason = models.CharField(max_length=500, blank=True) class Meta: verbose_name_plural = "User Banning" ordering = ('user',) def __str__(self): return f"{self.user}" middleware.py: from .models import UserBanning from django.shortcuts import render class BanManagement(): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) banned = UserBanning.objects.all() context = { 'banned': banned, } if(banned.filter(ban=True, user_id=request.user.id)): return render(request, "account/banned.html", context) else: return response banned.html: {% extends "base.html" %} {% block content %} <p>Your account has been banned. Reason: {{ banned.reason }}</p> {% endblock content %} -
ModelForm's data attribute returns a tuple in Django shell
Upon reading how to create custom Form widgets, I noticed the documentation details passing widget attributes in the ModelForm constructor. https://docs.djangoproject.com/en/2.2/ref/forms/widgets/#customizing-widget-instances Attempting to emulate this in the Django shell, the form instance's data attribute returns a tuple and not a dictionary. I'm not clear on what is causing this behavior. from django.db import models class Person(models.Model): lastname = models.CharField(verbose_name="Last Name", max_length=20) firstname = models.CharField(verbose_name="First Name", max_length=20) age = models.CharField(verbose_name="Age", max_length=20) from django import forms from .models import Person class PersonForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.fields['firstname'].widget.attrs.update({'placeholder': 'First Name'}) class Meta: model = Person fields = '__all__' #django shell >>> person = PersonForm({'lastname': 'Monster', 'firstname': 'Cookie', 'age': 53}) >>> person.data ({'lastname': 'Monster', 'firstname': 'Cookie', 'age': 53},) -
Chrome Webdriver Options aren't affecting my test at all
So as a newbie in web development, my current topic is TDD, and thus i was tasked to deploy a web to heroku that has Functional Test on it. And so i wrote the code below. When i run test the code, the webdriver still open a Chrome window, even though i already added the argument '--headless' from selenium import webdriver from selenium.webdriver.chrome.options import Options class FunctionalTest(TestCase): def setUp(self): chrome_options = Options() chrome_options.add_argument("--headless") chrome_options.add_argument("--disable-infobars") chrome_options.add_argument("--disable-extensions") chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--disable-dev-shm-usage") chrome_options.add_argument("--no-sandbox") chrome_options.add_argument("--dns-prefetch-disable") self.browser = webdriver.Chrome(chrome_options=chrome_options) by the way, i put the Chromedriver in Program Files so i don't need to put 'executable_path' argument -
Celery(with django/redis)- Function with api calls works as a normal function, once add .delay() to add it to asynchronous task queue, I get SSL error
I have celery setup fine in that it works for simple tasks like a hello world (calling hello_world.delay() in django views there is no problem). I created another more complicated function that involves making many calls to a an api to retrieve data to update the database. Just calling this function without celery (update_comments()) there is no problem, and the database gets updated(takes around 15 seconds or so...that is why I want to use celery). Currently the function makes dozens of calls to the api to update the model. The problem is once I add .delay() to make it a celery task. I get the below errors (maxretry ssl error). I know I have celery setup correctly for basic tasks as it works fine for a basic hello world function, but not this more complicated function with many api calls. I can't figure out why there is this disparity or if there is any setting I am supposed to change because I have an api call. Currently just running on dev. Tasks @task() def update_comments(): for channel in Channel.objects.all(): search_url='https://www.googleapis.com/youtube/v3/commentThreads' params1={ 'part': 'replies,snippet', 'allThreadsRelatedToChannelId': channel.channel, 'searchTerms': '#vi', 'maxResults': 100, 'order': 'time', 'key' : settings.YOUTUBE_API_DATA_KEY } params2={ 'part': 'replies,snippet', 'allThreadsRelatedToChannelId': channel.channel, … -
TypeError Return on cURL command to Django DRF
When testing my API through cURL I'm getting an TypeError response (500 Internal Server Error) even though my data is saving to the database. When I remove save_task = serializer.save() from the views.py I get a 200 response, but the data is not saved to the database. Any ideas on what could be causing this? cURL Command: curl -kiu root:password -X POST -d "task=Register&creator=POAP Script&owner=Register Microservice&mac=00:00:00:00:00:00&ip=172.16.24.24" http://192.168.1.100/api/task/ cURL Error: HTTP/1.1 500 Internal Server Error Server: nginx/1.14.1 Date: Fri, 01 Nov 2019 22:45:21 GMT Content-Type: text/plain; charset=utf-8 Content-Length: 12593 Connection: keep-alive X-Frame-Options: SAMEORIGIN Vary: Cookie TypeError at /api/task/ 'Task' object is not callable Request Method: POST Request URL: http://192.168.1.100/api/task/ Django Version: 2.2.6 Python Executable: /usr/local/bin/uwsgi Python Version: 3.6.8 Python Path: ['.', '', '/usr/lib64/python36.zip', '/usr/lib64/python3.6', '/usr/lib64/python3.6/lib-dynload', '/opt/django/lib64/python3.6/site-packages', '/opt/django/lib/python3.6/site-packages'] Server time: Fri, 1 Nov 2019 22:45:21 +0000 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'task', '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: File "/opt/django/lib64/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/opt/django/lib64/python3.6/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/opt/django/lib64/python3.6/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/django/lib64/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "/opt/django/lib64/python3.6/site-packages/django/views/generic/base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "/opt/django/lib64/python3.6/site-packages/rest_framework/views.py" … -
Browser is not loading page
Good day. I am new to django. I just build my Listview and detailview for my app. But when ever i try to run my program on a server, i found the following problems. Please find the images The error am getting on the browser is page not found The current path products/ does not match any of the urls in my app -
verifying users email using django rest auth as a rest API
I am creating a rest API and using Django-rest-auth, and want to verify users' email. Everything works until I click the link to verify the user's email. earlier I got an error, but I eventually got it fixed, the problem was that the fix made it no longer restful. I later found out in the documentation an idea to why I was getting this problem https://django-rest-auth.readthedocs.io/en/latest/faq.html after searching online I found some fixes that worked to some degree, BUT the email still did not verify after clicking the link, although I wasn't getting errors like before. my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'rest_auth.registration', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.facebook', 'users', ] ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_LOGOUT_ON_GET = True ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 1 ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5 ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 86400 # 1 day in seconds ACCOUNT_LOGOUT_REDIRECT_URL ='/accounts/login/' LOGIN_REDIRECT_URL = '/accounts/profile' SOCIALACCOUNT_EMAIL_VERIFICATION = 'none' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'test@gmail.com' EMAIL_HOST_PASSWORD = 'test' DEFAULT_FROM_EMAIL = 'test@gmail.com' DEFAULT_TO_EMAIL = EMAIL_HOST_USER EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = '/' my urls.py from django.contrib import admin from django.urls import path, re_path from django.conf.urls import … -
How to build database API with Django that connects bridge to local server?
I want to implement a website that serves as an API to a database on one of our servers. The server is secure and can only be accessed on site. So to push data from the server, a bridge computer must be used. I want to set up a site where users can request access, filter a database, and then retrieve files based on their filtering criteria. For example, if a user wants all files for a subject aged 50 years, then a command needs to be executed on the host machine connected to the correct network to retrieve those files (based on an identifier) from the secure server, then send to the user, perhaps after performing a couple of additional operations on the host machine (python and bash scripts). I want to build all of this in python (Django) and mysql (if necessary). Would a set up like this be possible? -
Javascript Fetch - Get data from server when ok = false
I want to make an POST request to my server using the fetch method. If the request was successfully, it returns status code 200 with data. If there was an error, it returns any status code except 200 with a message. Here's my JS code: class Ajax{ static Post(url, data, success, error=null){ const csrftoken = data["csrfmiddlewaretoken"]; delete data["csrfmiddlewaretoken"]; fetch(url, { method: "POST", credentials: 'same-origin', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', "X-CSRFToken": csrftoken }, body: JSON.stringify(data) }) .then(response => { const data = response.json(); if (response.ok){ return data } else { throw {"name": "ResponseNotOkError", "message": data["message"], "status": response.status}; } }) .then(success) .catch(err => { if (error !== null){ error(err.message, err.status); // custom function } else { TinyText.Create(err.message); // Showing error } }); } } For debugging I inserted this into the first line after my ajax function in my Django project: return JsonResponse({ "message": "Blablablabla" }, status=400) I don't know how to access that message.