Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting all cookies for privacy policy
We have to write a new privacy policy for a website and therefore need to create a list of all Cookies. It is running in React.js (Front-end)/Django (Backend). I wonder if there is a "smart" way to get all the cookies our website is using. We have integrated different providers e.g. Intercom, Segment, etc. Is there any tool/extension you can recommend, or would you rather go through each individual provider to check which cookies they are adding? -
Domain Name Changes Back to Static IP
I have been trying to solve this issue for the past days, but haven't been able to fix it. The problem is that my domain name redirects me to my static ip address, but as soon as the page is loaded, the url displays the ip. Some context: I am running a django-based application in AWS Lightsail, which uses Apache 2 as the web-server. I have created a virtual host that serves port 80. The domain name I bought it using GoDaddy, and currently points to this static ip. My intuition tells me that the problem is not with the domain service provider because it does redirect my traffic to the ip. However, one thing to consider is that I have not changed the nameservers at Godaddy, would this be the root problem? My httpd.conf file looks like this, in AWS is named bitnami.conf: <VirtualHost _default_:80> WSGIScriptAlias / /opt/bitnami/apps/django/django_projects/myApp/myApp/wsgi.py ServerName myApp.ca <Directory /opt/bitnami/apps/django/django_projects/myApp> AllowOverride all Require all grantedOptions FollowSymlinks </Directory> DocumentRoot /opt/bitnami/apps/django/django_projects/myApp Alias /static/ /opt/bitnami/apps/django/django_projects/myApp/static/ <Directory /opt/bitnami/apps/django/django_projects/inVerte/static> Require all granted </Directory> </VirtualHost> I have tried adding other directies such as: RedirectPermanent / http://myApp.ca/ Redirect /index http://myApp.ca/ RewriteEngine On RewriteCond %{HTTP_HOST} !^myApp.ca$ RewriteRule /.* http:/myApp.ca/ [R] However, they only cause a … -
What is the best format for an image that I can retrieve from the desktop application and display it in a web application?
Good evening I want to import photos and PDFs from the desktop application and view them in the web app (dango), how do we do it without using binary format? -
Is there a way to make a django ModelFormSet contain an uneditable field
I have a series of model objects, and I'd like data about them to be editable from a single view. Accordingly, I set this up: class JiraTicketTaskUpdateView(LoginRequiredMixin, ModelFormSetView): model = models.TaskRecord template_name = 'qa_jiraticket_task_update.html' #form_class = forms.EditListForm fields = ['task_name', 'status', 'hours', 'assigned_to'] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) ticket_id = int(self.request.path.split('/')[-1]) ticket = models.JiraTicket.objects.get(pk=ticket_id) context['formset'].queryset = ticket.taskrecord_set.all() breakpoint() #We can add more stuff here later return context I want the "assigned_to" field to be viewable, but not editable. Now, I'm aware from the django documentation I can render each form in the formset manually (following example is not my code, its from the django docs) <form method="post"> {{ formset.management_form }} {% for form in formset %} {{ form.id }} <ul> <li>{{ form.name }}</li> <li>{{ form.age }}</li> </ul> {% endfor %} </form> However, for some reason management doesn't want the form id rendered, which is necessary for this method to work. Is there any way to edit the underlying formset and/or context to make the field uneditable on the view side? -
Django settings, templates and SQLite data don't update
I deployed my django website to Hostgator, but now I can't see any changes in the website when changing the files. The only changes that happen are in static files, like CSS and JS, but changing the templates won't make any difference to the shown HTML. The database works fine: I can add and remove entries with Django admin in the site and that will take effect in the HTML. But if I run manage.py or even delete completely the SQLite file, nothing happens. Running the same django project locally on my machine works fine. It's as if those files were in cache or something like that. I tried lots of things, but nothing works. -
How to pass topic from urls to utils.py?
I have a problem in the utils.py file. I would like to pass the argument "calendar_id" from the url in the utils.py file but in the line "calendar_id = self.kwargs['calendar_id']" makes me the following error: "'Calendar' object has no attribute 'kwargs'" urls.py: urlpatterns = [ url(r'^home/(?P<group_id>\d+)/(?P<calendar_id>\d+)/calendar/$', views.CalendarView.as_view(), name='calendar_view'), #Prova ] views.py: class CalendarView(generic.ListView): model = Event template_name = 'cal/calendar.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # use today's date for the calendar d = get_date(self.request.GET.get('month', None)) # Instantiate our calendar class with today's year and date cal = CalendarUtils(d.year, d.month) # Call the formatmonth method, which returns our calendar as a table html_cal = cal.formatmonth(withyear=True) context['calendar_view'] = mark_safe(html_cal) context['prev_month'] = prev_month(d) context['next_month'] = next_month(d) return context utils.py: class Calendar(HTMLCalendar): def __init__(self, year=None, month=None): self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, events): events_per_day = events.filter(start_time__day=day) d = '' for event in events_per_day: # d += f'<li> {event.title} </li>' d += f'<li> {event.get_html_url} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek, events): week = '' for d, weekday in theweek: week += … -
How to implement chart.js with Django?
I'm a beginner django programmer with little but some python experience. For my personal project, I'm trying to use chart.js to graph my stored data. Here's what I have in models.py class MarksInputOne(models.Model): date = models.DateTimeField(auto_now_add=True) mark = models.CharField(max_length=200) def __str__(self): return self.mark And this is just an example code from chart.js <div class="col"> <div class="col-md"> <h5>Graph</h5> <hr> <div class="card card-body"> <canvas id="chart" width="800" height="400"></canvas> <script> var ctx = document.getElementById('chart').getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], datasets: [{ label: 'Academic Performance', data: [12, 19, 3, 5, 2, 3], fill: false, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); </script> </div> </div> </div> Could someone please help me to implement my data into the chart.js code above? If any extra info is needed, please let … -
Is it possible to use a PHP script in Django project?
I'm using Django as a backend in my project and JS for the frontend. I linked my frontend HTML pages to the Matomo analytics tool for collecting user data via a JS tracking code. but I don't want to reveal the Matomo server URL as it will be shown in response data. Matomo team provide a PHP script to do that via a proxy server you can find it here My question: Is it possible to use this PHP script while the backend is Django? do I need any kind of bridging? Thank you. -
Django. DetailView simple validation. Check weather user has a subscription
When user requests object, when user wants to enter detail view's page, I want to check weather user have subscription and redirect him. But I don't know how to request user and validate him in DetailView. This is what at least I could did. class PropertyDetailView(LoginRequiredMixin, DetailView): login_url = '/login/' model = Property template_name = 'project/property/property_detail.html' def post(self, *args, **kwargs): if self.request.user.sale_tariff is None: return redirect('/') Are there any ways how to validate DetailView? -
IntegrityError: null value in column "invoiceOwner_id" violates not-null constraint
In my django app, i'm having difficulties whenever i want to add a new object that uses the table paymentInvoice. The error i'm getting from my api looks like this IntegrityError at /api/clients/invoice/ null value in column "invoiceOwner_id" violates not-null constraint DETAIL: Failing row contains (10, INV-0006, Lix, 2020-08-04, 1, Pending, 3000, null). NB: I haven't created the field invoiceOwner_id, postgres automatically added it or rather is using it as a representation for my invoiceOwner field class Purchaser(models.Model): name = models.CharField(max_length=50) phone = models.CharField(max_length=20, unique=True) email = models.EmailField(max_length=255, unique=True, blank=True) image = models.ImageField(default='default.png', upload_to='customer_photos/%Y/%m/%d/') data_added = models.DateField(default=datetime.date.today) def __str__(self): return self.name class paymentInvoice(models.Model): invoiceNo = models.CharField(max_length=50, unique=True, default=increment_invoice_number) invoiceOwner = models.ForeignKey(Purchaser, on_delete=models.CASCADE, related_name="invoice_detail") product = models.CharField(max_length=50, blank=True) date = models.DateField(default=datetime.date.today) quantity = models.PositiveSmallIntegerField(blank=True, default=1) payment_made = models.IntegerField(default=0) def __str__(self): return self.invoiceOwner.name serilizers file class paymentInvoiceSerializer(serializers.ModelSerializer): invoiceOwner = serializers.SerializerMethodField() class Meta: model = paymentInvoice fields = '__all__' def get_invoiceOwner(self, instance): return instance.invoiceOwner.name views file class paymentInvoiceListCreateView(ListCreateAPIView): serializer_class = paymentInvoiceSerializer queryset = paymentInvoice.objects.all().order_by('-date') GET result from api call. **GET** result from ``api`` { "id": 1, "invoiceOwner": "Martin", "invoiceNo": "INV-0001", "product": "", "date": "2020-08-04", "quantity": 1, "payment_made": 0 } Tried passing below as POST but got the main error { "invoiceOwner": "Becky", "product": … -
I am trying to integrate paytm payment gateway to my django website but having trouble
In integration steps on paytm website the first step is to Initiate transaction API for which they have provided this code:https://developer.paytm.com/docs/initiate-transaction-api/?ref=payments I copy pasted this in my views.py under the processOrder view: def processOrder(request): transaction_id = datetime.datetime.now().timestamp() data = json.loads(request.body) if request.user.is_authenticated: customer=request.user.customer order, created=Order.objects.get_or_create(customer=customer, complete=False) total=float(data['form']['total']) order.transaction_id=transaction_id if total == order.get_cart_total: order.complete = True order.save() ShippingAddress.objects.create( customer=customer, order=order, address=data['shipping']['address'], city=data['shipping']['city'], state=data['shipping']['state'], zipcode=data['shipping']['zipcode'], name=data['form']['name'], email=data['form']['email'], mobile=data['form']['mobile'], ) paytmParams = dict() paytmParams["body"] = { "requestType" : "Payment", "mid" : "YOUR_MID_HERE", "websiteName" : "WEBSTAGING", "orderId" : "ORDERID_98765", "callbackUrl" : "https://localhost/handlerequest", "txnAmount" : { "value" : "1.00", "currency" : "INR", }, "userInfo" : { "custId" : "CUST_001", }, } checksum = PaytmChecksum.generateSignature(json.dumps(paytmParams["body"]), "YOUR_MERCHANT_KEY") paytmParams["head"] = { "signature" : checksum } post_data = json.dumps(paytmParams) # for Staging url = "https://securegw-stage.paytm.in/theia/api/v1/initiateTransaction?mid=YOUR_MID_HERE&orderId=ORDERID_98765" mid=YOUR_MID_HERE&orderId=ORDERID_98765" response = requests.post(url, data = post_data, headers = {"Content-type": "application/json"}).json() print(response) return render(request,"paytm.html",{'paytmParams':paytmParams}) return JsonResponse('Payment Complete',safe=False) and this is my js for html html:<button class="btnabc btnabc-secondary btnabc-lg d-none" id='payment-info'>Proceed</button> <script type="text/javascript"> var total = '{{order.get_cart_total}}' var form = document.getElementById('form') form.addEventListener('submit', function (e) { e.preventDefault() console.log('form submitted..') document.getElementById('form-button').classList.add("d-none"); document.getElementById('payment-info').classList.remove("d-none"); }) document.getElementById('payment-info').addEventListener('click', function (e) { submitFormData() }) function submitFormData() { console.log('Payment Button Clicked') var userFormData = { 'name': null, 'email': null, 'mobile':null, 'total': total, } … -
Find the difference between two model field
I want to find the difference between quantity of Product class and sold_quantity of Stock class. How do I do that models.py from django.db import models class Category(models.Model): name = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return self.name class Product(models.Model): name = models.CharField(max_length=100) slug = models.CharField(max_length=100) price = models.DecimalField(max_digits=6, decimal_places=2) quantity = models.IntegerField(null=True, blank=True) category = models.ForeignKey( Category, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.name class Stock(models.Model): sold_quantity = models.IntegerField(null=True, blank=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True) def __str__(self): return self.product.name -
How to setup wsgi.py file in Django for WhiteNoise 5.1.0?
I use Heroku and i have a problem with static files - they are creating in STATIC_ROOT. I've got that i need to setup wsgi.py file for WhiteNoise. I tried some different ways which i found to setup it but i every time get fail. Here is my code: /wsgi.py import os from django.conf import settings from django.core.wsgi import get_wsgi_application from whitenoise import WhiteNoise application = get_wsgi_application() application = WhiteNoise(application, root=settings.STATIC_ROOT) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'api_obs.settings') With this here is the last error message in errors thread: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' What the right way to setup it? My settings.py file is right here is my previous question with them. I only haven't declared STATICFILES_DIRS but it's not required right? -
Manipulate serialization result for a many=true serialization
I want to manipulate the serialization result of a many=True serialization: class CustomContentElementSerializer(serializers.ModelSerializer): class Meta: model = CustomContentElement fields = [ 'type', 'html' ] result = CustomContentElementSerializer( CustomContentElement.objects.all(), many=True ) I don`t want to manipulate the single object serialization result, but the complete list. With overriding function to_representation, I'm just able to manipulate the single elements of the returned list. I think it`s complicated, because the ModelSerializer class sets it`s base class in the constructor (Line 117: https://github.com/encode/django-rest-framework/blob/master/rest_framework/serializers.py) Does somebody have an idea how it could be possible to manipulate the result at the end for many=True serialization? -
Django 3 - NoReverseMatch
I'm somehow new to Django, and I don't know how to resolve what seems to be a simple bug. A lot of peoples asked more or less the same question here but any to their fixes worked for me. So I have 2 apps, one that will work as the main menu for other apps: Main Menu urls.py : re_path(r'^elec/boq/', include('a0101_boq_elec_main.urls', namespace="SAMM")), Then in the urls.py of that app I have this: app_name='BoqElecMM' urlpatterns = [ path('', views.boq_index.as_view(), name='boqIndex'), path('search/', views.SearchResultView.as_view(), name='searchResult'), path('<int:boq_project_id>', views.BoqProjectInfo.as_view(), name='BPInfo'), ] But when I'm trying to use this in my template: <a href="{% url 'BoqElecMM:BPInfo' %}"> , I'm getting this Django error : NoReverseMatch at /elec/boq/ Reverse for 'BPInfo' not found. 'BPInfo' is not a valid view function or pattern name. Could some of you tell me please, what I'm doing wrong here? Thank you in advance. -
TypeError at / buf is not a numpy array, neither a scalar. How to make Celery work with OpenCV?
I'm trying to work with an image in Celery using OpenCV. For that, I'm creating a task, a Django form, and in the task, I'm passing the form's image path. From now on, I want to encode the image, create a numpy array, and then play around with the image using OpenCV. @app.task() def clean(file_path): with open(file_path, encoding='latin1') as img: numpyar = np.fromstring(img.read(), dtype=np.uint8) image = cv2.imdecode(numpyar, cv2.IMREAD_UNCHANGED) return image When I run this, my task's result is None; so I'm guessing the problem has to be with the numpy array. The problem is that the array is not JSON serializable. When I transform the array into a JSON, running the following code @app.task() def clean(file_path): with open(file_path, encoding='latin1') as img: numpyar = np.fromstring(img.read(), dtype=np.uint8) f = json.dumps(numpyar, cls=NumpyEncoder) image = cv2.imdecode(f, cv2.IMREAD_UNCHANGED) return image I'm getting an error from OpenCV, at imdecode function: TypeError at / buf is not a numpy array, neither a scalar So basically, Celery can't work with numpy arrays, but opencv needs the numpy array in order to work. Is there any way to make this work? Thank you! -
ModuleNotFoundError: No module named 'backend' when trying to use django project models in a standalone python script
I'm trying the following. I have a backend API written in Django. I want to create a standalone script that uses some models, the database and some functions from that backend project. So I made a new python project (using docker) and when I try to import a basic class from the backend project in it I get a ModuleNotFoundError: No module named 'backend' error. This is the structure of my new project: In my app.py I try to use the backend api, this is the code: import os, sys, django sys.path.append('/Users/sgerrits/PycharmProjects/backend/') os.environ['DJANGO_SETTINGS_MODULE'] = 'backend.settings.development"' django.setup() from backend.util.helper_classes import Sensor cough = Sensor.COUGHS Error log: Attaching to store-handler_app_1 app_1 | Traceback (most recent call last): app_1 | File "/opt/project/store-handler/app.py", line 5, in <module> app_1 | django.setup() app_1 | File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 19, in setup app_1 | configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) app_1 | File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 83, in __getattr__ app_1 | self._setup(name) app_1 | File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 70, in _setup app_1 | self._wrapped = Settings(settings_module) app_1 | File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 177, in __init__ app_1 | mod = importlib.import_module(self.SETTINGS_MODULE) app_1 | File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module app_1 | return _bootstrap._gcd_import(name[level:], package, level) app_1 | File "<frozen importlib._bootstrap>", line 994, in _gcd_import app_1 | … -
An error occurs when adding a container command to Django aws eb
I am using Python 3.7 Django 3.0.9 postgresql 11 -ebextension/django.config container_commands: 01_migrate: command: "django-admin.py migrate" leader_only: true 02_compilemessages: command: "django-admin.py compilemessages" option_settings: aws:elasticbeanstalk:container:python: WSGIPath: config.wsgi:application aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: config.settings Error message when running eb deploy 2020-08-04 14:48:51 INFO Environment update is starting. 2020-08-04 14:49:30 INFO Deploying new version to instance(s). 2020-08-04 14:49:45 ERROR [Instance: i-0719a2ed67b621907] Command failed on instance. An unexpected error has occurred [ErrorCode: 0000000001]. 2020-08-04 14:49:45 INFO Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. 2020-08-04 14:49:45 ERROR Unsuccessful command execution on instance id(s) 'i-0719a2ed67b621907'. Aborting the operation. 2020-08-04 14:49:45 ERROR Failed to deploy application. eb logs error content 2020/08/04 11:35:55.132182 ERROR Requirements file provided! Importing into Pipfile… 2020/08/04 11:35:56.227858 ERROR Error occurred during build: Command 01_migrate failed 2020/08/04 11:35:56.227884 ERROR An error occurred during execution of command app-deploy - PostBuildEbExtension. Stop running the command. Error: Container commands build failed. Please refer to /var/log/cfn-init.log for more details. After checking the command 01_migrate failed message, it seems that there is a problem with the continer commands, so I ran django-admin migrate. django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I have defined … -
Change how comments are shown (django_comments_xtd)
Django=3.0.8 settings.py INSTALLED_APPS = [ ... 'comments_aux', # PROJECT_APPS 'django_comments_xtd', # THIRD_PARTY_APPS. django-comments-xtd 'django_comments', # THIRD_PARTY_APPS. django-comments-xtd ... ] comments_aux.html {% load static %} {% load socialaccount %} {% load comments_xtd %} {% load general %} {% if object.allow_comments %} {% providers_media_js %} {% endif %} <a href="{% url 'account_login' %}?next={{ object.get_absolute_url|add:'#comments'|urlencode }}">Login</a> <div id="comments"></div> {% script 'jquery' %} {% script 'react' %} {% script 'react_dom' %} {% script 'popper' %} {% script 'bootstrap' %} **comments_aux.html** <script> window.comments_props = {% get_commentbox_props for object %}; window.comments_props_override = { allow_comments: {%if object.allow_comments%}true{%else%}false{%endif%}, allow_feedback: true, show_feedback: true, allow_flagging: true, polling_interval: 86400000 // Day in milliseconds. In fact, this means never poll. }; </script> <script type="text/javascript" src="{% url 'javascript-catalog' %}"></script> <script src="{% static 'django_comments_xtd/js/vendor~plugin-2.6.2.js' %}"></script> <script src="{% static 'django_comments_xtd/js/plugin-2.6.2.js' %}"></script> <script> $(function() { $('[data-toggle="tooltip"]').tooltip({html: true}); }); </script> Problem Could you help me change the way how comments are displayed. This is the documentation: https://django-comments-xtd.readthedocs.io/en/latest/templates.html#comment-tree-html But in this case comments don't seem to be rendered at the backend. They seem to be shown via react. What I need is at least: 1. Show users' avatars like this: <img src="{{ user.socialaccount_set.all.0.get_avatar_url }}" /> I use django-allauth, so, this will show avatars from social networks. 2. Now … -
Django Form Update using __init__ method, failed to have 'instance' value shown at Edited Form
I would like to Edit Django Form for a particular instance with PK value. I need to use init method to limit the dropdown selection. However I do not know how to do instance value capture in Django Form, with init method. Views.py def updateOrder(request, pk): order = Order.objects.get(id=pk) form = OrderForm(request.POST, customer=request.user.customer.id, instance=order) if request.method == 'POST': form = OrderForm(request.POST, customer=request.user.customer.id, instance=order) if form.is_valid(): form.save() return redirect('customer_table') context = {'form':form} return render(request, 'create-order.html', context) class OrderForm(ModelForm): class Meta: model = Order fields = ['contract', 'quantity', 'status'] def __init__(self, *args, **kwargs): customer = kwargs.pop('customer', None) super(OrderForm, self).__init__(*args, **kwargs) self.fields['contract'].queryset = Contract.objects.filter(customer__id=customer) self.fields['status'].queryset = Status.objects.filter(customer__id=customer) -
it is not return QuerySet filter data to HTML
I am trying the following code to print all data into the HTML page. when I am printing the data in command prompt it works properly but not printing data into the HTML. view.py output of view.py in command prompt I want to print same data to HTML def previousYear(request): Subjects = Subject.objects.all() filters = None Papers = None print("=========================================================") if request.method == "POST": if (request.POST.get("Year") != "") & (request.POST.get("Department") != ""): a = request.POST.get("Year") b = request.POST.get("Department") filters = Subjects.filter(Year=a,Department_id=b) for i in filters: Papers = Pre_Q_Paper.objects.filter(Subjects=i) if Papers.exists(): print(i) for j in Papers: print(j) data = {"papers":Papers, "filters":filters} return render(request,"Previous.html", data) main.html {%for i in filters%} <h2>{{i}}</h2> {% for item in papers %} <h2>{{ item }}</h2> {% endfor %} {% endfor %} -
django rest framework and cors error with apache2
I have an api that requires authtoken in the form of headers using django token authentication Authorization Token:2312esdadsadsad But in javascript calling with this header shows error Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response. I have already done CORS_ORIGIN_ALLOW_ALL = True CORS_ORIGIN_WHITELIST = ( 'http://mypage.com' ) in my settings.py but it doesn't work as well I also have corsMiddle from django-cors-header included at the top but it still doesn't work. This same requests works with postman on apache as well as local server, but doesn't work with request from browser html What should I do? My gut feeling says it can be solved by Apache, but not Django framework.But I may be wrong. -
Logical delete in Angular & Django project
I'm new to programming in general, and currently I’m working on a project for an appointment app developed in Angular, Django & Django REST for the api part. I’ve created two different models, an Agent model and a Customer one, both extended from the default User that Django provides, just to add some more fields to them. I’ve successfully created the basic CRUD operations in both models and in both parts, backend and frontend. Currently i have an issue assigned to me from my project manager. The issue consists in logical deleting the Agent & Customer models, and as a result make the User inactive. Now, being new to the programming world I’ve done some research and understood that the logical delete is also know as ‘soft delete’, where an instance is simply marked as deleted, but not entirely deleted from the database. The problem is I’m not sure how to solve this issue, if i should work for this in the Angular code? Or Django code? What should i do exactly? Thanks in advance! -
405 Method Post Not Allowed
I wrote the following code: class UserViewSet(viewsets.ReadOnlyModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [IsCreation|permissions.IsAuthenticated] def change_password(self, request): print(request.user) With the following corresponding route in urls.py: path('api/users/password', views.UserViewSet.as_view({'post': 'change_password'})) But when I make a request to 'api/users/password/' I get the following error: { "detail": "Method \"POST\" not allowed." } What am I doing wrong here? -
Can I use google,facebook etc. oauth in django-rest?
I want to implement oauth in my django-rest-framework project.I tried some packages but I'm getting errors everytime. If you have any idea please share with me. Thanks!