Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting error by Django insert queries caused by duplicates
I am trying to add some data to a table (made in Django) How can I avoid de error caused by duplicates? class Prefixe(models.Model): remote_as = models.CharField(max_length=250) prefix_list = models.CharField(max_length=250, unique=True) def insert(): p = Prefixe(remote_as='Apress', prefix_list='Berkeley') p.save() If I don't use object oriented, I can fix it with postgres: INSERT INTO "peer_table" ("remote_as","prefix_list")VALUES('{}','{}')ON CONFLICT DO NOTHING""" Right now I get an error when duplicates -
Multiple Objects Returned Exception when entering wrong password in Django
I am using cookie cutter Django and on the url http://localhost:8000/accounts/login/ whenever I enter a wrong password I am getting the following traceback and a 500 Internal Server Error on the network console. I am using sqlite database. I am not able to understand why I am getting this error because when I create an empty project using the same database no such error is thrown. Environment: Request Method: POST Request URL: http://localhost:8000/accounts/login/ Django Version: 2.1.4 Python Version: 3.6.7 Installed Applications: ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'crispy_forms', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_framework', 'widget_tweaks', 'core.users.apps.UsersAppConfig', 'core.userManagement.apps.UsermanagementConfig', 'debug_toolbar', 'django_extensions'] 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', 'debug_toolbar.middleware.DebugToolbarMiddleware'] Traceback: File "/home/power/Documents/Projects/core/venv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/power/Documents/Projects/core/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/home/power/Documents/Projects/core/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/power/Documents/Projects/core/venv/lib/python3.6/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/home/power/Documents/Projects/core/venv/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "/home/power/Documents/Projects/core/venv/lib/python3.6/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs) File "/home/power/Documents/Projects/core/venv/lib/python3.6/site-packages/allauth/account/views.py" in dispatch 137. return super(LoginView, self).dispatch(request, *args, **kwargs) File "/home/power/Documents/Projects/core/venv/lib/python3.6/site-packages/allauth/account/views.py" in dispatch 80. **kwargs) File "/home/power/Documents/Projects/core/venv/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/home/power/Documents/Projects/core/venv/lib/python3.6/site-packages/allauth/account/views.py" in post 102. if form.is_valid(): File "/home/power/Documents/Projects/core/venv/lib/python3.6/site-packages/django/forms/forms.py" in is_valid 185. return … -
How to iterate formsets with inline structure
I face up with the problem of inability to iterate through my formsets. I have already create an inline structure between Client model(form) and Phone model(formset). My aim is to be able to store more than one phone for each client. The issue is that despite the fact that I can create more than one inlines, when it comes the phase of storing, my code only stores the last phone and not each phone as expected. models.py class Client(models.Model): name = models.CharField(max_length=50, verbose_name="Όνομα") surname = models.CharField(max_length=50, verbose_name="Επίθετο") amka_amesa = models.BigIntegerField( validators=[MaxValueValidator(99999999999)],null=True,blank=True, verbose_name="AΜΚΑ Άμεσα Ασφαλισμένου") amka_emesa = models.BigIntegerField( validators=[MaxValueValidator(99999999999)], unique=True, null=True, blank=True, verbose_name="ΑΜΚΑ Έμεσα Ασφαλισμένου") am_asfa = models.CharField( max_length=11, validators=[RegexValidator(r'^\d+$')], null=True, blank=True, verbose_name="Α.Μητρώου Ασφαλισμένου") address = models.CharField(max_length=100, null=True, blank=True, verbose_name="Διεύθυνση") ika_branch = models.ForeignKey(Client_IKA_Branch, null=True, blank=True, verbose_name=u'Υποκατάστημα Ασφαλισμένου') notes = models.CharField(max_length=100, null=True, blank=True, verbose_name="Σημειώσεις") #active field=1 #inactive field=0 INACTIVE, ACTIVE = range(0, 2) ACTIVITY_OPTIONS = ( (INACTIVE, 'Ανενεργός'), (ACTIVE, 'Ενεργός'), ) activity = models.IntegerField(choices=ACTIVITY_OPTIONS, null=True,default=ACTIVE) class Phone(models.Model): MOBILE, WORK, HOME = range(0, 3) CATEGORIES = ( (MOBILE, 'Κινητό'), (WORK, 'Δουλειά'), (HOME, 'Σπίτι'), ) number = models.CharField(max_length=14, null=True) category = models.IntegerField(choices=CATEGORIES, null=True,default=MOBILE) client = models.ForeignKey(Client, null=True) def __unicode__(self): return self.number def get_absolute_url(self): return reverse('client_list') forms.py class ClientForm(ModelForm): class Meta: model = Client exclude=('activity',) … -
How to send dict of dict from Django to javascript
I want to send data from Django to JavaScript so I can write all logic in JS + Vue and keep html clean. In Django I have context={'names':{'fn':'john','ln':'cena'}} return render(request,'app/page1.html',context) in page1.html template I have <script type="text/javascript"> var names="{{names}}"; </script> In javascript how can I access names.fn & names.ln ? I have two more related questions: Is this a preferred Django way to send data directly from Django to JS when template is rendered. (The only other method I know is through Ajax call. Here I dont want to do additional Ajax call after the page is rendered) From security stand point, is it better to keep Django data related logic {% if x > y %} inside templates or is it ok to move the logic part to JS + Vue and just keep data structure in the template. I ask this because when i check page source in a browser window, I can see entire JS code but I cannot see anything that's inside a Django condition statement in html : {% if x>y %} ----THIS IS INVISIBLE IN A BROWSER---- {% endif %} Thanks -
Combine a queryset with a newly created object
There is a new object (not yet saved): obj = MyObject() q = MyObject.objects.all() Is there any way to combine obj and q? -
How to store data in database from views.py Django?
This is my models: class ledger1(models.Model): name = models.CharField(max_length=32) Closing_balance = models.DecimalField(max_digits=10,decimal_places=2,blank=True,null=True) class journal(models.Model): Date = models.DateField(default=datetime.date.today) By = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Debitledgers') To = models.ForeignKey(ledger1,on_delete=models.CASCADE,related_name='Creditledgers') Debit = models.DecimalField(max_digits=10,decimal_places=2,null=True) Credit = models.DecimalField(max_digits=10,decimal_places=2,null=True) And in my views I have done this: qscb = journal.objects.filter(User=request.user, Company=company_details.pk, By=ledger1_details.pk, Date__gte=selectdatefield_details.Start_Date, Date__lte=selectdatefield_details.End_Date) qscb2 = journal.objects.filter(User=request.user, Company=company_details.pk, To=ledger1_details.pk, Date__gte=selectdatefield_details.Start_Date, Date__lte=selectdatefield_details.End_Date) total_debitcb = qscb.aggregate(the_sum=Coalesce(Sum('Debit'), Value(0)))['the_sum'] total_creditcb = qscb2.aggregate(the_sum=Coalesce(Sum('Credit'), Value(0)))['the_sum'] if(ledger1_details.group1_Name.balance_nature == 'Debit'): closing_balance = opening_balance + total_debitcb - total_creditcb else: closing_balance = opening_balance + total_creditcb - total_debitcb I want to store the value of 'closing_balance' into my model field named 'Closing_Balance'....And automatically update it when any changes are made... Any idea anyone how it is possible in django? Thank you -
Download Static Files by name Django
I am new to Django and am creating a site where user uploads a file (test.png etc). The file is then processed and a new file (test.csv) is created in the local directory. ../django/myproject/mysite/csv/test.csv Users can keep uploading files and more .csv files are created. A result page will show the .csv files and the user can download those files. However, I'm confused as I can't download them. views.py def make_csv(request): ... csv_filename = str(in_csv_file) #send to result page return render(request,'thesite/results.html', {"csv_filename": csv_filename}) views.py (same as above file) def download_csv(request, csvfile): path = os.path.join(SETTING_DIR) filename = path + csvfile + ".csv" filewrapper = FileWrapper(open(filename, 'rb')) response = HttpResponse(filewrapper, content_type='text/csv') response['Content-Length'] = os.path.getsize(filename) response['Content-Disposition'] = 'attachment; filename="{}"'.format(csvfile +".csv") return response results.html <tbody> <tr> <td></td> <td>{{csv_filename}}</td> <td><a href='/thesite/download_csv/{{csv_filename}}' do i add something here? >Download</a></td> </tr></tbody> urls.py urlpatterns = [ ... path('results/', views.results, name='results'), path('download_csv/(?P<csvfile>.+)$/', views.download_csv, name='download_csv'), or do I add smt here??] I'm sorry if my question is unclear. Thank you for your help. -
The parameters are escaping in href in an activation email Django 2.0
I am sending an activation email but in the email the link seems to be escaped, showing as follows. http://localhost:8000/activate/b&#39;MzIw&#39;/token--here/ Where it should be http://localhost:8000/activate/b'MzIw'/token--here/ In urls.py re_path(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.....)/$', views.activate, name="activate"), The token is displaying as it is but the uidb64 is escaping. What's wrong here? -
React axios CSRF 403 FORBIDDEN when deploying django to DigitalOcean
The following action creator setup works just fine locally. However, when deploying the site in DigitalOcean I keep getting CSRF 403 FORBIDDEN and thus, fails to authenticate the user. ERROR -> POST https://app-machinespector.com/auth/signin/ 403 (Forbidden) Action creator that authenticates user. I'm loading the cookie but not using it anywhere (since it's not necessary). It's value is undefined... import axios from 'axios'; axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = 'X-CSRFToken'; import { browserHistory } from 'react-router'; import cookie from 'react-cookie'; import { AUTH_USER, } from './types'; # load and print cookie --> undefined const csrftoken = cookie.load('csrftoken'); console.log(csrftoken); export function signinUser({email, password}){ return function(dispatch){ axios.post('/auth/signin/', { email, password }) .then(response => { dispatch({ type: AUTH_USER }); localStorage.setItem('token', response.data.token); browserHistory.push('/machines'); }) .catch(() =>{ dispatch(authError('Log in credentials are invalid')); }); } } Django production settings: from .base import * # noqa DEBUG = False # SECRET CONFIGURATION # ------------------------------------------------------------------------------ # See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key # Raises ImproperlyConfigured exception if DJANGO_SECRET_KEY not in os.environ SECRET_KEY = env('DJANGO_SECRET_KEY') # ALLOWED_HOSTS # ------------------------------------------------------------------------------ ALLOWED_HOSTS=["app-machinespector.com", "localhost", "127.0.0.1"] # CSRF # ------------------------------------------------- CSRF_USE_SESSIONS = False CSRF_COOKIE_HTTPONLY = False CSRF_COOKIE_NAME = 'csrftoken' CSRF_HEADER_NAME = 'X-CSRFToken' # WEBPACK CONFIGURATION # ------------------------------------------------------------------------------ WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'bundles/prod/', # end with slash 'STATS_FILE': str(ROOT_DIR.path('webpack-stats-prod.json')), … -
ModuleNotFoundError at /auth/complete/google-oauth2/
Hi I am currently struggling with my social-auth-django as it keeps giving me ModuleNotFoundError at /auth/complete/google-oauth2/ No module named 'social_auth' When I click the login button, It redirects to the google authentication perfectly, yet After entering my credentials, and when it redirects to my website it kept giving me that error message :") I am new to the web development Environment and I'll be glad if anyone can help :D Thank you Here is also a segment of my code (settings.py) AUTHENTICATION_BACKENDS = ( 'social_core.backends.open_id.OpenIdAuth', # for Google authentication 'social_core.backends.google.GoogleOpenId', # for Google authentication 'social_core.backends.google.GoogleOAuth2', # for Google authentication 'django.contrib.auth.backends.ModelBackend',) SOCIAL_AUTH_PIPELINE = ( 'social_auth.backends.pipeline.social.social_auth_user', 'social_auth.backends.pipeline.associate.associate_by_email', 'social_auth.backends.pipeline.user.get_username', 'social_auth.backends.pipeline.social.associate_user', 'social_auth.backends.pipeline.social.load_extra_data', 'social_auth.backends.pipeline.user.update_user_details', 'social_auth.backends.pipeline.user.create_user') -
Simple site search django
I'm trying to create a simple search for products in the online store. I watched tutorials and read questions here. I tried to do it. Nothing succeeded. What did I do wrong? view.py from django.shortcuts import render, get_object_or_404, render_to_response from django.db.models import Q from cart.forms import CartAddProductForm from .models import Category, Product # Product page def ProductList(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) query = request.GET.get('q') if query: return Product.objects.filter(title_icontains=query) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) return render(request, 'product/list.html', { 'category': category, 'categories': categories, 'products': products }) def ProductDetail(request, id, slug): product = get_object_or_404(Product, id=id, slug=slug, available=True) return render(request, 'product/detail.html', {'product': product}) def ProductDetail(request, id, slug): product = get_object_or_404(Product, id=id, slug=slug, available=True) cart_product_form = CartAddProductForm() return render(request, 'product/detail.html', {'product': product, 'cart_product_form': cart_product_form}) product\list.html <form method="get" action=""> <div class="row"> <div class="col"> <input type="text" name="query" placeholder="search..." value="{{request.get.q}}"/> <input type="submit" value="search"/> </div> </div> </form> -
Django update the row if its existing
I have a model say, class ABC(models.Model): x = models.CharFeild(max_length=100) y = model.IntegerFeild(default=1) and another model is, class XYZ(models.Model): a = models.CharFeild(max_length=100) abc = model.ForeignKey(ABC, db_index=True) and my existing database looks like, ABC id x y 1 a 10 2 b 20 3 c 30 . . . . . . XYZ id a abc_id 1 x 1 2 y 2 3 z 3 . . . . . . So now I want to update the field if its exist in model XYZ i.e., change column 'a' value where abc_id=1 or 2 or 3, and if that abc_id doesn't exist create a new row. -
How to send emails through Django using private domain email address?
# Email Setting EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # Host for sending e-mail. EMAIL_HOST = 'localhost' # Port for sending e-mail. EMAIL_PORT = 1025 # Optional SMTP authentication information for EMAIL_HOST. EMAIL_HOST_USER = 'test@ex.com' EMAIL_HOST_PASSWORD = '123' EMAIL_USE_TLS = False if there any additional setting to send email private domain -
How do i get the footer to stay at the bottom with flexbox
This is my css that i am using on the base template so other templates will inherit it. body { font-family: Raleway, sans-serif; } header{ background-image: linear-gradient(to bottom, #1a1c1b, #1c2d25, #1b4030, #15533a, #046644); padding: 1.5em 1em; } header h1 { margin: 0; font-size: 2em; font-weight: bold; } section a { padding-left: 10px; padding-right: 10px; } .container{ max-width: 1200px; margin: 0 auto; } .header-top{ display: flex; justify-content: space-between; font-weight: bold; align-items:center; color: white; } header a{ color: white; padding-left: 5px ; padding-right: 5px; } a{ text-decoration: none; } .footer-bottom { display: flex; justify-content: space-between; color: white; } footer { background-image: linear-gradient(to bottom, #1a1c1b, #1c2d25, #1b4030, #15533a, #046644); padding: 1.5em 1em; position:inherit; bottom:0; width:100%; height:60px; /* margin-top: -40px; */ } footer a { color: white; padding: 0px; } footer p { margin: 0px; } HTML: there are some django links in it . {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title> Startup Organizer </title> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!--[if IE]><script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"> </script><![endif]--> <link rel="stylesheet" href="{% static 'site/style.css' %}"> <link rel="stylesheet" href="{% static 'site/normalize.css' %}"> <link rel="stylesheet" href="{% static 'site/skelton.css' %}"> {% block head %} {% endblock %} </head> <body> <div class="container"><!-- container --> <div class="status … -
django: signin form is not valid
I'm trying to define a signin function to signin my user, but when clicking the button "Ingresar" (Signin in spanish) nothing happens. I've tried to debug this and in my function def signinView(request): I've notice that Django never reaches the condition if form.is_valid():, so apparently my form isn't valid. I don't know why? *It never prints "Hola3", only "Hola" and "Hola2". views.py def signinView(request): print("Hola") if request.method == 'POST': print("Hola2") form = AuthenticationForm(request.POST) if form.is_valid(): print("Hola3") username = request.POST['username'] password = request.POST['password'] print(username) print(password) user = authenticate(username = username, password = password) if user is not None: login(request, user) return redirect('shop:allProdCat') else: return redirect('signup') else: form = AuthenticationForm() return render(request, 'accounts/signin.html', {'form':form}) html: <div class="col-12 col-sm-12 col-md-12 col-lg-6 bg-light"> <div> <br> <h2 class="my_title"> Solo usuarios registrados </h2> <form method="post"> {% csrf_token %} <p>{{ form | crispy }}</p> <button type='submit' class="btn btn-secondary">Ingresar</button> </form> <br> </div> </div> urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name = 'index'), path('shop/', include('shop.urls')), path('cart/', include('cart.urls')), path('order/', include('order.urls')), path('account/create/', views.signupView, name = 'signup'), path('account/login/', views.signinView, name = 'signin'), path('account/logout/', views.signoutView, name = 'signout') ] -
How can I pass the custom AuthentificationForm in login in Django 2.1.4
I changed Django to 2.1.4 from 1.11 and couldn't work around how to set the custom AuthentificationForm in auth_login. url(r'^login/$', django.contrib.auth.views.login, { 'template_name': 'login.html', 'authentication_form': forms.CustomAuthenticationForm, }, name='login'), In views.py, from django.contrib.auth.forms import AuthenticationForm class CustomAuthenticationForm(AuthenticationForm): ... It seems the Django 2.1.4 LoginView accepts the template only. How can I go through without writing a view for this view? -
Django test database username
I am starting a Django project and I am using gitlab's ci/cd on the shared runners and I use Postgres as the database. I have this weird problem that it seems like Django is creating the test database with the username "postgres" and I can't find a way to configure it's setting and change it to use the role named "runner". This causes a break in my ci/cd pipeline. here is my .gitlab-ci.yml: image: python:3.6.5 services: - postgres:latest variables: POSTGRES_DB: asdproject POSTGRES_USER: runner POSTGRES_PASSWORD: asdpassword test: script: - whoami - export DATABASE_URL=postgres://postgres:@postgres:5432/asdproject - export PGPASSWORD=$POSTGRES_PASSWORD - apt-get update -qy - apt-get install -y python-dev python-pip - pip install -r requirements.txt - python manage.py test - settings=asd.gitlab_runner_settings and my gitlab_runner_settings.py file: I tried many forms of changing settings.py that were recommended in questions but neither worked. from asd.with_debug_settings import * import sys DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'asdproject', 'USER': 'runner', 'PASSWORD': 'asdpassword', 'HOST': 'postgres', 'PORT': '5432', 'TEST': { 'NAME': 'asdtest', 'USER': 'runner' }, } } The error I get while running my pipeline script in gitlab is: --------------------------------------------------------------------- Ran 0 tests in 0.000s OK Using existing test database for alias 'default'... System check identified no issues (0 silenced). … -
Javascript array to Django many to many field
Ok, so I have a Django form with Area and Subarea. The subarea input is a ManytoManyField (Not every area is a subarea but all subarea is an area), but I have to style it in the frontend in a way that I can add and remove elements from a text input before I submit the form. I have already implemented a js function that collects all subareas in an array, i would like to know how can i pass this array to Django, so it can go to the Subarea field and save it. -
I cannot create a virutal enviroment using virtualenv
Virtualenv problem I am watching a tutorial in YouTube ~> https://www.youtube.com/watch?v=3TqO5FfhV28&t=868s&list=LLGGkVh7THuKVM6vp_zFE8Bg&index=2 The exact minute I am having trouble is @ 12:41... Please,please anyone knows what I am doing wrong ? -
django rest framework - POST request causes 400 status code
I am trying to perform a POST request to create an article and I am getting this error Request failed with status code 400. An article needs 3 attributes to be created: (1) title (2) body (3) author (the current user) The router works fine since the POST request goes into the post method of the ArticleCreateView class. But the serializer = ArticleSerializer(data=request.data) doesn't invoke the create method of the ArticleSerializer class for some reason. I can see the output of print('inside the post method') in the Terminal. But I cannot see the output of print('inside the create method'). Another mystery about Django is, how does the serializer know if I want to get, create or update something? In all the examples I've seen, the serializer magically seems to know this. class ArticleCreateView(CreateAPIView): permission_classes = [IsAuthenticated] def post(self, request): print('inside the post method') serializer = ArticleSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors) class ArticleSerializer(serializers.ModelSerializer): class Meta: model = Article fields = '__all__' def create(self, validated_data): print('inside the create method') author = self.context['request'].user title = validated_data.get('title') body = validated_data.get('body') return Article.objects.create(author=author, title=title, body=body) -
Creating plain API which accepts files
I am building an API which accepts file and validates it, sends json response (not storing the file in db, so no need of model). I have created a class based view, in post function, request.FILES or request.POST doesn’t contain the file… If I make a form class, it will work. But, I don’t want any UI, it should be a simple API. Anyone knows how to do it? class ValidateView(View): def get(self, request, *args, **kwargs): pass def post(self, request, *args, **kwargs): file = request.FILES if not file: return JsonResponse({"status_code": "400", "message": "a file is required", "status_response": "Bad Request"}) return JsonResponse({"status_code": "200", "message": "data validated", "status_response": "Success"}) @csrf_exempt def dispatch(self, request, *args, **kwargs): return super(ValidateView, self).dispatch(request, *args, **kwargs) I used djangorestframework and come up with this class ValidateView(views.APIView): parser_classes = (FileUploadParser,) def post(self, request, filename, format=None): file_obj = request.data['file'] if is_csv_valid(file_obj): return Response(status=200, data={"message": "valid file"}) else: return Response(status=400, data={"message": "not valid"}) But, here the problem is I must build a url like this re_path("validate/(?P<filename>[^/]+)$", ValidateView.as_view(), name="api-validate") If I exclude filename in url, it throws an error. Also, file_obj contains some extra lines (Content-Type) along with original data. Someone help!!! -
Can't runserver on Django
I just started playing with Django, and I encountered a problem. Here's what it said when I tried to runserver. ImproperlyConfigured: The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. Here's what I did. On setting.py: INSTALLED_APPS = [ 'Siblog.apps.SiblogConfig', 'django.contrib.admin', 'django.contrib.auth',**strong text** 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Project urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('Siblog.urls')), ] Siblog urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.home, name='Siblog-home'), ] Siblog views.py: from django.shortcuts import render def home(request): return render(request, 'Siblog/home.html') Also the template I've created inside of the Siblog file: <!DOCTYPE html> <html> <head> <title></title> </head> <body> <h1>Siblog Home!</h1>> </body> </html> -
Searching Across Django Models against Search Form Query
I've been reading up on Django forms and am stumped on how to proceed. I'm creating a forms.py with the aim that at the form level, a user can input a string query, and this query is then run against one of the models, depending on which one is selected from a drop-down on the form. Something like the following in HTML: <div class="row"> <form class="col s12"> <div class="row"> <div class="input-field col s6" > <input type="text" class="validate" list="option"> </div> <option value="1">model 1</option> <option value="2">model 2</option> <option value="3">model 3</option> </select> So essentially the query should be run against the appropriate model in views.py. Each model has its own view function. Also, how should I structure my urlconf to account for this? -
Django Unexpected 405 Response
Problem My django application often respond 405 Method Now Allowed even though it's working api on development environment. But if i restart development server (python manage.py runserver) It works. Environment macOS Mojave 10.14 Python 3.6.4 (Isolated environment via Pipenv) Django 2.1.4 djangorestframework 3.8.2 API Code settings/urls.py (root url file) from django.urls import path, include import my_account.urls urlpatterns = [ path('account/', include(my_account.urls, namespace='account_v1')), ] my_account/urls.py from django.urls import path from .apps import MyAccountConfig from .views import TokenView app_name = MyAccountConfig.name urlpatterns = [ path('token/', TokenView.as_view()), ] my_account/views.py from rest_framework.views import APIView class TokenView(APIView): def post(self, request): # Some Business-Logic Code pass Log Log when 405 occured System check identified no issues (0 silenced). December 07, 2018 - 11:22:54 Django version 2.1.4, using settings 'my_server.settings.staging' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. .env Applied [07/Dec/2018 11:24:30] "OPTIONS /account/token/ HTTP/1.1" 200 0 [07/Dec/2018 11:24:30] "{"email":"email@hidden.com","password":"hidden_password"}POST /v1/account/token/ HTTP/1.1" 405 66 Log when working System check identified no issues (0 silenced). December 07, 2018 - 11:48:01 Django version 2.1.4, using settings 'my_server.settings.staging' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. .env Applied [07/Dec/2018 11:48:08] "OPTIONS /account/token/ HTTP/1.1" 200 0 [07/Dec/2018 11:48:09] "POST /account/token/ HTTP/1.1" 200 517 In chrome network tab, … -
Django equivalent to SQLAlchemy ORM events
Is there a built-in equivalent, or library, that matches the features of SQLAlchemy ORM events for the Django ORM? I'm interested in hooking into the Django ORM like the before-compile event allows. I want to modify a Django ORM queryset before it is executed.