Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Serializer field named incorrectly
I'm attempting to present some serialized data, and am getting a AttributeError when attempting to get a value for field name. models.py: class Resource(models.Model): """Initial representation of a resource.""" # ID from fixture resources, for internal dedupe internal_id = models.CharField(max_length=20, null=True, blank=True) name = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) categories = models.ManyToManyField("Category") neighborhoods = models.ManyToManyField("Neighborhood") email_contact = models.EmailField(null=True, blank=True) pdf = models.ManyToManyField("PDF") phone = models.CharField(max_length=200, blank=True, null=True) website = models.URLField(max_length=200, blank=True, null=True) # address street_address = models.CharField(max_length=400, null=True, blank=True) city = models.CharField(max_length=100, null=True, blank=True) state = models.CharField(max_length=10, null=True, blank=True) latitude = models.FloatField(null=True, blank=True) longitude = models.FloatField(null=True, blank=True) zip_code = models.CharField(max_length=10, null=True, blank=True) # meta created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name def __unicode__(self): return u'{}'.format(self.name) @property def categories_str(self): return [str(t) for t in self.categories.all()] @property def neighborhoods_str(self): return [str(t) for t in self.neighborhoods.all() if t] or ["Houston"] @property def bookmark(self): """This is here to make it easier to serialize a standard resource.""" return getattr(self, "_bookmark", None) @bookmark.setter def bookmark(self, bookmark): self._bookmark = bookmark def indexing(self): safe_zip = str(self.zip_code or "") safe_neighborhood = [n for n in self.neighborhoods.all() if n] or ["Houston"] obj = ResourceDoc( meta={"id": self.id}, name=self.name, resource_suggest=self.name, email_contact=self.email_contact, phone=self.phone, description=self.description, website=self.website, categories=self.categories_str, street_address=self.street_address, city=self.city, state=self.state, zip_code=safe_zip, … -
HTML templates not getting rendered in django
I am new at django and I have an app in django project. My base.html has navigation bar through which you can redirect to "about", 'contact us', 'home'. The first page when app starts (after loging in) is home. <!DOCTYPE html> <html lang="en"> <head> {%load staticfiles%} <meta charset="utf-8"> <title>Ekyam: India's First Entrepreneurial Ecosystem</title> <meta content="width=device-width, initial-scale=1.0" name="viewport"> <meta content="" name="keywords"> <meta content="" name="description"> <!-- Google Fonts --> <link href="https://fonts.googleapis.com/css?family=Roboto:400,100,300,500,700,900" rel="stylesheet"> <!-- Bootstrap CSS File --> <link href="{% static "visit/lib/bootstrap/css/bootstrap.min.css" %}" rel="stylesheet"> <!-- Libraries CSS Files --> <link href="{% static "visit/lib/font-awesome/css/font-awesome.min.css"%}" rel="stylesheet"> <link href="{% static "visit/lib/owlcarousel/owl.carousel.min.css" %}" rel="stylesheet"> <link href="{% static "visit/lib/owlcarousel/owl.theme.min.css"%}" rel="stylesheet"> <link href="{% static "visit/lib/owlcarousel/owl.transitions.min.css" %}" rel="stylesheet"> <!-- Main Stylesheet File --> <link href="{%static "visit/css/style.css"%}" rel="stylesheet"> <!--Your custom colour override - predefined colours are: colour-blue.css, colour-green.css, colour-lavander.css, orange is default--> <link href="#" id="colour-blue" rel="stylesheet"> </head> <body class="page-index has-hero"> <!--Change the background class to alter background image, options are: benches, boots, buildings, city, metro --> <div id="background-wrapper" class="city" data-stellar-background-ratio="0.1"> <!-- ======== @Region: #navigation ======== --> <div id="navigation" class="wrapper"> <!--Hidden Header Region--> <div class="header-hidden collapse"> <div class="header-hidden-inner container"> <div class="row"> <div class="col-md-3"> <h3> About Us </h3> <p>Ekyam is dedicated to support and nourish Startups and accelaration</p> <a href="about.html" class="btn btn-more"><i class="fa … -
Issue with urls re_path
I have the following url re_path: re_path(r'^up_account/(?P<ud>[0-9A-Za-z_\-]+)/(?P<tk>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', AccountView.as_view(), name='up_account'), path('accounts/', include('users.urls', namespace='users')), I called in a template this way: {% url 'users:up_account' ud=ud tk=tk %} I have the following error: Reverse for 'up_account' with keyword arguments '{'ud': b'MjA', 'tk': '4u9-15b083b81757413cf575'}' not found. 1 pattern(s) tried: ['accounts\\/up_account/(?P<ud>[0-9A-Za-z_\\-]+)/(?P<tk>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'] "accounts\" - I think is because I'm on windows and print does it this way -
I need to add form files as model instances dynamically in django
I'm trying to do something like this: There's a form in my web page and has a "select files button" so you can upload multiple files at once. My problem is that I need "get" that files and add each of them to be a model instance, is there possible? -
Django Rest Framework: AttributeError: 'NoneType' object has no attribute '_meta' [for OneToOneField]
I need help with a POST request using Django rest framework. I have a User model that inherits from AbstractBaseUser which has 2 fields: name and email. Then I have a DojoMaster model that has a OneToOne relationship with the User model: class DojoMaster(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) phone = models.BigIntegerField() country = models.ForeignKey(Country, on_delete=models.CASCADE) I want to register the dojo master via an API so I created the following serializers: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('name', 'email', 'password') class DojoMasterCreateSerializer(serializers.ModelSerializer): user = UserSerializer(required=True) class Meta: model = DojoMaster fields = ('user', 'phone', 'country') def create(self, validated_data): validated_data['country'] = Country.objects.get( country=validated_data['country']) user_data = validated_data.pop('user') user = UserSerializer.create(UserSerializer(), validated_data=user_data) subscriber, created = DojoMaster.objects.update_or_create(user=user, phone = validated_data.pop('phone'), country = validated_data['country']) return subscriber To call on these serializers, I created the following view: class DojoMasterCreateView(generics.CreateAPIView): def post(self, request, format='json'): serializer = DojoMasterCreateSerializer(data=request.data) if serializer.is_valid(raise_exception=ValueError): serializer.create(validated_data=request.data) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) For the body of the POST request I had the following: { "user": { "name": "XYZ", "email": "xyz@mail.com", "password": "8Xa,9Lv&" }, "phone": 9696510, "country": "USA" } However, when I do that I get the following error: Traceback (most recent call last): File "C:\Users\app_dev\Envs\game_of_quarks\lib\site-packages\django\core\handlers\exception.py", line 41, in inner … -
(Django) Cannot update custom profile
So I'm trying to update the user's info in an extended update, but it worked before I added the rest, but now it won't work I've tried going back still nothing. it's not taking it as its even POST Requesting when clicking submit why tho? Html <form xaction="{% url 'userprofileupdate' logged_in_user.pk %}" method="POST"> {% csrf_token %} https://pastebin.com/vMw6AEai (only Pastebin because of its a lot of code) Views.py @login_required def userprofileupdate(request, user_pk): if request.method == 'POST': form = UpdateProfileForm(request.POST, instance=request.user) if form.is_valid(): user = form.save() user.refresh_from_db() # load the profile instance created by the signal user.extendeduser.nickname = form.cleaned_data.get('username') user.extendeduser.postal_code = form.cleaned_data.get('postal_code') user.extendeduser.phone_number = form.cleaned_data.get('phone_number') user.extendeduser.emergency_number = form.cleaned_data.get('emergency_number') user.extendeduser.birthdate = form.cleaned_data.get('birthdate') user.extendeduser.languages = form.cleaned_data.get('languages') user.extendeduser.drivers_licence = form.cleaned_data.get('drivers_licence') user.extendeduser.tshirt = form.cleaned_data.get('tshirt') user.extendeduser.special_considerations = form.cleaned_data.get('special_considerations') user.save() messages.success(request, "Your profile has been updated!") return redirect('usersettings', user_pk=request.user.pk) messages.error(request, 'Error: please update your settings if you want to update them') return redirect('usersettings', user_pk=request.user.pk) forms.py class UpdateProfileForm(forms.ModelForm): postal_code = forms.CharField(max_length=10, required=True) phone_number = forms.CharField(max_length=16, required=True) emergency_number = forms.CharField(max_length=16, required=True) birthdate = forms.DateField(required=False) languages = forms.MultipleChoiceField(required=False) drivers_licence = forms.MultipleChoiceField(required=False) tshirt = forms.ChoiceField(required=False) special_considerations = forms.CharField(required=False) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'birthdate', 'phone_number', 'emergency_number', 'postal_code', 'languages', 'drivers_licence', 'tshirt', 'special_considerations',) -
Count True or False (1 or 0) values from database in Django template
I am trying to implement user template view to show how many devices are online and how many are offline. For that instance I am storing in database column 'status' with values of 1 and 0. I could not figure it out how to take these values and count them in Django environment. I mean if i have 4 True(1) values, in template it should look like: You have 4 online devices and vise versa if there are 4 False(0) values it should look like: You have 4 offline devices Is it possible to make it happen in Django? I'm really a rookie in this field and would really appreciate some good tips... my models.py class Device(models.Model): usr = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ip = models.CharField(max_length=50) status = models.IntegerField(default=0) -
Query db in Django for one row with a pair of values
I want to query DB in my views.py to retrieve one pair of values from two columns only. Let me show you my efforts: Items.objects.filter(file_name=name).values('file_name', 'secret') I need exactly one pair of values coming from columns called: 'file_name' and 'secret'. Value of 'secret' has to be in the same raw of 'file_name' How could I write such query? What data type is it going to return? -
Local postgis DB setup for Geodjango
I've been trying to setup my (windows) computer such that I can have a local postgreSQL with PostGIS extension. With this installed I hope to be able to create a project with geodjango locally before putting it in the cloud. I have been working with Django for a little while now on my local machine with the SQLite DB, but since the next project will partly be based on coordinate based data I wanted to setup the right environment. I've tried to follow most of the geodjango information/tutorials online, but can't get it to work. What I've done (mostly followed this: https://docs.djangoproject.com/en/2.0/ref/contrib/gis/install/#windows): Download and install the latest (10.3) PostgreSQL setup from https://www.enterprisedb.com/downloads/postgres-postgresql-downloads After installation I also installed used the Application Stack Builder to install PostGis I've installed OSGeo4W from https://trac.osgeo.org/osgeo4w/ I've created a batch script as described on the geodjango website (https://docs.djangoproject.com/en/2.0/ref/contrib/gis/install/#windows) and ran it as administrator (except for the part where it sets the path to python, cause python was already in there since I've been using python for a while now) I've tried some command in psql shell and I think I've created a database with name: geodjango, username: **** and pass: ****. I don't know if I … -
Library for editing images with different effects in Django, Python
I am looking to apply all possible effects to an uploaded image. I need to figure out that, is there any third party packages or Python libraries to edit the image uploaded with different effects. And how to approach as per it. -
Django: setting environmental variables with Supervisor
I'm using Supervisor to run Celery in the background of a Django application however it's not able to access the environmental variables I have set/exported in my virtual environment's postactivate file. I'm working in a local environment and running Ubuntu 16.04 on a Vagrant box. When I start Celery using Supervisor I get a Spawn error with the following exception: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty I know this question has been asked here before however I've tried many of the solutions and haven't found one that works. I've tried setting supervisor's 'environment' key in supervisord.conf under the supervisord section as follows but I get a "file not found error" when I start Supervisor: [supervisord] ... environment=DJANGO_KEY="key" I've also tried setting the same key in the same file as a django program which Supervisor seems to recognize however it's unable to parse Django's special characters. [program:django] environment=DJANGO_KEY="key" If I set the Django_KEY directly into my settings file everything works. I'm a bit new at all this and it's still a little foggy to me as to how the different programs that run gain access to the file directory, so it's very possible that I'm missing some core concept … -
'Comments' object has no attribute 'is_valid'
I am making a comment app to make comments to a post. This is my comments/forms.py from django import forms from .models import Comments class CommentForm(forms.ModelForm): theuser ='hhh123' thepost ='Bitcoin' thecontent =forms.CharField(widget=forms.TextArea) class Meta: model=Comments fields = ('user','post','content') This is my comments/models.py from django.db import models from django.conf import settings from currency.models import Currencies class Comments(models.Model): user =models.ForeignKey(settings.AUTH_USER_MODEL,default=1) post =models.ForeignKey(Currencies) content =models.TextField() timestamp =models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username This is my comments/views.py from django.conf import settings from currency.models import Currencies from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.shortcuts import render, get_object_or_404, redirect from .models import Comments def mycommentview(request): instance = Comments.objects.all() myformofcomments=Comments(request.POST or None) if myformofcomments.is_valid(): print(myformofcomments.cleaned_data) context = { "instance" : instance, "myformofcomments": myformofcomments, } return render(request, "home2.html",context) When i load the page I get these errors: AttributeError at /mycommentview/ Comments' object has no attribute 'is_valid' What is my error?? My environment: Request Method: GET Request URL: http://localhost:8000/mycommentview/ Django Version: 1.8 Python Version: 3.5.4 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mainpage', 'signup', 'login', 'currency', 'comments', 'rest_framework', 'corsheaders') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware') Error traceback: File "C:\Users\vaibhav2\AppData\Local\Programs\Python\Python35\lib\site-packages\django\core\handlers\base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\vaibhav2\PycharmProjects\MajorProject\src\comments\views.py" in … -
Calendar in python/django
I am working on a website with weekly votations, but only the first three weeks of the month, so in each instance I have a start_date and end_date field. I'd like to know if there's a way to automitically create these instances based on the current date, for instance: Today it is 6 of March, and votations end tomorrow, so a function should be run (tmrw) that, taking into account this month calendar, would fill in the appropiate dates for the next votations. What calendar do you recommend me, and how shoul I do it? (Never mind the automatically run part, I'll go with celery). Thanks! -
How can I get in post the context_data?
In a CreateView I have the following code: def post(self, request, *args, **kwargs): response = super().post(request, *args, **kwargs) send_confirmation_email() When a form is submited, I want to send an email, but in the email function, I need some data from the context(what was submitted). Also I want this to happen if everything is ok, so also on get_success_url. -
Aligning Text boxes Django
This is my registration form: Registration Form I am trying to align all of the text boxes. This is my form code; Forms.py class RegistrationForm(UserCreationForm): email = forms.EmailField(required=True, label = "Email:") username = forms.CharField(required=True, label = "Username:") first_name = forms.CharField(required=True, label = "First Name:") last_name = forms.CharField(required=True, label = "Last Name:") password1 = forms.CharField(widget=forms.PasswordInput, required=True, label = "Password:") password2 = forms.CharField(widget=forms.PasswordInput, required=True, label = "Confirm Password:") class Meta: model = User fields = { 'password2', 'username', 'first_name', 'last_name', 'email', 'password1' } Any help is greatly appreciated. -
Handling multiple query params
I have a create user view and here I first register a normal user and then create a player object for that user which has a fk relation with the user. In my case, I have three different types of users, Player, Coach, and Academy. I created a view to handle register all three different types of users, but my player user has a lot of extra model fields and storing all query params in variables will make it messy. Is there a better way to handle this, including validation? TLDR; I created a view to handle register all three different types of users, but my player user has a lot of extra model fields and storing all query params in variables will make it messy. Is there a better way to handle this, including validation? This is my view. class CreateUser(APIView): """ Creates the User. """ def post(self, request): email = request.data.get('email', None).strip() password = request.data.get('password', None).strip() name = request.data.get('name', None).strip() phone = request.data.get('phone', None) kind = request.query_params.get('kind', None).strip() print(kind) serializer = UserSerializer(data={'email': email, 'password':password}) serializer.is_valid(raise_exception=True) try: User.objects.create_user(email=email, password=password) user_obj = User.objects.get(email=email) except: raise ValidationError('User already exists') if kind == 'academy': Academy.objects.create(email=email, name=name, phone=phone, user=user_obj) if kind == 'coach': … -
POST request not working in Ajax jQuery
I have a Django application where I am trying to open index2.html from index.html on button click event. Basically, I am using 2 procedures in order to fulfil this simple task Form with submit button (Button 1) Ajax (Button 2) First one seems to work fine but Ajax is not working. On clicking, Button 2 nothing seems to happen. Can anybody tell me whats going on, any help would be appreciated. index.html <!DOCTYPE html> <html lang="en"> <head> <title>Index</title> </head> <body> <h2>Index</h2> <form method="post" action="/index2/"> <button type="submit" >Button 1</button> <input type="button" id="btn" name="btn" value="Button 2" /> </form> <script src="https://code.jquery.com/jquery-2.2.3.min.js"></script> <script> $("#btn").click(function() { $.ajax({ type: 'POST', url: '/index2/', data: {} }); }); </script> </body> </html> index2.html <!DOCTYPE html> <html lang="en"> <head> <title>Index 2</title> </head> <body> <h2>Index 2</h2> </body> </html> views.py from django.views.decorators.csrf import csrf_exempt from django.shortcuts import render @csrf_exempt def index(request): return render(request, "index.html") @csrf_exempt def index2(request): return render(request, "index2.html") urls.py from django.urls import path from . import views urlpatterns = [ path('index/', views.index, name='index'), path('index2/', views.index2, name='index2'), ] -
How to call a function from models.py with class based views in Django?
I would like to convert a user uploaded .docx file to .html using a function/method I have in models.py. I can do it with function based view with this kind of approach: models.py: class Article(models.Model): main_file = models.FileField(upload_to="files") slug = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) @classmethod def convert_word(self, slug): import pypandoc pypandoc.convert_file('media/files/%s.docx' %slug, 'html', outputfile="media/files/%s.html" %slug) And then I call the convert_word function like this in views.py: def submission_conf_view(request, slug): Article.convert_word(slug) return redirect('submission:article_list') What I would like to do is to call the same function/method but using Djangos Class-based views, but I am having trouble figuring that out... -
How to retry all celery tasks when OperationalErrors occur?
Occasionally when postgres is restarted I get a flood of errors from Celery because of OperationalErrors. Things like: File "/var/www/.virtualenvs/xxx/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) OperationalError: terminating connection due to administrator command SSL connection has been closed unexpectedly Is there a way to just automatically restart any celery tasks that end this way, perhaps with a 30s delay or something? I'm using redis as my broker. I could catch this kind of error in my task, but it'd mean wrapping every database command in a try/except, which would be kind of horrific. -
Can anyone help my find find error in django?
I am new to Django. I have a project which has 2 child apps: "visit" and "main". The error is in base.html file in href for the navigation bar. I am facing No reverse match found error. main/base.html: {%load staticfiles%} <link href="{%static "main/vendor/bootstrap/css/bootstrap.min.css"%}" rel="stylesheet"> <link href="{%static "main/css/small-business.css"%}" rel="stylesheet"> </head> <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top"> <div class="container"> <a class="navbar-brand" href="/home.html">Ekyam</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarResponsive"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href='{%url 'main:home'%}'>Home <span class="sr-only">(current)</span> </a> </li> <li class="nav-item"> <a class="nav-link" href='{%url 'main: incubators'%}'>Incubators</a> </li> <li class="nav-item"> <a class="nav-link" href="#">About</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Services</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Contact</a> </li> </ul> </div> </div> </nav> {%block content%} {%endblock%} This is the error that I am facing NoReverseMatch at /home.html Reverse for ' incubators' not found. ' incubators' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/home.html Django Version: 1.11.3 Exception Type: NoReverseMatch Exception Value: Reverse for ' incubators' not found. ' incubators' is not a valid view function or pattern name. Exception Location: C:\Users\my dell\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 497 Python Executable: C:\Users\my dell\AppData\Local\Programs\Python\Python36-32\python.exe Python Version: 3.6.1 Python Path: ['C:\\Users\\my … -
Django Query Best Practice
Wondering about some Django querying performance/best practices. It is my understanding that QuerySets are "lazy" as the documentation states and that the three queries below do not run until they are actually evaluated at some point. Is that a correct understanding and is the below snippet a reasonable way to query against the same table for three different filter values against the same field? # General Education general_education_assignments = FTEAssignment.objects.filter( group_name='General Education' ) # Specials specials_assignments = FTEAssignment.objects.filter( group_name='Specials' ) # Dual dual_assignments = FTEAssignment.objects.filter( group_name='Dual Language' ) Even more so what I am wondering about besides if my understanding of the above is correct is if the below is in anyway more efficient (I don't think it will be)? Also, if either the above or below is better stylistically for Django or more 'pythonic'? # Get all assignments then filter fte_assignments = FTEAssignment.objects.all() # General Education general_education_assignments = fte_assignments.filter( group_name='General Education') # Specials specials_assignments = fte_assignments.filter(group_name='Specials') # Dual dual_assignments = fte_assignments.filter(group_name='Dual Language') Thank you! -
Django: null value in column "created_at" violates not-null constraint
I'm trying to add records via the code below: Post.objects.update_or_create( user=user, defaults={ "title": external_post.get('title'), "body": external_post.get('body'), "seo": external_post.get('seo') } ) I've successfully migrated the model but I'm getting the error " null value in column "created_at" violates not-null constraint". created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) -
UnicodeDecodeError relating to Unicode symbols in Django HTML templates
I don't understand why an HTML template containing Unicode symbols provokes the error: Environment: Request Method: GET Request URL: http://localhost:51389/ Django Version: 1.11.10 Python Version: 3.6.3 Installed Applications: ['app', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] 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.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\pavel\source\repos\Арт-каскад\Арт-каскад\env\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Users\pavel\source\repos\Арт-каскад\Арт-каскад\env\lib\site-packages\django\core\handlers\base.py" in _legacy_get_response 249. response = self._get_response(request) File "C:\Users\pavel\source\repos\Арт-каскад\Арт-каскад\env\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\pavel\source\repos\Арт-каскад\Арт-каскад\env\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\pavel\source\repos\Арт-каскад\Арт-каскад\app\views.py" in home 28. 'future_date':datetime(2018, 3, 16).strftime('%d %B %Y'), File "C:\Users\pavel\source\repos\Арт-каскад\Арт-каскад\env\lib\site-packages\django\shortcuts.py" in render 30. content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\pavel\source\repos\Арт-каскад\Арт-каскад\env\lib\site-packages\django\template\loader.py" in render_to_string 67. template = get_template(template_name, using=using) File "C:\Users\pavel\source\repos\Арт-каскад\Арт-каскад\env\lib\site-packages\django\template\loader.py" in get_template 21. return engine.get_template(template_name) File "C:\Users\pavel\source\repos\Арт-каскад\Арт-каскад\env\lib\site-packages\django\template\backends\django.py" in get_template 39. return Template(self.engine.get_template(template_name), self) File "C:\Users\pavel\source\repos\Арт-каскад\Арт-каскад\env\lib\site-packages\django\template\engine.py" in get_template 162. template, origin = self.find_template(template_name) File "C:\Users\pavel\source\repos\Арт-каскад\Арт-каскад\env\lib\site-packages\django\template\engine.py" in find_template 136. name, template_dirs=dirs, skip=skip, File "C:\Users\pavel\source\repos\Арт-каскад\Арт-каскад\env\lib\site-packages\django\template\loaders\base.py" in get_template 38. contents = self.get_contents(origin) File "C:\Users\pavel\source\repos\Арт-каскад\Арт-каскад\env\lib\site-packages\django\template\loaders\filesystem.py" in get_contents 29. return fp.read() File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\codecs.py" in decode 321. (result, consumed) = self._buffer_decode(data, self.errors, final) Exception Type: UnicodeDecodeError at / Exception Value: 'utf-8' codec can't decode byte 0xc0 in position 91: invalid start byte The HTML template index.html {% extends "app/layout.html" %} … -
user login not working with django, admin can login fine
I'm creating a django app. I have set up the basic structure and admin creation and management. What I am trying to achieve is that the admin creates the accounts for the users. Then the users login using those credentials and create tickets for issues they're facing. Following are the pieces of code from different files: settings.py INSTALLED_APPS = [ 'ticketsapp.apps.TicketsappConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] ROOT_URLCONF = 'appsgenii.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'ticketsapp/templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'appsgenii.wsgi.application' # Database # https://docs.djangoproject.com/en/2.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'appsgenii', 'USER': 'root', 'PASSWORD': '', 'HOST': '127.0.0.1', 'PORT': '3306', } } # Authentication Backend # AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend',) # Password validation # https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] Project urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('auth/', include('django.contrib.auth.urls')), path('tickets/', include('ticketsapp.urls')), ] App urls.py urlpatterns = [ path('success/', views.ticket_created, name='ticket created'), path('create/', views.create_ticket, name='create ticket'), ] views.py from django.contrib.auth import authenticate, login as django_login, … -
Django ProgrammingError [42S02] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server] Invalid object name
I am using Django version 2.0.2. My Django application is connected to MS SQL (connection below). DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'projectcreation', 'HOST': 'Host_name', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', 'dns': 'projectcreation' }, } } So, I am getting the following error when trying to access my Django application: django.db.utils.ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Invalid object name 'projectcreation_partner'. (208) (SQLExecDirectW)") I believe that the problem is following: When I created tables (makemigrations+migrate) instead of creating tables that look like this: [projectcreation].[dbo].[projectcreation_partner] it created tables like this [projectcreation].[username].[projectcreation_partner]. So instead putting dbo which I actually expected to see it put my username.. I suppose that when the app tries to connect to db it cannot find it because it is looking for one containing dbo not username.. Of course, I could be wrong.. If you need more information please let me know, any help is greatly appreciated. Note: both db and application are called "projectcreation", "partner" is name of one of the models.