Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to use images passed down from context_dict in background-image property? Django
I'm trying to access an image passed down from context dictionary in a Django template as a background-image, like this: <div style="background-image:url('{{city.city_image.url}}');"> But it doesn't seem accessible from HTML or CSS. -
I have written this test returning status code 404 while there are other same tests but they are running OK and returning status code 200
Do not know why this test returning 404 instead of 200. Plz help. def test_portal_day_archive_view(self): self.entry = Entry.objects.create(pub_date=self.now, is_active=True, headline='active', slug='b') url = reverse('portal:archive_day', kwargs={'year': self.entry.pub_date.year, 'month': self.entry.pub_date.strftime('%b').lower(), 'day': self.entry.pub_date.strftime('%d')} ) self.assertEqual(200, self.client.get(url).status_code) -
Django ModuleNotFoundError: No module named 'settings'
The Problem When I try to run 'python manage.py runserver' I get this error: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x1068ddc80> Traceback (most recent call last): File "/Users/aricliesenfelt/.virtualenvs/django/lib/python3.6/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/Users/aricliesenfelt/.virtualenvs/django/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/Users/aricliesenfelt/.virtualenvs/django/lib/python3.6/site-packages/django/utils/autoreload.py", line 250, in raise_last_exception six.reraise(*_exception) File "/Users/aricliesenfelt/.virtualenvs/django/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/Users/aricliesenfelt/.virtualenvs/django/lib/python3.6/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/Users/aricliesenfelt/.virtualenvs/django/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/aricliesenfelt/.virtualenvs/django/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/Users/aricliesenfelt/.virtualenvs/django/lib/python3.6/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/Users/aricliesenfelt/.virtualenvs/django/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "/Users/aricliesenfelt/Desktop/scratch/django/django_tutorials/supplyai/ingest/models.py", line 5, in <module> import settings.py ModuleNotFoundError: No module named 'settings' Here is my urls.py: from django.conf.urls import url, include from django.contrib import admin from rest_framework.urlpatterns import format_suffix_patterns urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^ingest/', include('ingest.urls')) ] urlpatterns = format_suffix_patterns(urlpatterns) Here is my models.py where I am just trying to import the local settings.py file I have. … -
Getting long error trying to upgrade Django
I'm trying to run pip install -U Django but I'm getting a super long error: Exception: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip/req/req_set.py", line 778, in install requirement.uninstall(auto_confirm=True) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip/req/req_install.py", line 754, in uninstall paths_to_remove.remove(auto_confirm) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip/req/req_uninstall.py", line 115, in remove renames(path, new_path) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip/utils/__init__.py", line 267, in renames shutil.move(old, new) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 299, in move copytree(src, real_dst, symlinks=True) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 208, in copytree raise Error, errors Error: [('/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pytz/__init__.py', '/var/folders/vw/5tw6gm0x6tn654xbwq1l698h0000gn/T/pip-yMgDg2-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pytz/__init__.py', "[Errno 1] Operation not permitted: '/var/folders/vw/5tw6gm0x6tn654xbwq1l698h0000gn/T/pip-yMgDg2-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pytz/__init__.py'"), ('/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pytz/__init__.pyc', '/var/folders/vw/5tw6gm0x6tn654xbwq1l698h0000gn/T/pip-yMgDg2-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pytz/__init__.pyc', "[Errno 1] Operation not permitted: '/var/folders/vw/5tw6gm0x6tn654xbwq1l698h0000gn/T/pip-yMgDg2-uninstall/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pytz/_ it keeps going... how do i fix this? -
Django Delete an object via Post request
I want to delete an object via clicking on a glyphicon wrapped in a form. To do this, my function looks like this: def deleteHabit(request, id): print('deleteHabit') habit_to_delete = get_object_or_404(Habit, id=id) print(habit_to_delete) if (request.method == 'POST'): form = HabitForm(instance=habit_to_delete) if form.is_valid(): # checks CSRF print('delete') # normally habit_to_delete.delete() return redirect('renderOverview') # wherever to go after deleting else: # Not Working return render(request, 'overview/habit_delete_confirm', args) My understanding of Post and Get is the 'Post' condition does roughly the deleting part and the 'Get' condition renders a confirmation page for example to confirm the deletion. However, the object will be deleted, but by clicking the form it redirects to success_url and does not show a confirmation page. What's wrong on the code snippet above? -
Importing models from deployed django project in Heroku
I have been working in two projects for a while. One is a Django project where I have a web and all my logic (models, algorithms, etc). The other one is a Scrapy project. This one is the one that take care of collecting new data that it's being stored in the Django Database. While I was working locally there wasn't any problem but now that I've deployed both projects to two different heroku apps I began to have this problem: My scrapy project is importing the Django models in this way: - In my settings.py in my scrapy project I've this: import sys sys.path.insert(0, '/home/guillermo/Documents/project/django_project') #(2) import os os.environ['DJANGO_SETTINGS_MODULE'] = 'my_project.settings' and then in my files where I need a django model I do this: from base_project.models import New where New is a model in my app "base_project". Now, I don't know what to put where I put my django directory in line (2). Any help on that would be really useful as this is my project degree as an engineer and I'm looking to finish it as soon as possible. Thanks! -
Is .lower() with day is necessary on this url?
https://github.com/django/djangoproject.com/blob/master/blog/models.py#L77 Is putting .lower() with day is necessary? What does day do with the .lower()? -
Deploying Django To Heroku - Server Error (500)
I have been making a django app, and am now trying to deploy it to heroku. However when I go on it, says Server Error (500), and the log says: 2017-05-27T21:00:14.634310+00:00 heroku[router]: at=info method=GET path="/" host=remberit.herokuapp.com request_id=065d27c6-9211-458f-9fc6-bb677d43581e fwd="86.13.204.65" dyno=web.1 connect=0ms service=151ms status=500 bytes=387 protocol=https Here is my settings.py (at learst the relevant parts, but please ask if you would like the rest): PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, "staticfiles") STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' import dj_database_url DATABASES['default'] = dj_database_url.config() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') ALLOWED_HOSTS = ['*'] DEBUG = False try: from .local_settings import * except ImportError: pass And here is my wsgi.py: import os from django.core.wsgi import get_wsgi_application #from whitenoise.django import DjangoWhiteNoise import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'remberit.settings') django.setup() application = get_wsgi_application() #application = DjangoWhiteNoise(application) Here is my Procfile: web: gunicorn remberit.wsgi Here is my runtime.txt: python-3.5.2 Here is my requirements.txt: appdirs==1.4.3 dj-database-url==0.4.2 gunicorn==19.7.1 packaging==16.8 pyparsing==2.2.0 six==1.10.0 whitenoise==3.3.0 psycopg2==2.6.2 And here is the output of pip freeze: appdirs==1.4.3 dj-database-url==0.4.2 gunicorn==19.7.1 packaging==16.8 pyparsing==2.2.0 six==1.10.0 whitenoise==3.3.0 Also, when I run the app locally with gunicorn remberit.wsgi or python manage.py runserver it works fine, it only doesn't work when I use heroku. Please tell me if you need … -
django.db.utils.OperationalError: no such table -- Known error location, unknown why
I have a django app in production, and working. But when I try to setup a new version of the app, I get this error when running the initial migrate command that generates the SQLite db: django.db.utils.OperationalError: no such table: badges_badge The stack trace points to this method as the problem: File "/home/me/Developer/app/src/badges/models.py", line 69, in all_manually_granted obj.pk for obj in self.get_queryset() Here's the relevant code in badges/models.py: class BadgeManager(models.Manager): def get_queryset(self): return BadgeQuerySet(self.model, using=self._db).order_by('sort_order') ... def all_manually_granted(self): # build a list of pk's for badges that have no prerequisites. pk_manual_list = [ obj.pk for obj in self.get_queryset() # <-- OFFENDING LINE OF CODE if Prereq.objects.all_parent(obj).count() == 0 ] return self.filter(pk__in=pk_manual_list).order_by('name') class Badge(models.Model, IsAPrereqMixin): name = models.CharField(max_length=50, unique=True) ... If I teporarily change this method, the migrate works no problem. def all_manually_granted(self): return None; Why does this cause a problem with the initial migration? -
Creating histogram bins from Django queries
I'm trying to create bins with the count of prices to be used for a histogram. The code I've written seems to end in a infinite loop (or at least the script is still running after an hour). I'm not sure how to do it correctly. I hope someone can help. Here is the code I wrote: from itertools import zip_longest def price_histogram(area_id, agency_id): # Get prices and total count for competitors query = HousePrice.objects.filter(area_id=area_id, cur_price__range=(1000,30000)).exclude(agency_id=agency_id) count = query.values('cur_price').annotate(count=Count('cur_price')).order_by('cur_price') total = query.count() # Get prices and total count for selected agency query_agency = HousePrice.objects.filter(area_id=area_id, agency_id=agency_id, cur_price__range=(1000,30000)) count_agency = query_agency.values('cur_price').annotate(count=Count('cur_price')).order_by('cur_price') total_agency = query_agency.count() # Make list for x and y values x_comp = [] y_comp = [] x_agency = [] y_agency = [] bin_start = 0 bin_end = 1000 _count_comp = 0 _count_agency = 0 for row_comp, row_agency in zip_longest(count, count_agency, fillvalue={}): while bin_start < int(row_comp['cur_price']) < bin_end: _count_comp += row_comp['count'] _count_agency += row_agency.get('count', 0) bin_start += 1000 bin_end += 1000 x_comp.append(str(bin_start) + "-" + str(bin_end) + " USD") x_agency.append(str(bin_start) + "-" + str(bin_end) + " USD") y_comp.append(_count_comp/total) y_agency.append(_count_agency/total_agency) return {'x_comp': x_comp, 'y_comp': y_comp, 'x_agency': x_agency, 'y_agency': y_agency} I'm using Python 3.5 and Django 1.10. -
Django Template Foreign Key Check
In model: class Example text class Share example (foreign_key) user (foreign_key) In view: def page: items = Example.objects.get(user=user) user_shares = Example.objects.get(user=user) return render(page.html, {'items': items, 'user_shares': user_shares}) In the template I can show items in rows. But for the shared ones I want to put for example additional buttons. How can I use something like {% if item in shares %} in for loop? Or do you have better ideas? -
Django: Read Uploaded Excel File
I have a where users can upload an Excel fie, and am able to call the file in my views.py like so: def create_chart(request): # How I get Excel file: file = File.objects.get(id=1).file content = file.read() # excel.read_data is a custom function I wrote using pandas print(excel.read_data(content)) Here is what that read_data function actually does: import pandas as pd def read_data(file, sheetname=0): df = pd.read_excel(file, sheetname, engine='xlrd') return(df) However, when I run my code I get the following error message: Must explicitly set engine if not passing in buffer or path for io. Any ideas on where I am going wrong? -
New users can't log in. Django
I'm using a view to create new users in Django. And then I have another view to log them in. But when I create a user, and I try to log in with authenticate(username=username_post, password=password_post), I get None, so it displays in the template 'Wrong username or password.'. In my database, I see new registers every time I create a new user. However, as the password is encrypted, I can't say if the problem is the login view, or the register view. However, the super user that I created through the command line after I first installed django, is able to login with no problem, so that makes me thing that the problem is when I create the user. These are my Login and Register views: class Login(View): form = LoginForm() message = None template = 'settings/blog_login.html' def get(self, request, *args, **kwargs): if request.user.is_authenticated(): return redirect('settings:index') return render(request, self.template, self.get_context()) def post(self, request, *args, **kwargs): username_post = request.POST['username'] password_post = request.POST['password'] user = authenticate(username=username_post, password=password_post) if user is not None: login(request, user) return redirect('settings:index') else: self.message = 'Wrong username or password.' return render(request, self.template, self.get_context()) def get_context(self): return {'form': self.form, 'message': self.message} class Register(CreateView): success_url = reverse_lazy('settings:login') model = User … -
Nginx - Django i serve perfect static files but not media files
(Sorry for my bad english) I'm having a peculiar problem... I configure Django and Nginx all perfect, my site shows perfect all static files are loaded perfect to. But..... Nginx is not serving the media files, i check my configurations and all seems to be ok. But i always get the 404 error and the route is the same that static files but with the media word this is a static file route http://project.com/static/css/custom.css And this a media file http://project.com/media/stores/logos/solutions_logo_rdWRcqQ.jpg This is the nginx config server { listen 80; server_name project.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/username; } location /media/ { root /home/username; } location / { include proxy_params; proxy_pass http://unix:/home/username/project.sock; } } And this are the django settings STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static/'), ) STATIC_ROOT=os.path.join(os.path.dirname(os.path.dirname(BASE_DIR)), 'static/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.path.dirname(os.path.dirname(BASE_DIR)), 'media/') Any idea??? -
Django - How can I create POST with foreign key defined in URL?
I wonder how can I create object POST with defined ID. Let's assume that I have for instance table User with columns id,name and table Object with columns id,id_users,sth where id_users is a foreign key of id from User table. I would like to have such URL /users/{id}/object and I would like to create object for user with defined ID in URL. For example this is my URL /users/1/object (url(r'^users/(?P<myID>[0-9]+)/object/$', views.UserObject) - should be okey) and body of POST: { "id": 2, "sth": 123 } In this case it should be added to my database: { "id": 2, "id_users": 1, "sth": 123 } For User with id equals 1 we have created object with id equals 2 and sth equals 123. I don't know what my view should look like? I always did POST in this way: @api_view(['GET', 'POST']) def ObjectList(request): if request.method == 'POST': serializer = ObjectSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I have deleted duplicated posts, because I have explained here how my database and relations between tables look like. I also specified what I would like to achieve. Any suggestions how can I deal with this? -
Django DeleteView without confirmation
I want to delete an object via DeleteView. my views.py looks like this: class HabitDelete(DeleteView): model = Habit success_url = reverse_lazy('renderOverview') template_name = 'overview/habit_delete_confirm.html' my urls.py looks like this: url(r'^details/(?P<pk>\w{0,50})/delete/$', overview_views.HabitDelete.as_view(), name='deleteHabit'), my template: {% block content %} <div class="container custom-div-habit-detail"> <h1 class="custom-title-label">{{habit.title}}</h1> <!-- <a href="{% url 'deleteHabit' habit.id %}"> <span class="glyphicon glyphicon-trash custom-glyphicon-trash"></span> </a> --> <form action="{% url 'deleteHabit' pk=habit.id %}" method="POST" class="custom-form-trash"> {% csrf_token %} <button type="submit" class="btn btn-default custom-btn-trash"> <span class="glyphicon glyphicon-trash custom-glyphicon-trash"></span> </button> </form> <br> <br> <p class="custom-trigger-label custom-padding-top-30">{{habit.trigger}}...<p> <p class="custom-routinebehavior-label">{{habit.existingroutine}}<p><br> <p class="custom-trigger-label">I will...</p> <p class="custom-routinebehavior-label">{{habit.targetbehavior}}</p><br> <p> <img src="{{ habit.image_url }}" class="img-responsive custom-image-detail" width="100"></p> <br> <a class="btn btn-default custom-tab-item" href="/overview"> <span class="glyphicon glyphicon-chevron-left"></span> <span class="tab-label">Go back</span> </a> <button class="btn btn-default custom-tab-item" id="myform"> <span class="glyphicon glyphicon-ok"></span> <span class="tab-label">Let's go</span> </button> </div> {% endblock %} and the folder templates/overview contains habit_delete_confirm.html. My object 'habit' will be deleted successful, but I don't know why I do not get a confirmation template as usual. -
How to get image from a custom django registration view
I'm using using django-registration (redux) and I have created a custom register view for my purposes. class MyRegisterView(RegistrationView): form_class = MyCustomForm def register(self, form_class): new_user = super(MyRegisterView, self).register(form_class) cm = CustomModel() # cm.profile_picture = form_class.cleaned_data['profile_picture'] cm.save() return new_user In order to get the image I would have to instantiate the form as form_class = MyCustomForm(request.POST, request.FILES) And to do that request should be added in register method as def register(self, request, form_class) Since register method is overridden from RegistrationView class the signatures do not match. What's the correct way to do it? -
In Django1.11 form, how can I handle url?
I have started learning Django a few days ago, I'm not sure how I can handle form url. myproject/urls.py file as follows. from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^form/', include('app.urls')) ] Here is myproject/app/urls.py file. from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.get_name, name = 'get_name'), url(r'^/your-name/$', views.your_name, name = 'your_name') ] Here is app/views.py file. from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .forms import NameForm def get_name(request): if request.method == 'POST': form = NameForm(request.POST) if form.is_valid(): return HttpResponseRedirect('/thanks/') else: form = NameForm() return render(request, 'name.html', {'form' : form}) def your_name(request): return HttpResponse("Hello, world.") app/forms.py file. from django import forms class NameForm(forms.Form): your_name = forms.CharField(label='Your name', max_length=100) app/name.html file. <form action="/your-name/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" /> </form> When I click the submit button, exception occurs. The current path, your-name/, didn't match any of these. When I click the submit button, http://localhost:8000/your-name/. I think it's wrong. I guess http://localhost:8000/form/your-name/ must appear and Hello, world must be printed on the browser. But it didn't. I wanna know the reason why? -
How to show current object inside template used with class based FormView
Having this urls.py snippet: url(r'^storageitem/(?P<pk>[\w]+)/addtransaction/$', login_required( StorageItemTransactionAddView.as_view()), name='storage_item_transaction'), I'm wondering what is the correct way to make the object beihind pk available inside a template to show it e.g. with <h1>{{ object.name }}</h1> I tried to configure a query set ... queryset = StorageItem.objects.get pk=get_from_kwargs()['object']) def get_form_kwargs(self): kwargs = super(ItemCreate, self).get_form_kwargs() kwargs.update({ 'object' : self.kwargs['pk'] }) return kwargs but the method is not access able at this point. So I'm wondering how could one do it the correct way? All I need would be something like self.object = StorageItem.objects.get(pk='my pk') -
Foreign Key to single attribute from another entity in Django
I want to create database model in django and define a foreign key. All the example I see in internet have following syntax. attr = models.ForeignKey(Entity) However I want a foreign key to be linked with single attribute from another entity and not the whole entity. I have following models: class User(models.Model): user_id = models.PositiveIntegerField(primary_key=True) password = models.CharField(max_length=20) email = models.EmailField() ........ class ContentItem(models.Model): content_id = models.PositiveIntegerField(primary_key=True) title = models.CharField(max_length=100) description = models.TextField() ......... author_id = models.ForeignKey(User, on_delete= models.CASCADE) Here, I want ContentItem.author_id to be foreign key for User.user_id and not the whole User model. Sorry if the question is very general and thanks in advance -
Django - How to create POST with defined ID? [duplicate]
This question is an exact duplicate of: Django - How to create POST with defined ID I wonder how can I create object POST with defined ID. Let's assume that I have for instance table User with columns id,name and table Object with columns id,id_users,sth where id_users is a foreign key of id from User table. I would like to have such URL /users/{id}/object and I would like to create object for user with defined ID in URL. For example this is my URL /users/1/object (url(r'^users/(?P<myID>[0-9]+)/object/$', views.UserObject) - should be okey) and body of POST: { "id": 2, "sth": 123 } In this case it should be added to my database: { "id": 2, "id_users": 1, "sth": 123 } For User with id equals 1 we have created object with id equals 2 and sth equals 123. I don't know what my view should look like? I always did POST in this way: @api_view(['GET', 'POST']) def ObjectList(request): if request.method == 'POST': serializer = ObjectSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Any suggestions how can I deal with this? -
New Django Cookiecutter project using older project's Postgres DB
I am creating a new django cookiecutter project (for clarification - the first on Python 2.7, this new one on Python 3.6). I just did the following: brew install python3 create the virtualenvironment with venv activated the venv installed cookiecutter setup a new project pip install -r requirements/local.txt createdb (project_name) (The projects aren't the same name) I then get to running the initial migrations, and run into an issue with Postgres. When I run "python manage.py migrate" I get the following error: django.db.utils.ProgrammingError: relation "django_site_domain_a2e37b91_uniq" already exists I see the new postgres db, and my Django settings are pointing to this new db. DATABASES = { 'default': env.db('DATABASE_URL', default='postgres:///inventorymaster'), } DATABASES['default']['ATOMIC_REQUESTS'] = True When I then run python manage.py runserver, I can login to the new project with the username/password for the first cookiecutter project. The second project is referencing the first project's db - but this doesn't make sense to me seeing the settings are pointed to the new db. How is the new project referencing the first, older projects user table to allow me to login and making the django.db.utils.ProgrammingError? -
MySQL (MariaDB) backend for Django under Python3 on Debian
I am attempting to configure Django running under Python3 on a Debian box to use MariaDB as its backend. If I alter my mysite/settpings.py as per the tutorial i.e. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'foo', 'USER': 'tim', 'PASSWORD': 'swordfish', 'HOST': 'localhost' } } I get a lot of grief, culminating in File "/usr/local/lib/python3.4/dist-packages/django/db/backends/mysql/base.py", line 30, in <module> 'Did you install mysqlclient or MySQL-python?' % e django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'. Did you install mysqlclient or MySQL-python? Now, obviously, MySQLdb doesn't work on Python3 and although I have installed the mysql connector package doesn't seem to work. If I try using the connector recommended by MySQL i.e. DATABASES = { 'default': { 'ENGINE': 'mysql.connector.django', 'NAME': 'foo', 'USER': 'tim', 'PASSWORD': 'swordfish', 'HOST': 'localhost' then I get a load of grief culminating in django.core.exceptions.ImproperlyConfigured: 'mysql.connector.django' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' Error was: cannot import name 'BaseDatabaseFeatures' Any suggestions? -
How to set field in model that was not defined in Meta class
In django, how do we set fields that were not defined in class Meta?` I have this model: class User(models.Model): user_name = models.CharField(max_length=32, unique=True) email = models.EmailField(unique=True) first_name = models.CharField(max_length=32) last_name = models.CharField(max_length=32) password_hash = models.CharField(max_length=64) password_salt = models.CharField(max_length=64) and this form: class ContactForm(ModelForm): password = forms.CharField(widget=forms.PasswordInput()) repeat_password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ['user_name', 'email', 'first_name', 'last_name'] def clean(self): cleaned_data = super(ContactForm, self).clean() password = cleaned_data.get('password') repeat_password = cleaned_data.get('repeat_password') if password is not None and repeat_password is not None: if password != repeat_password: raise forms.ValidationError("Passwords do not match.") password_validate = password_validate = password_validation.validate_password(password) if password_validate is not None: raise password_validate I only want the user to be able to set user_name, email, first_name and last_name fields. In clean(self) I check if the entered passwords match and if they are valid. What I want to do now is to set password_hash and password_salt of my model User. How can this be done? -
Django makemessages to get custom translatable strings
In my Django project I use Vue + vue-gettext for i18n to make translatable strings I have the following code in my my .vue files: <translate>Hello %{name}</translate> <a href="..." v-traslate>Click here</a> (using translate tags and v-translate attributes) Is there a way to configure manage.py makmessages parse this code as well ? (by default it does not look into vue files or parse this i18n code format)