Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Splitting Transaction across Multiple Views
I'm trying to figure out how to split a transaction across multiple views. This is what I have in mind: I have a view which creates a number of records (all packaged into a single transaction); The view presents some information on these changes and also a form which allows the user to either accept or reject; On the basis of the user's choice the transaction should either be committed or rolled back. The code that I have looks like this at present: @transaction.non_atomic_requests def record_results(request): if request.method=='POST': if "approve" in request.POST: transaction.commit() transaction.set_autocommit(True) if "reject" in request.POST: transaction.rollback() # # Turn AUTOCOMMIT back on again. # transaction.set_autocommit(True) # return render(request, 'updated.html') approve = ApproveForm() # Turn off AUTOCOMMIT. # transaction.set_autocommit(False) # Create records here. # # [...] context = { 'approve': approve, } return render(request, 'accept.html', context) Based on my understanding of the documentation, I thought that this would work. However, it does not do as I expected, so I suspect my understanding is flawed. If I comment out transaction.set_autocommit(False) then the data are committed, but immediately rather than after being approved. If transaction.set_autocommit(False) is included then no data are committed at all. Is the problem perhaps due to … -
How to get 'requests' object in custom function in django
I have created one library file where I have created one function suppose : def myfunc(param1): ---- --- do something ---- Now If I require requests object (to get details of user or something like that), How can I get requests object without passing parameter in my function. Note : As of now I am adding requests in my parameters (shown as below) but is there any other method as If I am calling this function to any other function I might not have requests object. def myfunc(requests,param1): ---- --- do something ---- -
Installing rpy2 with Docker is unable to find R path
A Django application using Docker needs to install rpy2 as a dependency. Although I install r-base container and specify it as a dependency, when installing django requirements I keep getting: Collecting rpy2==2.8.3 (from -r /requirements/base.txt (line 55)) Downloading rpy2-2.8.3.tar.gz (186kB) Complete output from command python setup.py egg_info: Error: Tried to guess R's HOME but no command 'R' in the PATH. How can specify inside Docker where the R path is? My server.yml looks like this: version: '2' services: r: build: ./services/r django: build: context: ./myproject/ dockerfile: ./compose/django/Dockerfile env_file: - .env - .env-server environment: - DATABASE_URL=postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_USER} depends_on: - postgres - r command: /gunicorn.sh volumes: - ./myproject:/app The Dockerfile for django is: FROM python:2.7 ENV PYTHONUNBUFFERED 1 COPY ./requirements /requirements RUN pip install -r /requirements/production.txt \ && pip install -r /requirements/test.txt \ && groupadd -r django \ && useradd -r -g django django COPY . /app RUN chown -R django /app COPY ./compose/django/gunicorn.sh /gunicorn.sh COPY ./compose/django/entrypoint.sh /entrypoint.sh RUN sed -i 's/\r//' /entrypoint.sh \ && sed -i 's/\r//' /gunicorn.sh \ && chmod +x /entrypoint.sh \ && chown django /entrypoint.sh \ && chmod +x /gunicorn.sh \ && chown django /gunicorn.sh WORKDIR /app ENTRYPOINT ["/entrypoint.sh"] The Dockerfile for R is: FROM r-base -
Crispy forms layout different in local server and Ubuntu server
I am using crispy forms in my django forms and formset. It Worked as expected in the local server when run the same project in Ubuntu server its layout is different. For example, I am created a two column form using following code: class MemberForm(ModelForm): class Meta: model = Person exclude =('user',) def __init__(self, *args, **kwargs): super(MemberForm, self).__init__(*args, **kwargs) self.fields['name'].widget.attrs['placeholder'] = 'Your full name. 100 characters.' self.fields['tele_land'].label = 'Land phone' self.fields['tele_cell'].label = 'Cell phone' self.fields['passing_year'].label = 'Passing year' self.fields['passing_year'].help_text = 'According to your session year' self.helper = FormHelper() self.helper.form_method = 'POST' self.helper.form_tag = False self.helper.layout = Layout( Div( Div('name', 'name_in_bangla', 'nick_name', 'birth_date','blood_group','present_address','permanent_address','tele_land','tele_cell','photo','admission_session','degree_obtained','passing_year', 'category','is_active',css_class='col-md-5'), Div(css_class='col-xs-2'), Div('payment_number','bank_name','branch_name','profession', 'Designation', 'organization', 'official_address','office_phone', 'office_mobile','office_email','office_fax',' website','father_name','mother_name','is_married','national_id_no','passport_no','spouse_name','spouse_blood_group', css_class='col-md-5'), css_class='row-crispy' ), In localhost:8000 it gives two columns form but in Ubuntu server it gives one column form which is not desired. In another form it didn't show slug field which is shown by the localhost. Does anyone suggest me what will get rid of this behavior. -
Python Social Auth duplicating e-mails for different users
In my website it is possible to login through: username and password e-mail and password google auth 2 facebook Where I am using django user built in system and python social auth. The problem: Suppose I create the following account: username: losimonassi e-mail: lorenzosimonassi@gmail.com Then when I try to login with my gmail (lorenzosimonassi@gmail.com) python social auth creates another user with the same e-mail. So, when I try to login using my e-mail the auth system finds two similar e-mails which raises an error. I am trying to find a way that when the user try to login with gmail his e-mail is checked against the DB and if it already exists the process is stopped with a redirect and a alert message (I think it could be made through the middleware). But of course the checking against the DB should only check against other backends users and normal users, to avoid blocking his own login. I don't want to associate the accounts. settings.py SOCIAL_AUTH_PIPELINE = ( 'social.pipeline.social_auth.social_details', 'social.pipeline.social_auth.social_uid', 'social.pipeline.social_auth.auth_allowed', 'social.pipeline.social_auth.social_user', 'social.pipeline.user.get_username', 'social.pipeline.user.create_user', #'social.pipeline.social_auth.associate_user', #'social.pipeline.social_auth.load_extra_data', 'social.pipeline.user.user_details' ) enter image description here -
How to create a python dictionary using user id in django?
i'm a beginner in programming and i've got an impediment, so basically i want to create something like this set = { user_id_1 : 'result_user_id_1', user_id_2 : 'result_user_id_2', user_id_3 : 'result_user_id_3' } Simplified i want each user to have it's score in the dictionary. result is from mytags (teamplatetags) and it's a score that all the users are giving a score for eachother in order to obtain a final score. models.py from django.db import models from django.conf import settings VALOARE = ( (1, "Nota 1"), (2, "Nota 2"), (3, "Nota 3"), (4, "Nota 4"), (5, "Nota 5"), (6, "Nota 6"), (7, "Nota 7"), (8, "Nota 8"), (9, "Nota 9"), (10, "Nota 10"), ) class Punctaj(models.Model): acordat_de = models.ForeignKey(settings.AUTH_USER_MODEL, default=0) acordat_catre = models.ForeignKey(settings.AUTH_USER_MODEL, default=0, related_name="acordat_catre") nota = models.PositiveSmallIntegerField(default=0, choices=VALOARE) views.py def home(request): data = dict() data['users']=User.objects.all() if request.method == "POST": for key in request.POST: if 'nota_' in key: nota_acordata = Punctaj.objects.filter(acordat_de=request.user, acordat_catre__id=key.split('_')[1]).first() if nota_acordata: nota_acordata.nota = request.POST.get(key) nota_acordata.save() else: Punctaj.objects.create(acordat_de=request.user, acordat_catre_id=key.split('_')[1], nota=request.POST.get(key)) messages.success(request,"Successfully Voted") return redirect('home') return render(request, "login/home.html", data) mytags.py - templatetag @register.simple_tag def results(user): suma = Punctaj.objects.filter(acordat_catre=user).aggregate(punctaj=Sum('nota')).get("punctaj") count = Punctaj.objects.filter(acordat_catre=user).count() if not suma: result = 0 else: result = int(suma)/count return result template <form class ="nota" method="POST" action="">{% csrf_token … -
DRF: JSONField in serializers with TextField in models cause stringification
I am using python 2.7.11 A have a model let's say Game that has a TextField that's supposed to store json values. TextField was chosen because the database is shared with hibernate ORM that doesn't support postgres JSONb natively. Thus I have: models.py: @python_2_unicode_compatible class Game(models.Model): settings = models.TextField(default='{}') serializers.py: class GameSerializer(serializers.ModelSerializer): settings = serializers.JSONField() Is there a clean way to handle this, having valid json strings in the database and returning them as json objects through the API? -
Set environment variable for Django project in windows10
I have currently worked on two Django project. when I tried to runserver for the second project it run the setting on the first one. Do I need to set the environment separatly or not.. but for now I already set the environment variables and the result still same.. what is the mistake? -
Django serializer call a funtion
i have class ProfileSerializer(serializers.ModelSerializer): relevence = ?? the thing is i want to call relevance as a separate function. I do not want to write as a serialiser method field nor under a model,can it be done? -
template folder in django not recognized digital ocean
the problem that I have is that this is my project tree: django_project |-- circuitos | |-- admin.py | |-- apps.py | |-- __init__.py | |-- migrations | | |-- 0001_initial.py | | |-- 0002_auto_20161031_1107.py | | |-- 0003_circuito_imagen_trazado.py | | |-- 0004_circuito_fecha_evento.py | | |-- 0005_auto_20161111_1025.py | | |-- 0006_auto_20161111_1026.py | | |-- 0007_auto_20161111_1028.py | | |-- 0008_auto_20161111_1133.py | | |-- __init__.py | | `-- __pycache__ | | |-- 0001_initial.cpython-35.pyc | | |-- 0002_auto_20161031_1107.cpython-35.pyc | | |-- 0003_circuito_imagen_trazado.cpython-35.pyc | | |-- 0004_circuito_fecha_evento.cpython-35.pyc | | |-- 0005_auto_20161111_1025.cpython-35.pyc | | |-- 0006_auto_20161111_1026.cpython-35.pyc | | |-- 0007_auto_20161111_1028.cpython-35.pyc | | |-- 0008_auto_20161111_1133.cpython-35.pyc | | `-- __init__.cpython-35.pyc | |-- models.py | |-- __pycache__ | | |-- admin.cpython-35.pyc | | |-- __init__.cpython-35.pyc | | |-- models.cpython-35.pyc | | |-- urls.cpython-35.pyc | | `-- views.cpython-35.pyc | |-- tests.py | |-- urls.py | `-- views.py |-- django_project | |-- __init__.py | |-- __init__.pyc | |-- settings.py | |-- settings.pyc | |-- settings.pye | |-- urls.py | |-- urls.pyc | |-- wsgi.py | `-- wsgi.pyc |-- equipos | |-- admin.py | |-- apps.py | |-- __init__.py | |-- migrations | | |-- 0001_initial.py | | |-- 0002_remove_equipo_slug.py | | |-- 0003_equipo_imagen_equipo.py | | |-- __init__.py | | `-- … -
Azure web service and Django log
I got some confuse question for writing log.... Below are my setting.py: DEBUG = True## Heading ## TEMPLATE_DEBUG = DEBUG ..... LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, 'logfile': { 'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.getenv('LOGFILE', 'django.log') } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, 'django': { 'handlers': ['logfile'], 'level': 'INFO', 'propagate': False, } } } ** I want passes all INFO messages to django.log. It will correctly write django.log when I running server at localhost test. After I publish to Azure web app service, and set the "Application setting " => "App settings", add new path LOGFILE D:\home\site\wwwroot\logfiles\django.log. I send a few request to my app service, then log in DebugConsole to watch the D:\home\site\wwwroot\logfiles\django.log file. There has no any content in this log file (django.log), and I try to modify it at DebugConsole, it will occurs ERROR 409 confict: Could not write to local resource 'D:\home\site\wwwroot\logfiles\django.log' due to error 'The process cannot access the file 'D:\home\site\wwwroot\logfiles\django.log' becaure it is being used by another process.'. It seem like Django cannot write anything in django.log, how … -
Reverse for 'results' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'library/(?P<student_id>[0-9]+)/results/$']
i am getting the following error while running the django server- Reverse for 'results' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'library/(?P[0-9]+)/results/$'] note: the error goes off if i remove the line from index.html file. But without this, i cannot do the post request . this is my result.html template <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> hey {{ student.name }} </body> </html> my views.py file from django.http import Http404 from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from django.template import loader from .models import Student, Choice from django.urls import reverse def vote(request, student_id): student = get_object_or_404(Student, pk=student_id) try: selected_choice = Student.Choice_set.get(pk=request.POST['Choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'library/results.html', { 'student': student, 'error_message': "You didn't select a choice.", }) else: selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('library:results', args=(student.id,))) def index(request): students_list = Student.objects.all() template = loader.get_template('library/index.html') context = { 'students_list': students_list, } return HttpResponse(template.render(context, request)) def detail(request, student_id): try: student = Student.objects.get(pk=student_id) except Student.DoesNotExist: raise Http404("Student does not exist") return render(request, 'library/detail.html', … -
'dict' object has no attribute 'HTTP_REFERER'
I've been trying to find the previous url following this answer: Django request to find previous referrer So, in my .py I did: print request.META print request.META.HTTP_REFERER print request.META['HTTP_REFERER'] request.META returns: {'RUN_MAIN': 'true', 'HTTP_REFERER': 'http://127.0.0.1:8000/info/contact/', 'XDG_GREETER_DATA_DIR': '/var/lib/lightdm-data/user', 'QT4_IM_MODULE': 'xim',.... So, I can see HTTP_REFERER is there, but when trying to access it either way I get the error: <type 'exceptions.AttributeError'> 'dict' object has no attribute 'HTTP_REFERER' How can I access it? -
Heroku application error: (Django) cannot find VLC module
I am creating a django web application which uses vlc to play audio. Everything works locally and I tried to deploy it via heroku. I used heroku-buildpack-apt to install the vlc apt dependencies onto heroku. Everything went smoothly and it deployed successfully and said all the dependencies were installed, but whenever I try to run it on the web server it returns with an error. These are the heroku log files after I try to run 2016-11-16T07:42:42.439116+00:00 app[web.1]: Unhandled exception in thread started by <function wrapper at 0x7f35330158c0> 2016-11-16T07:42:42.439122+00:00 app[web.1]: Traceback (most recent call last): 2016-11-16T07:42:42.439126+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper 2016-11-16T07:42:42.439191+00:00 app[web.1]: fn(*args, **kwargs) 2016-11-16T07:42:42.439210+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run 2016-11-16T07:42:42.439259+00:00 app[web.1]: self.check(display_num_errors=True) 2016-11-16T07:42:42.439262+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 374, in check 2016-11-16T07:42:42.439356+00:00 app[web.1]: include_deployment_checks=include_deployment_checks, 2016-11-16T07:42:42.439360+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 361, in _run_checks 2016-11-16T07:42:42.439449+00:00 app[web.1]: return checks.run_checks(**kwargs) 2016-11-16T07:42:42.439488+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks 2016-11-16T07:42:42.439506+00:00 app[web.1]: new_errors = check(app_configs=app_configs) 2016-11-16T07:42:42.439523+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/checks/urls.py", line 14, in check_url_config 2016-11-16T07:42:42.439549+00:00 app[web.1]: return check_resolver(resolver) 2016-11-16T07:42:42.439567+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/checks/urls.py", line 24, in check_resolver 2016-11-16T07:42:42.439595+00:00 app[web.1]: for pattern in resolver.url_patterns: 2016-11-16T07:42:42.439598+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/utils/functional.py", line 35, in __get__ 2016-11-16T07:42:42.439649+00:00 app[web.1]: res = instance.__dict__[self.name] = self.func(instance) 2016-11-16T07:42:42.439650+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/urls/resolvers.py", line … -
How can I loop through Django management command *args?
I have the following code: class Command(BaseCommand): help = 'Build static site output.' def add_arguments(self, parser): parser.add_argument('args') def handle(self, *args, **options): """Request pages and build output.""" if args: pages = args available = list(get_pages()) invalid = [] for page in pages: if page not in available: invalid.append(page) if invalid: msg = 'Invalid pages: {}'.format(', '.join(invalid)) raise CommandError(msg) else: ... However when I run this command: python prototypes.py build index the command loops through each letter of the word index. CommandError: Invalid pages: i, n, d, e, x I want it to detect index as one argument and if I provide more arguments with spaces in between it should be looping through those. If I don't add the add_arguments method it shows unrecognized argument in the console. -
migrations on django server 1.9 failing
I deployed my Django 1.9 project to Webfaction using FTP a few months ago. However I wanted to start automating the deployment process and so managed to link my existing deployment on Webfaction to my bitbucket repo. My local env is still working fine, can makemigrations and migrate without errors. However, it appears a few migrations in the past don't quite exactly match up, and so extra migrations were copied across when I did a git pull on Webfaction. Now I cannot run makemigrations or migrate on Webfaction anymore - I get the error CommandError: Conflicting migrations detected; multiple leaf nodes in the migration graph: (0016_auto_20161030_1228, 0003_auto_20161030_1638 in locations). To fix them run 'python manage.py makemigrations --merge If I run this command, I see the following prompt: Merging locations Branch 0016_auto_20161030_1228 - Add field added_by to location - Change managers on location - Add field latlng to location - Add field address to location - Alter field latitude on location - Alter field longitude on location - Alter field country on location Branch 0003_auto_20161030_1638 - Add field added_by to location - Change managers on location - Add field address to location - Add field latlng to location - Alter field … -
Django - order many to many relation on id of intermediary model without using through
I am facing issue while sorting many to many field. I have many to many relationship on hobbies field. I want to keep the order user adds the hobbies. This can be done by sorting the records on intermediate model id. May people suggested to use through and add some field for ordering. But this creates problem while I create records using add function of related model. Is there any way to provide meta ordering to intermediary model so it can sort by id when I access data. My model is as - class User(AbstractBaseUser, PermissionsMixin): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) hobbies = models.ManyToManyField('UserHobby') class UserHobby(models.Model): hobby = models.CharField(max_length=100) -
Django Row Level Locking For Model Forms
I am using Python 3.5, Django 1.8 and PostgreSql 9.4. So I have one edit method where in get request I am rendering form and when user submit form it will get updated. Hers's the code def edit_case(request, case_id): case = get_object_or_404(Case, pk=case_id) if request.method == 'POST': data = request.POST.copy() form = CaseEditForm(data, instance=case) if form.is_valid(): res = form.save() return HttpResponseRedirect(reverse("case_list")) else: form = CaseEditForm(instance=case) variables = RequestContext(request, { "form": form, }) return render_to_response( 'sample/edit_case.html', variables, ) Now I want to add row level locking on it like if one user is updating something at the same time other will not be able update anything unless previous transaction succeeded Or if someone have any other better suggestions rather then using Pessimistic Locking. I know about select_for_update but don't have any idea how it will get implemented in case of form.save() Any help would be really appreciated -
django using uuid primary key to access linked models
Trying to come to grips with Django (from php or .Net past) and finding it a little challenging. If have created the following models: class Member(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) def __str__(self): return self.last_name + ", " + self.first_name class Organisation(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=140) def __str__(self): return self.name class Membership(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False) member_id = models.ForeignKey('Member', on_delete=models.DO_NOTHING) organisation_id = models.ForeignKey('Organisation', on_delete=models.DO_NOTHING) membership_no = models.CharField(max_length=20) class Meta: unique_together = (("organisation_id", "member_id"), ("organisation_id", "membership_no")) def __str__(self): mbr = Member.objects.get(pk=self.member_id) org = Organisation.objects.get(pk=self.organisation_id) return str(org) + ": " + str(mbr) The problem occurs when I try to view/edit the Membership models in Admin. I get the error: TypeError at/admin/membership/membership Exception Value: 'Anderson, Roy' is not a valid UUID. I am using Django version 1.10.3. Now the string 'Anderson, Roy' happens to be one of the database entries for the Member model and appears to do the value returned by the str function for the Member model. However I don't know why it is trying to use it as a UUID. I am trying to user string values from the Member and Organisation models to create the return value (str … -
How to set gunicorn limit_request_line parameter over 8190?
I need to post large text fragment to web-application beside gunicorn. But gunicorn failed requests that large 8190 request line. This constant hardcoded this https://github.com/benoitc/gunicorn/blob/master/gunicorn/http/message.py#L20 And used this line: https://github.com/benoitc/gunicorn/blob/master/gunicorn/http/message.py#L146 How can redefine behavior? -
Testing related page in Wagtail
I've got a ContentPage model in wagtail and a RelatedPost model that links other ContentPage models to ContentPage a bit like this: class ContentPage(Page): summary = RichTextField(blank=True) body = RichTextField(blank=True) published = models.DateTimeField(default=timezone.now()) content_panels = Page.content_panels + [ FieldPanel('summary'), FieldPanel('body', classname="full"), InlinePanel('related_page', label="Related Content"), ] settings_panels = Page.settings_panels + [ FieldPanel('published'), ] class RelatedPost(Orderable): post = ParentalKey( 'ContentPage', related_name='related_page' ) page = models.ForeignKey( 'ContentPage', null=True, blank=True, on_delete=models.SET_NULL, related_name="+" ) panels = [ FieldPanel('page') ] When I run this test: class ContentPageTests(WagtailPageTests): def test_can_create_article_page(self): self.assertCanCreateAt(ContentIndexPage, ContentPage) # content_index is just a parent page content_index = self.create_content_index_page() self.assertCanCreate(content_index, ContentPage, { 'title': 'Test Article', 'published': datetime.datetime.now() }) I get an error saying: django.core.exceptions.ValidationError: ['ManagementForm data is missing or has been tampered with'] The admin works fine. I can save related pages etc and when I comment out the InlinePanel line it works fine. -
Getting object has no attribute error when creating admin reg in django
I have been getting this error only when creating my first user, which is suppose to become the admin user. How can i fix this? Error: response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/Johnny/Desktop/pythondjango/django/user_dashboard/apps/login/views.py", line 18, in register regstatus = User.userManager.register(**request.POST) File "/Users/Johnny/Desktop/pythondjango/django/user_dashboard/apps/login/models.py", line 43, in register new_user.update(user_level='admin') AttributeError: 'User' object has no attribute 'update' code: views.py def register(request): regstatus = User.userManager.register(**request.POST) if regstatus[0]: request.session['user_id'] = regstatus[1] return redirect(reverse('dashboard:index')) else: for message in regstatus[1]: messages.warning(request, message) return redirect(reverse('login:index')) models.py: new_user = self.create(email=email, first_name=first_name, last_name=last_name, password=pw_hash) # Make first registered user an admin if new_user.id == 1: new_user.update(user_level='admin') return (True, new_user.id) These two snippets of code is where my errors are currently happening. Any help is greatly appreciated -
python django splitting models into separate files
I'm stumbling through learning python (3.5.2) and django (1.10.3). I have a project and that project has my first app. It is a member's area. I anticipate that this app will have a number of models and I like the idea of splitting the models out into their own files. I have seen an explanation of this here: https://code.djangoproject.com/wiki/CookBookSplitModelsToFiles -- MyApplication |-- __init__.py |-- settings.py |-- urls.py |-- wsgi.py -- Members |-- __init__.py |-- admin.py |-- apps.py |-- migrations | |-- __init__.py |-- models | |-- __init__.py | |-- address.py |-- tests.py |-- urls.py |-- views.py -- manage.py Members/models/__init__.py looks like from address import Address Members/models/address.py looks like from django.db import models class Address(models.Model): Member_ID = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) Order = models.PositiveIntegerField() ... MyApplication/Settings.py has INSTALLED_APPS = [ 'Members.apps.MembersConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ... When I go to try to setup the DB migrations though I get $ python manage.py makemigrations Members Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/myUser/.pyenv/versions/3.5.2/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/myUser/.pyenv/versions/3.5.2/lib/python3.5/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/home/myUser/.pyenv/versions/3.5.2/lib/python3.5/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/myUser/.pyenv/versions/3.5.2/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/home/myUser/.pyenv/versions/3.5.2/lib/python3.5/site-packages/django/apps/config.py", line 199, in … -
Bootstrap snippet does not show in visual studio 2015 toolbox
Please, kindly assist. I have installed Bootstrap snippet in visual studio 2015 community edition but it does not show up in the toolbox so that i can drag n drop component. I am writing a django web application. -
Why is the following Django URLConf regex not working?
URLConf urlpatterns = [ url(r'^(?P<slug>[\w./-]+)/$', page, name='page'), url(r'^$', page, name='homepage'), ] views.py def page(request, slug='index'): """Render the requested page if found.""" print slug file_name = '{}.html'.format(slug) page = get_page_or_404(file_name) context = { 'slug': slug, 'page': page, } return render(request, "page.html", context) You see that I'm printing the slug at the very first line of view. It prints the slug if I don't pass any parameter, however when I do pass a parameter in the URL, even if it is the default index, it shows Page Not Found.