Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Django Forms and Models
I have a function based view: @login_required def profile(request): if request.method == 'POST': form = IngredientForm(request.POST, user=request.user) if form.is_valid(): form.save() ingredient_1 = form.cleaned_data['ingredient_1'] ingredient_2 = form.cleaned_data['ingredient_2'] ingredient_3 = form.cleaned_data['ingredient_3'] ingredient_4 = form.cleaned_data['ingredient_4'] ingredient_5 = form.cleaned_data['ingredient_5'] messages.success(request, f'Ingredients added to your account!') return redirect('profile') else: form = IngredientForm(user=request.user) return render(request, 'users/profile.html', {'form': form}) and the model is: from django.db import models from django.contrib.auth.models import User class ingredients(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) ingredient_1 = models.CharField(max_length=32) ingredient_2 = models.CharField(max_length=32) ingredient_3 = models.CharField(max_length=32) ingredient_4 = models.CharField(max_length=32) ingredient_5 = models.CharField(max_length=32) forms.py looks like: class IngredientForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(IngredientForm, self).__init__(*args, **kwargs) class Meta: model = ingredients fields = ('ingredient_1', 'ingredient_2', 'ingredient_3', 'ingredient_4', 'ingredient_5') I am trying to get the current user and use that as the key for the ingredients table in my database. I am not sure how to get the current user and set the user in the table as the current user. Any help would be appreciated :) The error that I get when I submit the form is: -
Cannot Export Django models in Openpyxl
here is my code from django.http import HttpResponse from openpyxl import Workbook from .models import Donor def export_to_excel(request): excel_data = [ ['First Name', 'last Name', 'Email', 'Address','City', 'State', 'Zip','Superdonor', 'Occupation'], [Donor.objects.all()] ] if excel_data: wb = Workbook(write_only=True) ws = wb.create_sheet() for line in excel_data: ws.append(line) response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=Donor_List.xlsx' wb.save(response) return response The Models form from django.db import models from django import forms from localflavor.us.models import USStateField, USZipCodeField # Create your models here. class Donor(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField(max_length=254) address = models.CharField(max_length=30) city = models.CharField(max_length=30) state = USStateField() zip = USZipCodeField() superdonor = models.BooleanField(default=False) occupation = models.CharField(max_length=50, blank=True) about = models.TextField(max_length=1000, blank=True) def __str__(self): return ("%s %s" % (self.first_name, self.last_name)) I am trying to loop through the model and have it list everything in the database. Any help is greatly appreciated. Without looping though the database the Excel sheet will generate but I need to export the entire database. -
Django admin failing to login after upgrade to 2.1
After upgrading an old Django 1.8 to 2.1, when I try to login on my admin site, I get a 404 with message: Using the URLconf defined in <mysite>.urls, Django tried these URL patterns, in this order: [...] The current path, login/, didn't match any of these. Which I guess is true because it should be on __admin/login as in my urls.py I have: urlpatterns = [ ... path(r'__admin/', admin.site.urls), ... ] But: The GET request /__admin/login returns the login page as expected The problem happens only in production (with passenger WSGI on a VPS), not on localhost Unfortunately the upgrade happened at the same time as a migration in VPS machine so there may also be a problem with the database. -
Related model ID gets lost in validated_data even though it is present in request
I am working on my create() method for my webapp which uses Django REST framework for the backend API. In this case, I'm trying to create a new RECIPE, which has a foreignkey field to a related model STYLE... I am running into an issue when trying to associate my new recipe record with an existing related object via the ID. My serializers looks like this: class StyleSerializer(serializers.ModelSerializer): http_method_names = ['get'] class Meta: model = Style exclude = () class RecipeSerializer(serializers.ModelSerializer): hops = HopAdditionSerializer(many=True, read_only=True) fermentables = FermentableAdditionSerializer(many=True, read_only=True) style = StyleSerializer() yeast = YeastSerializer(read_only=True) class Meta: model = Recipe exclude = () def create(self, validated_data): style_data = validated_data.pop('style') style = Style.objects.get(pk=style_data.get('id')) reipce = Recipe.objects.create(**validated_data) recipe.style = style recipe.save(); return recipe You can see I'm trying to assign the new recipe object with a related Style object. On my POST request for a new recipe, I include the style, which is all of the related attributes including the field ID. I have verified this info is getting POSTED both in the request via dev console AND in the django viewset via terminal log. However, in my serializer create() method, the ID value is always missing from the dictionary object returned … -
How to strip whitespace off of a returned field from DRF model Serializer?
I have the following code for my DRF serializer: class ObjectSerializer(serializers.ModelSerializer): class Meta: model = models.MyModel fields = ('field1', 'field2') My query code looks like this: class MyAPI(ListAPIView): http_method_names = ['get'] serializer_class = ObjectSerializer def get_queryset(self): queryset = MyModel.objects.values('field1', 'field2').filter(someField='SomeValue').all() return queryset field1 is a char field with trailing whitespace. I am trying to remove all of that trailing whitespace in the query set. How can I go about doing that? I tried passing in the extra_kwargs = {"content": {"trim_whitespace": True}} statement into my serializer but it doesn't trim the whitespace on the field. Is what I am doing wrong obvious and I am just missing it? -
Django Inner join using ORM
I have the following tables in my sqlite3 database : PRAGMA table_info(auth_user); 0|id|integer|1||1 1|password|varchar(128)|1||0 2|last_login|datetime|0||0 3|is_superuser|bool|1||0 4|username|varchar(150)|1||0 5|first_name|varchar(30)|1||0 6|email|varchar(254)|1||0 7|is_staff|bool|1||0 8|is_active|bool|1||0 9|date_joined|datetime|1||0 10|last_name|varchar(150)|1||0 PRAGMA table_info(accounts_member); 0|id|integer|1||1 1|team_id|integer|1||0 2|user_id|integer|1||0 3|department_id|integer|1||0 and lastly : PRAGMA table_info(accounts_department); 0|id|integer|1||1 1|name|varchar(20)|1||0 2|description|varchar(255)|1||0 The above three tables are related to each other in the following manner : auth_user is the main table that links the tables . accounts_member references auth_user with foreign key user_id and also references accounts_department with the foreign key department_id. How can I achieve the following query in django ? select * from auth_user inner join accounts_member on accounts_member.user_id = auth_user.id inner join account_department on account_department.department_id = accounts_member.id i have different tutorials but most I get requires use of where function condition. -
Duplicating an Imagefield on save() - django
I'm working on a project in django, I need to duplicate a picture stored in one model and save it with a different name into another one, I've tried many of the responses I've found but nothing seems to work. This last try doesn't give me an error but is not duplicating the image, nor storing a copy with the name. I'm running Pillow and Django 3.X models.py: class Visualization(models.Model): kind = models.CharField(max_length=90) description = models.CharField(max_length=90) image = models.ImageField(upload_to='visualization', null=True, blank=True) class Order(models.Model): visualization = models.ForeignKey(Visualization, on_delete=models.CASCADE) hashed = models.ImageField(upload_to='hashedimages', null=True, blank=True) def safe(self): super().save() self.hashed = self.visualization.image self.hashed.name = 'randomothername.jpg'' self.hashed.save() -
too many values to unpack (expected 2) - Dictionary to JSON
I have a big dictionary with more than 50 items. I am trying to return this dictionary in the form of JSON. The code for that is:- return HttpResponse(json.dumps(responseData, indent = 0, default=str), content_type="application/json") There are some date fields in the dictionary and so I mentioned default=str to convert them to string. When I print the json.dumps, I do see proper values present in the json. But when I put it in HttpResponse, I get the below error:- too many values to unpack (expected 2) Could somebody tell me why exactly its happening and what is the workaround? -
Postgres10 - CREATE TABLE AS with partition
I have an existing Postgres9 table, where every time I make a query, the WHERE clause includes the id of the US state. I would love to use Postgres10 Declarative Partitions to make a new version of this table, but with a LIST partition based off of the 50 states. I am trying things like: CREATE TABLE partitioned_stuff AS TABLE stuff PARTITION BY LIST( state ); but this gives syntax error at or near "PARTITION" Do I have to recreate the stuff table schema manually?