Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Auth add placeholder in the login form
I was following this tutorial for Django login: https://wsvincent.com/django-user-authentication-tutorial-login-and-logout/ Here is what the code look like to enable login using django auth urls.py: from django.contrib import admin from django.urls import path, include from django.views.generic.base import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('customers/', include('django.contrib.auth.urls')),] and created a templates/registration/login.html template I want to add placeholder string in the login page for username and password. I tried subclassing the AuthenticationForm (suggested here: Django adding placeholders to django built in login forms) but I am not sure how to make the changes in the urls.py. I do not want to impact the other forms that come with the Django such as auth password_change etc. Note I am using Django 2.1.5 and python 3.6 -
Getting an error while building a register page, AttributeError at /register/ 'RegisterForm' object has no attribute 'cleaned_data'
I am building a registration page using Python 2.7.15 && Django 1.11.18, but continue to get the error: AttributeError at /register/ 'RegisterForm' object has no attribute 'cleaned_data' I've looked through other very similar posts, tried the suggestions, but still I am not getting a functional result. To me it looks like everything is in order, but it is not. Below you will find my code, thanks. Views.py looks like: def register_page(request): form = RegisterForm(request.POST or None) context = { "form": form } if form.is_valid(): form.save() print(form.cleaned_data) username = form.cleaned_data.get("username") email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") new_user = User.objects.create_user(username, email, password) print(new_user) return render(request, "auth/register.html", context) forms.py looks like: class RegisterForm(forms.Form): username = forms.CharField() email = forms.EmailField() password = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput) def clean(self): data = self.cleaned_data password = self.cleaned_data.get('password') password2 = self.cleaned_data.get('password2') if password2 != password: raise forms.ValidationError("Passwords must match.") return data urls.py looks like: from django.conf.urls import url from django.contrib import admin from .views import home_page, about_page, contact_page, login_page, register_page urlpatterns = [ url(r'^$', home_page), url(r'^about/$', about_page), url(r'^contact/$', contact_page), url(r'^login/$', login_page), url(r'^register/$', register_page), url(r'^admin/', admin.site.urls), ] What am I missing here? -
How to force Django models to be released from memory
I want to use a management command to run a one-time analysis on the buildings in Massachusetts. The heavily simplified version of my code is as follows: zips = ZipCode.objects.filter(state='25').order_by('id') for zip in zips.iterator(): print('mem', process.memory_info().rss) # in bytes buildings = Building.objects.filter(boundary__within=zip.boundary) output = [] for building in buildings.iterator(): # Analysis would go here output.append(building) output = None When I run this exact code, I get the following output: mem 328777728 mem 331837440 mem 610684928 <-- The zipcode before this had a lot of buildings mem 609325056 <-- But this one was tiny... mem 608276480 mem 511086592 ... It seems like the output list is hogging up memory (with some slow decay), even though I'm trying everything I can think of to release memory. I've tried using del, gc.collect(), etc. to no avail. So, my question is: How can I force Python to release this array of Django models? Or, where else might the memory leak be? -
Django-filter __in lookup
class ProductFilter(django_filters.FilterSet): label = django_filters.LookupChoiceFilter( lookup_choices=[ ('contains', 'Contains'), ('in', 'In') ] ) class Meta: model = Product fields = ['label'] class ListProduct(generics.ListAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer filter_backends = (django_filters.rest_framework.DjangoFilterBackend,) filter_class = ProductFilter "http://localhost:8000/api?label=foo&label_lookup=contains" works fine but "http://localhost:8000/api?label=foo,bar&label_lookup=in" returns an empty list. I tried different approaches but couldn't make it work. Any solution? -
pandasticsearch and python function TypeError: 'NoneType object is not subscriptable'
I am having some trouble debugging an issue I'm experiencing with my Django application. My models.py file calls on a function defined in another file (), and somewhere along the way the pandas DataFrame within it is being re-classified as a NoneType. When I test the function by itself in my jupyer notebook there isn't an issue, but then when I test my models code that calls the function it errors out. substitution file import pandas as pd import json from elasticsearch import Elasticsearch from pandasticsearch import Select def subfunction(user_id): es=Elasticsearch() query = {"query": {"match": {"userprofile_id": user_id}}} index = "client_user_profile" search=es.search(index=index, doc_type='client_data', body=query, size=10000) # Extract data into Dataframe sf=Select.from_dict(search).to_pandas() sf=sf[['userprofile_id', 'Username', 'FirstName', 'LastName']] sf.reset_index(inplace=True) sf.drop(columns=sf[['index']], inplace=True) ans='Not on file' for i in range(len(sf['userprofile_id'])): if sf['userprofile_id'][i]==user_id: ans=sf['Username'][i] if '@' in ans: ans=ans.split('@') ans=ans[0].replace('<','\\') return ans models.py (the section that calls the function) # Import libraries from django.http import HttpResponse import json import pandas as pd from elasticsearch import Elasticsearch from pandasticsearch import Select from substitution import subfunction ... elif ('subfunction EQUALS' in sr): sl_sr=sr.split('subfunction EQUALS') user_id=subfunction(modeldf['UserId'][i]) txt+='\n'+' - User: '+str(user_id) modeldf['Action'][i]=txt error message --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-14-16c8b8610d51> in <module> 163 elif ('subfunction EQUALS' in sr): 164 … -
How do I reload a module in the Python console?
I'm using PyCharm with Python 3.7. In my Python console, how do I reload a module that I've changed? I created a file, "services.py" where I created a service class in class ArticlesService: def process(self): As I test this in the console, I can't seem to figure out how to reload it. This is the error I get from mainpage.services import ArticlesService importlib.reload(ArticlesService) Traceback (most recent call last): File "<input>", line 1, in <module> File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 140, in reload raise TypeError("reload() argument must be a module") TypeError: reload() argument must be a module How do I refer to my class to reload it? (Or better yet, how do I get the console to automatically reload everything I've changed?) -
Django (backend) + Angular (fronend) best practice for storing angular code within Django framework?
What would be considered best practice for storing the following Angular code structure in a Django backend framework?: . ├── ./README.md ├── ./angular.json ├── ./e2e ├── ./node_modules ├── ./package-lock.json ├── ./package.json ├── ./run_servers.sh ├── ./src ├── ./ssl ├── ./tsconfig.json └── ./tslint.json All of the above is just Angular, the following is Django: . ├── ./bin ├── ./include ├── ./lib └── ./src -
Please see below
Please see below and tell me how can i move further? pa_autoconfigure_django.py https://github.com/StruSak/my-first-blog.git < Running API sanity checks > \ ~<:>>>>>>>>> Traceback (most recent call last): File "/home/StruSak/.local/bin/pa_autoconfigure_django.py", line 52, in main(arguments[''], arguments['--domain'], arguments['--python'], nuke=arguments.get('--nuke')) File "/home/StruSak/.local/bin/pa_autoconfigure_django.py", line 34, in main project.sanity_checks(nuke=nuke) File "/home/StruSak/.local/lib/python3.6/site-packages/pythonanywhere/project.py", line 31, in sanity_checks domain=self.domain pythonanywhere.exceptions.SanityException: You already have a virtualenv for strusak.pythonanywhere.com. Use the --nuke option if you want to replace it. The first line i entered ,I want to replace the existing virtualenv,the system is telling to use --nuke option but i don't know how to. -
Get related items while looping in Django template
I am trying to access a related object (PaymentDetail if it exists) while looping through a _set list of objects (Registrations). My models look like this: models class Registration(models.Model): person = models.ForeignKey(Person, on_delete=models.PROTECT) course_detail = models.ForeignKey( CourseDetail, on_delete=models.PROTECT ) comments = models.CharField(max_length=200, blank=True, null=True) def __str__(self): return '%s' % (self.course_detail.course.name) class PaymentDetail(models.Model): payment = models.ForeignKey(Payment, on_delete=models.PROTECT) registration = models.ForeignKey( Registration, on_delete=models.PROTECT) In my views I'm just getting a queryset of desired people and passing it to the template (these display fine). view def index(request, **kwargs): people = Person.get_related_people(request.user.id).order_by('first_name') return render(request, 'people_app/index.html', { 'people': people, }) As I am looping through them in the template - I am displaying the associated Registrations for these people. While I'm looping through those registrations - I'm trying to see if there is a PaymentDetail associated with that Registration In my template I'm looping through the registration_list like this: template {% for person in people %} {% for registration in person.registration_set.all %} {{ registration.id }} {% if registration.paymentdetail_set|length > 0 %} PAID {% else %} NO PAYMENT {% endif %} {% endfor %} {% endfor %} As you may imagine - this doesn't work and always shows as NO PAYMENT even when the PaymentDetail exists. -
Django get_or_create() returning odd behaviour
I'm running into a strange error when trying to get or create an object through get_or_create() ValueError: Cannot assign "(<CaseStatus: CaseStatus object (13)>,)": "PatientCase.status" must be a "CaseStatus" instance. object "status": { "uuid": "233f02e474af40abbe909e15e5304e3d", "message": "pending" }, function processing the data def get_case_status(status_data): defaults = { "status": status_data['message'], "status_message": generate_status_message(status_data['message']), } if status_data.get('extra_data'): defaults['extra_data'] = status_data['extra_data'] status, created = CaseStatus.objects.get_or_create( uuid=status_data['uuid'], defaults = defaults ) return status -
Get different forms in view based on condition
Suppose I have forms as below : class FormA(models.ModelForm): ... class FormB(models.ModelForm): .... class FormC(models.ModelForm): ..... Now I want to get the forms in the single view as : Class FormCreateView(CreateView): model = User def post(self, request, *args, **kwargs): if self.request.user.user_level == 1: get FormA if self.request.user.user_level == 2: get FormB if self.request.user.user_level == 3: get Formc return reverse('xyz') -
Django - How to set the request in the admin form?
I have a form that uses the request object: class FooForm(forms.ModelForm): class Meta: model = Foo fields = ('title', ) def __init__(self, *args, **kwargs): self.request = kwargs.pop('request') super().__init__(*args, **kwargs) In my views, whenever I want to instantiate the form, it is as easy as doing the following: class FooCreateView(LoginRequiredMixin, CreateView): model = Foo form_class = FooForm def get_form_kwargs(self): kwargs = super(FooCreateView, self).get_form_kwargs() kwargs.update({'request': self.request}) return kwargs Now, I want to use the same form in the admin panel, so I do the following: class FooAdmin(admin.ModelAdmin): form = FooForm But Boom! It dies: KeyError at /admin/foo/foo/add/ 'request' I tried to do the following, but it didn't work def get_form(self, request, *args, **kwargs): form = super(FooAdmin, self).get_form(request, *args, **kwargs) form.request = request kwargs['request'] = request return form In summary, is there a way to pass the request to the admin form? -
Page not found (404) Using the URLconf defined in project.urls, Django tried these URL patterns, in this order:
In my rest API, I have added some data to table userdetails through http://127.0.0.1:8000/admin/eatslushapp/userdetails/add/ but when I click the http://127.0.0.1:8000/userdetails I am getting the following result https://i.imgur.com/Drtab69.png I tried this by watching this tutorial https://www.youtube.com/watch?v=ejJ-2oz4AgI NB:The admin url works fine The following is my urls.py from django.conf.urls import url from django.contrib import admin from rest_framework.urlpatterns import format_suffix_patterns from eatslushapp import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^userdetails/', views.userdetailsList.as_view()), ] I just want to get my data in json format -
Django-Bootstrap : form modal close button doesn't work
customer.html is like my index page. Here I have created the the button which shows the modal and also the with "modal fade" classes customer.html <div class="m-portlet__head-tools"> <ul class="m-portlet__nav"> <li class="m-portlet__nav-item"> <div class="m-dropdown m-dropdown--inline m-dropdown--arrow m-dropdown--align-right m-dropdown--align-push" m-dropdown-toggle="hover" aria-expanded="true"> <a href="#" class="m-portlet__nav-link btn btn-lg btn-secondary m-btn m-btn--icon m-btn--icon-only m-btn--pill m-dropdown__toggle"> <i class="la la-plus m--font-brand"></i> </a> <div class="m-dropdown__wrapper"> <span class="m-dropdown__arrow m-dropdown__arrow--right m-dropdown__arrow--adjust"></span> <div class="m-dropdown__inner"> <div class="m-dropdown__body"> <div class="m-dropdown__content"> <ul class="m-nav"> <li class="m-nav__section m-nav__section--first"> <span class="m-nav__section-text ">Quick Actions</span> </li> <li class="m-nav__item"> <!-- The button which shows the modal, notice the href attribute --> <a href="{% url 'customer_new' %}" class="m-nav__link " data-toggle="modal" data-target="#modal"> <i class="m-nav__link-icon flaticon-add"></i> <span class="m-nav__link-text">Modal</span> </a> </li> <li class="m-nav__separator m-nav__separator--fit m--hide"> </li> </ul> </div> </div> </div> </div> </div> </li> </ul> </div> <div class="m-portlet__body"> <!--begin: Datatable --> <!--begin:: Modal --> <div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-hidden="true"></div> <!--end:: Modal --> </div> The customer_form.html contains the modal-dialog and the button "Close" that I'm trying to make work. As you can see below I used the data-dismiss="modal", but it doesn't work. When I click on it there is no action in the modal form. But if I fill the fields and press the "Save" button the data is writen into the DB. <h1>customer_form.html</h1> … -
How can I annotate two models in one ListView?
I'm able to annotate my Company model data but I also need a fast way to query for my contacts data in my views.py. Currently my page is taking around 10s to load. I'm looking for a way to access the contacts faster. models.py class Company(models.Model): name = models.CharField(max_length=150) bic = models.CharField(max_length=150, blank=True) class Contact(models.Model): company = models.ForeignKey( Company, related_name="contacts", on_delete=models.PROTECT) first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150, blank=True) email = models.EmailField() def get_order_count(self): orders = 0 for order in self.orders.all(): orders += 1 return orders @python_2_unicode_compatible class Order(models.Model): order_number = models.CharField(max_length=150) company = models.ForeignKey(Company, related_name="orders") contact = models.ForeignKey(Contact, related_name="orders") total = models.DecimalField(max_digits=18, decimal_places=9) views.py class IndexView(ListView): template_name = "mailer/index.html" def get_queryset(self): model = Company.objects.annotate( order_count=Count('orders')).annotate( order_sum=Sum('contacts__orders__total')) return model paginate_by = 100 template {% for company in company_list %} <tr id="company-row"> <th id="company-name" scope="row">{{ company.name }}</th> <td>{{ company.order_count }}</td> <td id="order-sum">{{ company.order_sum|floatformat:2 }}</td> <td class="text-center"><input type="checkbox" name="select{{company.pk}}" id=""></td> </tr> {% for contact in company.contacts.all %} <tr id="contact-row"> <th scope="row">&nbsp;</th> <td>{{ contact.first_name }} {{ contact.last_name }}</td> <td id="contact-orders">Orders: {{ contact.get_order_count}}</td> <td></td> </tr> {% endfor %} {% endfor %} -
How to fix defining an 'invalid syntax' error Terminal when using Django to run a server (mac)
Hi I'm setting up a new server in Django using python and with the help of this tutorial (file:///Users/matthewdeyn/projects/helloapp/howdy/templates/index.html). When I try and run the server in terminal (using mac) I get a syntax error concerning the file: urls.py which was made previously in the tutorial. I am new to coding and have tried to search for the answer on google but nothing yet. I also typed in the code for the file in question exactly so am unsure as to the solution. # howdy/urls.py from django.conf.urls import url from howdy import views urlpatterns = [ url(r'^'$, views.HomePageView.as_view()) ] Expected results is that the server will run and previous html code will render when I load the webpage through: http://127.0.0.1:8000/. enter image description here -
No reverse match during post
reverse in the views not returning to urls namespace class UserCreateView(CreateView): model = User # form_class = UserCreationForm template_name = "users/create_user.html" success_url= "/users/create" def get_form_class(self): if self.request.user.user_level == 1 or self.request.user.user_level == 10: form_class = UserCreationForm return form_class elif self.request.user.user_level == 20: form_class = UserCreationFormCompanyManager return form_class else: form_class = UserCreationFormHomeManager return form_class def post(self, request, *args, **kwargs): form = self.get_form_class() user_level = User.objects.get(id=request.user.id) # form = UserCreationFormHomeManager(request.POST) if request.method=='POST': form = UserCreationFormCompanyManager(request.POST) if user_level == 20: if form.is_valid(): obj = form.save(commit=False) obj.company = self.request.user.company obj.password = make_password(form.cleaned_data['password']) obj.save() return obj elif user_level == 30: if request.method=='POST': form = UserCreationFormHomeManager(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.company = self.request.user.company obj.home = self.request.user.home obj.password = make_password(form.cleaned_data['password']) obj.save() return obj else: if request.method=='POST': form = UserCreationFormHomeManager(request.POST) if form.is_valid(): obj.password = make_password(form.cleaned_data['password']) obj = form.save() return obj return reverse('create-user')` urls.py path("create/", view=user_create_view, name="create-user"), Trace back : traceback (most recent call last): File "/home/bishwa/PycharmProjects/sharefile/env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/home/bishwa/PycharmProjects/sharefile/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/bishwa/PycharmProjects/sharefile/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python3.6/contextlib.py", line 52, in inner return func(*args, **kwds) File "/home/bishwa/PycharmProjects/sharefile/env/lib/python3.6/site-packages/django/views/generic/base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "/home/bishwa/PycharmProjects/sharefile/env/lib/python3.6/site-packages/django/views/generic/base.py", line 89, … -
How to resolve django.db.utils.IntegrityError: (1364, "Field 'name' doesn't have a default value")
I'm getting this error from trying to create a superuser for my Django project. Unsure what table requires a default value for its 'name' column. After successfully creating migrations for my Django project I ran python manage.py createsuperuser to create the superuser and got the following error: django.db.utils.IntegrityError: (1364, "Field 'name' doesn't have a default value"). I installed mysql (8.0) am using homebrew on OSX and using python 3 in a virtual env. I'm not sure which database the above command tries to engage, talk less of which table. In any case I have gone through all tables in the db relevant to my project as well as in the mysql database and have run this command on the only name column found: ALTER TABLE django_migrations ALTER COLUMN name SET DEFAULT '-' But I am still getting this error. I have read up on createsuperuser in the Django docs as well as looked into some of the Django code but have gleaned very little of value to solving this. Any help with this would be greatly appreciated. -
PgSQL, Django - history for table with many fields - how to organize properly?
I'm new to Django and not very experienced with PgSQL. I need to create a table with about 10 fields. Thing is that each item I constantly changing and I need to keep a history of changes for each field. For now, I found several solutions for this purpose, but I concerned: 1) https://github.com/arkhipov/temporal_tables Relays on DB and triggers. The concern is that history kept in an additional single table, so each time 1 field is changed it will create a new history record with 9 surplus fields and I intend to show history per field, not per item, so data amount will grow 9 times faster with no purpose. Or DB will optimize it? Also, have images, that naturally have only on/off datetime history. 2) https://github.com/treyhunner/django-simple-history Better, than first, because has integration with Django. Also have lots of features, like Custom history_date(i have lots of snapshots already in files). But still the same concern as 1 3) Manually create the main table with ID and make relation tables for each of fields. Looks like a nightmare for managing. Also, need to perform lots of joins to get current full record(Can Django work with VIEW?) So can you advice better … -
Datatable not displaying using Django-datatable-view
I'm trying to implement datatables.js using django-datatable-view, (not to be confused with django-datatables-view), and have started with the zero configuration datatable type: http://django-datatable-view.appspot.com/zero-configuration/ I've copied the template and view class implementations to my app and the page displays, but without content. The headers are present, but the content is completely absent. If I add the {{ object_list }} to the template, then a truncated list of the queryset objects is displayed, but the table is not rendered. Here is my base.py {% load static i18n %} <html> <head> {% block static %} <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1"> <title>{% block page_title %} MT Raider {% endblock %}</title> <meta name="description" content="{% block description %}{% endblock %}"> <meta content="text/html; charset=utf-8" http-equiv="Content-Type"> <meta name="application-name" content="core-Net.uk" /> {# Bootstrap #} <!-- Bootstrap Core CSS --> <link href="{% static 'core/site/vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet" /> <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script> <!-- toastr --> <link href="{% static 'core/toastr/toastr.min.css' %}" rel="stylesheet" > <!-- Custom Fonts --> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" integrity="sha384-DNOHZ68U8hZfKXOrtjWvjxusGo9WQnrNx2sqG0tfsghAvtVlRW3tvkXWZh58N9jp" crossorigin="anonymous"> <!-- Star rating --> <link rel="stylesheet" href="{% static 'star-ratings/css/star-ratings.css' %}"> <!-- Custom CSS --> <link href="{% static 'core/site/css/site.css' %}" rel="stylesheet" > {# jQuery #} <script src="http://code.jquery.com/jquery-2.0.3.min.js"></script> {# datatables.js #} <script type="text/javascript" charset="utf8" src="http://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script> … -
How to query database items from models.py in Django?
I have different model. Choices of Multiselctfield of one model is dependent on another model.So , database has to be queried inside model.py While doing so, this causes problem in migration. (Table doesn't exist error) class Invigilator(models.Model): --- ---- # this method queries Shift objects and Examroom def get_invigilator_assignment_list (): assignment = [] shifts = Shift.objects.all() for shift in shifts: rooms= ExamRoom.objects.all() for room in rooms: assign = str (shift.shiftName)+ " " +str (room.name) assignment.append (assign) return assignment assignment_choice = [] assign = get_invigilator_assignment_list() i = 0 for assignm in assign: datatuple = (i,assignm) assignment_choice.append(datatuple) i= i+1 ASSIGNMENT_CHOICE = tuple(assignment_choice) assignment =MultiSelectField (choices = ASSIGNMENT_CHOICE, blank = True, verbose_name="Assignments") -
Use django with firestore, Non-relational database
Can I use Firestore with django python being firestore a non-relational database? if it is not the case, Django-non-rel is the option? -
Django admin page login causing IIS to crash, need to restart iis everytime
My site is working fine. I can access all the pages. But when I am accessing admin page, it loads, prompts for username and password. After entering username and password when clicked login, it takes sometimes and after that I get below error: This page isn’t working mytestapp.company.com didn’t send any data. ERR_EMPTY_RESPONSE After refreshing the page, I get below error: Service Unavailable HTTP Error 503. The service is unavailable. After this no page loads. After restarting IIS using cmd (iisreset /noforce) again when I try to refresh the homepage, I see I am logged in which means admin page logged me in but after that response did not come and it something went wrong on the server side which caused server to crash. I am not sure how to proceed with this. Earlier my admin site use to work fine. No recent changes in code. The only change I did is I synced the DB from another DB which has more data. I am using virtual env which has python version is 2.7.3, Django version 1.3 in it IIS version 7.5 on WindowsServer 2008R2 (Python IsAPIe handler) Please help me on this. I am stuck with this issue... -
Creating a Path Based on SlugFields in Django
I have a Django project based around creating tournaments and nesting specific objects within them. For instance, every tournament has multiple committees. When someone creates a tournament, I allow them to create a link with a SlugField. My code (so far) is as follows: models.py from django.db import models from django.utils.text import slugify class Tournament(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True) def _get_unique_slug(self): ''' In this method a unique slug is created ''' slug = slugify(self.name) unique_slug = slug num = 1 while Tournament.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, num) num += 1 return unique_slug def save(self, *args, **kwargs): if not self.slug: self.slug = self._get_unique_slug() super().save(*args, **kwargs) class Committee(models.Model): name = models.CharField(max_length=100) belongsTo = models.ForeignKey(Tournament, blank=True, null=True) slug = models.SlugField(max_length=50, unique=True) def _get_unique_slug(self): ''' In this method a unique slug is created ''' slug = slugify(self.name) unique_slug = slug num = 1 while Committee.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, num) num += 1 return unique_slug def save(self, *args, **kwargs): if not self.slug: self.slug = self._get_unique_slug() super().save(*args, **kwargs) views.py from django.shortcuts import render, get_object_or_404 from .models import Tournament, Committee def tournament_detail_view(request, slug): tournament = get_object_or_404(Tournament, slug=slug) return render(request, 'tournament/detail.html', {'tournament': tournament}) def committee_detail_view(request, slug): committee = get_object_or_404(Committee, slug=slug) return render(request, 'committee/detail.html', {'committee': committee}) urls.py … -
How do i fix an error that occus when creating django model manager
I am creating a blog app from the book django 2 by example by antonio mele. I am on the sub topic creating model managers. However, as soon as i edit my models.py file, the power shell window that hosts the local server displays this error: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x03B61300> Traceback (most recent call last): File "C:\Users\public\django\my_env\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\public\django\my_env\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inne r_run autoreload.raise_last_exception() File "C:\Users\public\django\my_env\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Users\public\django\my_env\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\public\django\my_env\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\public\django\my_env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\public\django\my_env\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\public\django\my_env\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\public\django\my_env\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\public\django\mysite\blog\models.py", line 1, in <module> class PublishedManager(models.Manager): NameError: name 'models' is not defined This is the code on the models.py file class PublishedManager(models.Manager): def …