Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
RDS in AWS; Cannot connect to db
I was trying to deploy my Django project into AWS. I was just following the official instruction and successful in just showing a page. And now I am trying to connect the project to ebdb. But when I did python manage.py migrate, this error happened. django.db.utils.OperationalError: could not connect to server: Connection timed out (0x0000274C/10060) Is the server running on host "" and accepting TCP/IP connections on port 5432? I am trying to use RDS in AWS and I already set environment variables for the db on my virtual environment. settings.py is like this and it's just the same as the official doc does if 'RDS_HOSTNAME' in os.environ: DATABASES = { 'default': { #'ENGINE': 'django.db.backends.sqlite3', #'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), #RDS in AWS 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], } } Why does this error cause and how can I fix this? -
how to manage ubuntu server with django and celery?
So i had ubutu 16.04 server and i configure my project on them, i use django and postgresql with celery.I am facing a problem, like on a single server i want to manage one client for next client i want to deploy the same server with same configuration but my postgre server is same for all. I am able to do this but in future when user grow to 50 or 100 what can i do. i research some topic but not able to manage. Should i use docker or kubernatis services or any other route. because the main problem is celery worker and i want separate worker for each client on diffrent server, so plz suggest me. thanks for your time. -
Import Errors all through my django project
I upgraded my python version, now every import statement throughout my django project is underlined with red lines, indicating an error. -
How can I develop a Django site and app in separate Git repos?
I'm developing a new Django site. It uses some existing Django apps and I'm building some of my own. I'd like to make my site and apps available as separate Git repositories. In other words, someone may want to clone/contribute to the whole site, or they may want to clone/contribute to just an app. How can I organise the site folder so that I can: easily run the site locally easily modify either site or app code locally have site code and app code in separate Git repos -
form.field.value fail to display any information
I'd like to edit an article detail page, If the request method is get, pre-formulate the form with data def edit_article(request, pk): article = Article.objects.get(pk=pk) if request.method == "GET": form = CommentForm(instance=article) context = {'article':article,} return render(request, "article/article_detail_edit.html", context) The template <div class="form-group"> <label for="title" class="col-sm-1 control-label">Title</label> <div class="col-sm-11"> <input type="text" class="form-control" id="title" name="title" value="{{ form.title.value }}"> </div> </div> <div class="form-group"> <label for="content" class="col-sm-1 control-label" >Content</label> <div class="col-sm-11"> <textarea class="form-control" id="content" name="content" rows="10" cols="30">{{ form.content.value }}</textarea> </div> </div> Unfortunately, the form is blank after I click the edit link: I test the code with if request.method == "GET": form = CommentForm(instance=article) print(vars(form.instance)) It print all the data {'_state': <django.db.models.base.ModelState object at 0x10c977438>, 'id': 1, 'owner_id': 1, 'block_id': 1, 'title': 'Time and Tide', 'content':....} What's the problem with my code to display form.field.value? -
Django MySql Database Synchronisation
I have built a Django application on a MySql database. The data for this application is read from an external (master) MySql database (which is an application database for a Druple webapp). The schemas of the two databases are very different, but all data on the local Django database is read in from the external database with some ETL in the middle. There are several updates to the external database daily. I have built a module to do a bulk upload to the local database for development with the necessary validations etc and using the Django models API. However, in production, I would like the local Django database to be updated whenever there is a change to the Drupal database, if it passes the validity tests (or a daily sync would also work) (My application has many data constraints that the Drupal developer did not include). I've had a look at MySql synchronisation tools. However, I am concerned to bypass the Django models API. Is there a way for me to poll the external database for changes, and write changes to the Django database using the Django models API? Or does it not matter if I bypass it? Is there … -
django.db.utils.IntegrityError: NOT NULL constraint failed. Where is the constraint is not respected?
I see some topics about this error but I don't find my answer in. here is my error: django.db.utils.IntegrityError: NOT NULL constraint failed: domain_analyse_practice.header_id I don't really understand why this error happens. My models.py: class Header(models.Model): name = models.CharField(max_length=40, null=False) description = models.CharField(max_length=500, null=False) class Practice(models.Model): nature = models.CharField(max_length=10, null=False) value = models.CharField(max_length=300, null=False) further = models.CharField(max_length=50, null=True, blank=True) header = models.ForeignKey(Header, on_delete=models.CASCADE) def value_cleaner(self): self.value = self.value.replace("‘","'").replace("’", "'") def __init__(self, *args, **kwargs): super(Practice, self).__init__() self.value_cleaner() And here is my init_db.py script wich is in charge of populate the database: def init_practice_db(filename): with open('config/' + filename, newline='') as csv_file: reader = csv.reader(csv_file, delimiter=',', quotechar='|') i = 0 for row in reader: if i != 0: # Not the header row header_name = row[0] # Select the header in database with header name header = Header.objects.get(name=header_name) further = None nature = row[1].rstrip() value = row[2].rstrip() if row[3] != "None": further = further Practice.objects.create(nature=nature, value=value, further=further, header=header) i += 1 If some information are missing let me know :) Thanks for you answers. -
django 403 Forbidden You don't have permission to access(window)
actually many people has same error. I try search and apply, but all solution fail. please help me I use apache + django in windows this is my htdoc.conf ... and my project C:\url\mysite\mysite\wsgi.py \po\views.py htdoc.conf LoadModule wsgi_module "C:/Users/Administrator/AppData/Local/Programs/Python/Python35-32/Lib/site-packages/mod_wsgi/server/mod_wsgi.cp35-win32.pyd" LoadFile "c:/users/administrator/appdata/local/programs/python/python35-32/python35.dll" WSGIPythonHome "c:/users/administrator/appdata/local/programs/python/python35-32" WSGIPythonPath "C:/urlconverter/mysite" ServerName 10.33.39.42 ServerAlias 10.33.39.42 WSGIScriptAlias / "C:/url/mysite/mysite/wsgi.py" <Directory "C:/url/mysite/mysite"> <Files wsgi.py> Order allow,deny Allow from all </Files> </Directory> -
Django IntegrityError When Updating an Object
I'm upgrading our project from python 2 to 3 and observing inconsistent behaviors regarding creating/saving objects with null values. Consider a CharField defined with default='' (and without null=True) On the python 2 branch, creating an object with that field set to None causes exception but once created, setting the field to None, then saving, works fine (though None is converted to '') On the python 3 branch, creating and updating with field=None for the same model causes exception (IntegrityError). I'm not sure what the expected behavior is, if a field doesn't define null=True, it makes sense to error out when updating that field with None. However, saving with None clearly has worked on the python 2 branch for a while now (several years)..unless that was a bug and not a feature? Anyone have run into the same issue before? note: Both branches have the same Django (1.9 for now, updating to 2 after python 3 conversion), same version of MySQL (5.7.22), python 2 branch runs on Ubuntu 14.04, and python 3 on 16.04. -
Related Object seriliazer Django restframework
My question is somewhat related to this one with some differences. I have a model similar to this one: class Project(models.Model): project_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) created_by_id = models.ForeignKey('auth.User', related_name='project', on_delete=models.SET_NULL, blank=True, null=True) created_by = models.CharField(max_length=255, default="unknown") created = models.DateTimeField(auto_now_add=True) With the following serializer: class ProjectSerializer(serializers.ModelSerializer): created_by = serializers.ReadOnlyField(source='created_by_id.username') class Meta: model = Project fields = ('project_id', 'created_by', 'created') And corresponding view: class projectsView(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): queryset = Project.objects.all() serializer_class = ProjectSerializer def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) def perform_create(self, serializer): serializer.save(created_by_id=self.request.user) This code behaves like I want but forces information redundancy and does not leverage the underlying relationnal database. I tried to use the info from the linked question to achieve a "write user id on database but return username on "get"" in a flat json without success: Removing the "created_by" field in the model. Replacing the serializer with: class UserSerializer(serializers.ModelSerializer): class Meta: model = User class ProjectSerializer(serializers.ModelSerializer): created_by = UserSerializer(read_only=True) created_by_id = serializers.PrimaryKeyRelatedField( queryset=User.objects.all(), source='created_by', write_only=True) class Meta: model = Project fields = ('project_id', 'created_by', 'created_by_id', 'created') Which would NOT 100% give me what I want, i.e. replace the user id with the username in … -
Django unable to upload to 777 permission folder
I got error message when upload file into media folder. I already have set everything to 777 permisson and change owner to apache. Loading media and static files are fine. I m using centos7 with httpd service. Please, help me to figure it out. The error looks like Here's the error message: Traceback: File "/opt/ezadmin/env/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/opt/ezadmin/env/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/opt/ezadmin/env/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/ezadmin/env/lib/python2.7/site-packages/django/contrib/admin/options.py" in wrapper 552. return self.admin_site.admin_view(view)(*args, **kwargs) File "/opt/ezadmin/env/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/opt/ezadmin/env/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/opt/ezadmin/env/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner 224. return view(request, *args, **kwargs) File "/opt/ezadmin/env/lib/python2.7/site-packages/django/contrib/admin/options.py" in change_view 1512. return self.changeform_view(request, object_id, form_url, extra_context) File "/opt/ezadmin/env/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "/opt/ezadmin/env/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/opt/ezadmin/env/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func 63. return func.__get__(self, type(self))(*args2, **kwargs2) File "/opt/ezadmin/env/lib/python2.7/site-packages/django/contrib/admin/options.py" in changeform_view 1409. return self._changeform_view(request, object_id, form_url, extra_context) File "/opt/ezadmin/env/lib/python2.7/site-packages/django/contrib/admin/options.py" in _changeform_view 1449. self.save_model(request, new_object, form, not add) File "/opt/ezadmin/env/lib/python2.7/site-packages/django/contrib/admin/options.py" in save_model 980. obj.save() File "/opt/ezadmin/env/lib/python2.7/site-packages/django/contrib/auth/base_user.py" in save 80. super(AbstractBaseUser, self).save(*args, **kwargs) File "/opt/ezadmin/env/lib/python2.7/site-packages/django/db/models/base.py" in save 808. force_update=force_update, update_fields=update_fields) File "/opt/ezadmin/env/lib/python2.7/site-packages/django/db/models/base.py" in save_base 838. … -
Facing bug while creating `User` object in Django, error "django.db.utils.IntegrityError: UNIQUE constraint failed: auth_user.username"
I'm getting error while creating User object: user_name=request.data.get('username') first_name=request.data.get('first_name') last_name=request.data.get('last_name') email=request.data.get('email') User.objects.create(username=user_name,first_name=first_name,last_name=last_name, email=email) Error django.db.utils.IntegrityError: UNIQUE constraint failed: auth_user.username When I try to add direct username it's working. User.objects.create(username='xyz', first_name=first_name,last_name=last_name, email=email) <User: xyz> Why it's happening? Am I doing something wrong? Thanks in advance. -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 6
Traceback (most recent call last): File "pandas\_libs\parsers.pyx", line 1134, in pandas._libs.parsers.TextReader._convert_tokens File "pandas\_libs\parsers.pyx", line 1240, in pandas._libs.parsers.TextReader._convert_with_dtype File "pandas\_libs\parsers.pyx", line 1256, in pandas._libs.parsers.TextReader._string_convert File "pandas\_libs\parsers.pyx", line 1494, in pandas._libs.parsers._string_box_utf8 UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 6: invalid start byte During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\Shivani\Anaconda3\lib\site-packages\django\core\handlers\exception.py", line 35, in inner response = get_response(request) File "C:\Users\Shivani\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Shivani\Anaconda3\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\MNNIT Python\Project1\crime1\views.py", line 11, in data data=pd.read_csv("C:/MNNIT Python/Project1/crime.csv") File "C:\Users\Shivani\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 678, in parser_f return _read(filepath_or_buffer, kwds) File "C:\Users\Shivani\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 446, in _read data = parser.read(nrows) File "C:\Users\Shivani\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 1036, in read ret = self._engine.read(nrows) File "C:\Users\Shivani\Anaconda3\lib\site-packages\pandas\io\parsers.py", line 1848, in read data = self._reader.read(nrows) File "pandas_libs\parsers.pyx", line 876, in pandas._libs.parsers.TextReader.read File "pandas_libs\parsers.pyx", line 891, in pandas._libs.parsers.TextReader._read_low_memory File "pandas_libs\parsers.pyx", line 968, in pandas._libs.parsers.TextReader._read_rows File "pandas_libs\parsers.pyx", line 1094, in pandas._libs.parsers.TextReader._convert_column_data File "pandas_libs\parsers.pyx", line 1141, in pandas._libs.parsers.TextReader._convert_tokens File "pandas_libs\parsers.pyx", line 1240, in pandas._libs.parsers.TextReader._convert_with_dtype File "pandas_libs\parsers.pyx", line 1256, in pandas._libs.parsers.TextReader._string_convert File "pandas_libs\parsers.pyx", line 1494, in pandas._libs.parsers._string_box_utf8 UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 6: invalid start by -
Return Files Using Django
I'm working on a project using django, the project is about a website that takes 2 file(user upload em) then the website return/sends back once the file is ready(user download em). Currently, this is what I have in my views.py from django.shortcuts import render from django.http import HttpResponse import difflib import datetime from django.http import HttpResponseRedirect from .forms import FileForm from .forms import UploadFileForm # Create your views here. def handle_uploaded_file(file1,file2): print(file1) # with open(file1, 'r') as t1, open(file2, 'r') as t2: # here i open 2 files and make python read it fileone = file1.readlines() # read lines from 1st file filetwo = file2.readlines() # read lines from 2nd file fileone =[line.decode("utf-8").strip() for line in fileone] filetwo =[line.decode("utf-8").strip() for line in filetwo] # print(fileone,filetwo) with open('difference.csv', 'w') as outFile: # create output file called with update.csv for line in filetwo : #for statement # print(line) if line not in fileone : # if line is not same print(line) outFile.write(line+"\n") def index(request): if request.method == 'POST': print(request.FILES) form = UploadFileForm(request.POST, request.FILES) print(form.errors) if form.is_valid(): print("cool") handle_uploaded_file(request.FILES.get('file1'),request.FILES.get('file2')) return HttpResponseRedirect('results/') else: form = UploadFileForm() return render(request, 'hello.html', {'form': form}) from django.utils.encoding import smart_str def results(request): response = HttpResponse(content_type='difference.csv/force-download') response['Content-Disposition'] = 'attachment; filename=%s' … -
Django - django_tables2 and django-filters
I am working with these links example1 and example2 for displaying django tables from database and filter the results but i feel these examples are incomplete and I have not produced the desired results. Can someone share the complete code for this or any help? Thanks in advance -
Django decimal SyntaxError: invalid syntax error in views.py file
I searched the related questions on the web however I couldn't find any answer for me. I have a model.py like this; import datetime from django.db import models from django.utils import timezone class Product(models.Model): product_name = models.CharField(max_length=200) product_price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.product_name and I have a views.py like this; from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, render from django.urls import reverse from django.views import generic from django.utils import timezone from .models import Product from decimal import * def create_new_product(request): new_product = Product( product_name = 'test', product_price = 10.2, ) new_product.save() return new_product class IndexView(generic.ListView): #some code here# class DetailView(generic.DetailView): #some code here# After I run the server, I am getting the following error; product_price = 10.2, ^ SyntaxError: invalid syntax Basically, I am trying to create a product which will be eventually inserted into the database. Please help me on this. Thank you. -
How can I access the model objects after annotating a QuerySet
I have a QuerySet where I annotate the datefield and that works just fine. see my code below. tenderSet = userTenders.annotate(d_assigned=TruncDay('date_assigned')).values('d_assigned').annotate(c=Count('id')).values('d_assigned', 'c').order_by("-d_assigned") And this is the output. My problem is that I want to be able to click on the links in the image and see the actual objects. For example, if click on the link that says "2 tenders" in the image above, I would like to have access to the "tender" objects associated with that annotation. But unfortunately because my annotation above returns a QuerySet of "dictionaries" i am unable to access the model objects. I need to know if there is a way to keep the look of the listView above and still be able to access the annotated tender objects. Thank you. -
running a function to load csv data into the DB via Django
This should be like nobrainer question., but it intrigues me. I want to load a roster of countries into the database and yes, I know I could easily do it directly by importing the csv either in mysql or postgres, and I could also write the code snippet into the console (very inconvenient) and would work fine, but I wonder how you do it in django. Because, if I have this: def loadccountries(): with open(uploads/countries.csv) as f: reader = csv.reader(f) for row in reader: _,created = countries.objects.get_or_create( name = row[0] ) then, where do I place that code?, in the views? if yes, then, how do I make that function alone run? I cannot see myself creating artificial urls in urls.py and an html page so that I can call the view from the URL etc. Dont vote me down, I am struggling not to go below 23 score. -
Error while running the server in django project
C:\Python27\python.exe "C:/Users/Priyanshu kumar/Desktop/website/manage.py" runserver Traceback (most recent call last): File "C:/Users/Priyanshu kumar/Desktop/website/manage.py", line 8, in <module> from django.core.management import execute_from_command_line ImportError: No module named django.core.management Process finished with exit code 1 -
Benefits of using Django framework over Zend framework?
I have an existing system based on the Zend framework, but now I want to move that to a better one in terms of Security, Optimization, Robust, Reliability, Performance and cost. I choose Django to move on with the language Python to make it. Its a website. Please tell me if it gonna make any difference or not, if yes then how. Or if you have any other suggestions to do that then, please. Thanks -
unable to save a form with the django user as a foreign key
I have a model called Post and i want to submit model class Post(models.Model): link = models.CharField(...) creator = models.ForeignKey( User, blank=False, null=False, on_delete = models.CASCADE, ) content = models.TextField(...) img = models.ImageField(...) created = models.DateTimeField(...) form class publications(forms.ModelForm): class Meta: model = Post fields = ['link', 'content', 'img', 'creator'] view if request.method == 'POST': if 'publication' in request.POST: commentform = commentaires(request.POST, request.FILES or None) pubform = publications(request.POST, request.FILES or None) conent_post = request.POST.get('content') link_post = request.POST.get('link') img_post = request.POST.get('img') if pubform.is_valid(): pub = pubform.save(commit=False) pub.creator_id = request.user.id pub.content = conent_post pub.link = link_post pub.img = img_post pubform.save() return redirect('com_index') else: return redirect('index') If the post doesn't submit it will redirect to the index and if it does submit it redirects to the com_index but everytime i submit I get redirected to the index page , any help ? -
Exclusively restricting .py to read certain lines when sending query from html frontend
I have a .py file in which I read data from various sources and applied some logics and came up with a final output data. Now I created a html form which ask for an input and when user gives input it searches for the output file in .py file and return the row entries corresponding to that input value. Now the problem is everytime when user gives an input , it executes all my .py file at backend which causes lot of time to display result on html page which is connected with my .py. Suppose I have below code: #Importing Libraries import pyodbc import pandas as pd from bs4 import BeautifulSoup import requests from itertools import zip_longest import re import numpy as np import csv from IPython.display import display, HTML import xlrd import smtplib, os, cgi from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText #imported necessary drivers and established connection with database [x for x in pyodbc.drivers() if x.startswith('Microsoft Access Driver')] conn_str = ( r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};' r'DBQ=C:\\Users\\test.accdb;' ) cnxn = pyodbc.connect(conn_str) crsr = cnxn.cursor() for table_info in crsr.tables(tableType='TABLE'): print(table_info.table_name) #Read abc data from datbase sql= "SELECT * from abc" RMA = pd.read_sql(sql,cnxn) After the above … -
Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432?
I tried to deploy my Django project on Heroku but everytime I try 'heroku run python3 manage.py migrate' I get this error: /app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. """) Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 168, in get_new_connection connection = Database.connect(**conn_params) File "/app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 79, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/loader.py", line … -
Check(conditional) if the current url is the same with a url declared in path
In the main urls.py I have: urlpatterns = [ path('items/', include('items.urls', namespace='items')), .... ] In items urls.py I have: urlpatterns = [ path('item/add/', ItemCreateView.as_view(), name='create_item'), ] I want to check in a view/dispatch() if the current page url is the same with the one in the path, something like: if self.request.path == 'items:create_items' -
How do I deal with POST 403 error with React Native
My friend and I have faced a lot of errors while building up Hybrid app. We've used React Native as Frontend and django rest framework as backend Worst of them is 403 error when we post json file from React native to django rest framework. when we first made POST, It worked! but 403 error started to raise after moving our place. we used AWS and apapche2. and I set permission as Allowany that means anyone can access api and do GET, POST and DELETE. fronted code is like this let data = JSON.stringify({ username:"fuckingbitch", }); console.log(data) fetch(http://52.78.216.37:8080/api/users/, { method:'POST', headers: { 'Content-Type':'application/json', }, body:data, }) .then(result => console.log('success====:', result)) .catch(error => console.log('error============:', error)) } we guess apache has some problem about permission ! please help us !!!!