Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django issues creating a custom user model
I trying to switch to a custom User Authentication so I can make changes more easily to the user model when needed. I was looking at the documentation here https://docs.djangoproject.com/en/2.1/topics/auth/customizing/ but I am now having an issue with my forms. models.py from django.contrib.auth.models import AbstractBaseUser class DefaultUser(AbstractBaseUser): pass Forms.py Contains the following from .models import DefaultUser from django.core.validators import EmailValidator from django.utils.crypto import get_random_string from django.contrib.auth import password_validation from django import forms from django.utils.translation import gettext_lazy as _ from django.contrib.auth.forms import UsernameField class UserCreateForm(forms.ModelForm): """ A form that creates a user, with no privileges, from the given username and password. """ error_messages = { 'password_mismatch': _("The two password fields didn't match."), 'Invalid_Email_Address': _("Invalid Email Address"), } password1 = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput, help_text=password_validation.password_validators_help_text_html(), ) password2 = forms.CharField( label=_("Password confirmation"), widget=forms.PasswordInput, strip=False, help_text=_("Enter the same password as before, for verification."), ) class Meta: model = DefaultUser fields = [ "username", "first_name", "last_name", ] field_classes = {'username': UsernameField} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self._meta.model.USERNAME_FIELD in self.fields: self.fields[self._meta.model.USERNAME_FIELD].widget.attrs.update({'autofocus': True}) self.fields[self._meta.model.USERNAME_FIELD].label = 'Email' def clean_username(self): username = self.cleaned_data.get('username') validate_username_is_email = EmailValidator() print(username) print(validate_username_is_email(username)) if validate_username_is_email(username): raise forms.ValidationError( self.error_messages['Invalid_Email_Address'], code='Invalid_Email_Address', ) return username def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 … -
django-tenant-schemas relation "post_post" does not exist
I am working on an application (django 1.11) where clients can create an account (SaaS). I use: https://github.com/bernardopires/django-tenant-schemas I create a new client, schema and domain_url using the form, but I get an error: django.db.utils.ProgrammingError: relation "post_post" does not exist Yes I made: python manage.py makemigrations python manage.py migrate_schemas --shared Below are my settings: SHARED_APPS = ( 'tenant_schemas', # mandatory, should always be before any django app 'accounts', # you must list the app where your tenant model resides in 'django.contrib.contenttypes', 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) TENANT_APPS = ( 'django.contrib.contenttypes', 'accounts', 'base', 'post', 'topics', ) INSTALLED_APPS = [ 'tenant_schemas', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'base', 'post', 'topics', 'ckeditor', 'debug_toolbar', ] TENANT_MODEL = 'accounts.Customer' I am not sure that my settings in 'SHARED_APPS', 'TENANT_APPS' and 'INSTALLED_APPS' are OK. -
I cannot get ChoiceField dropdown to display in my form
I have been trying to get choicefield to work as part of a modelform however I have had no success. So I have attempted a very simple form to see if I could display a drop down of some sort however I still can't! I would be very grateful for anyone that could help me get even a simple choicefield form working so I can build from there. forms.py class NewArticleForm(forms.Form): c =[("1", "Option 1"), ("2", "Option 2")] choices = forms.ChoiceField(choices=c, label="Choices") views.py def post_new(request): form = NewArticleForm() return render(request, 'fitness/name.html', {'form': form}) name.html {% block content %} <form method="post"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Submit"> </form> {% endblock %} -
Canceling a process Django-ViewFlow
I'm creating an aplication for my company's workflow. Doing so I've arrived to the necesity of having some way to cancel process instances in case the user who created the flow AKA "Asignador" requieres it. I've tried using the "CancelProcessView" But it can only cancel the tasks that are unassigned. Since my flow uses the ".Assign()" method all tasks are assigned automatically and hence are uncancelable. Flows.py @frontend.register class Delivery_flow(Flow): process_class = DeliveryProcess iniciar = ( flow.Start( CreateProcessView, fields=["nombre_del_entregable", 'url_del_proyecto', 'Asignador', 'ejecutor', 'tipo_de_flujo','observaciones_asignador', "fecha_inicio", 'fecha_de_terminacion'], task_description='Asignacion de entregable' ).Next(this.split_editar_ejecutar) ) split_editar_ejecutar = ( flow.Split() .Next(this.editar_proceso) .Next(this.ejecutar) ) editar_proceso = ( flow.View( UpdateProcessView, fields=[ "nombre_del_entregable", "fecha_de_terminacion", "ejecutor", 'observaciones_asignador', 'url_del_proyecto', 'estado_del_proyecto'], task_description="Tarea para editar algun campo" ).Assign(lambda act: act.process.Asignador ).Next(this.split_terminar_editar) ) cancelar_proceso = ( flow.View(CancelProcessView, ).Assign(lambda act: act.process.Asignador) ) split_terminar_editar = ( flow.If(lambda act: act.process.estado_del_proyecto) .Then(this.editar_proceso) .Else(this.cancelar_proceso) ) ejecutar = ( flow.View( UpdateProcessView, fields=[ "oberservaciones_ejecutor", "fecha_de_ejecucion", "revisor", "finalizado"], task_description="Ejecucion" ).Assign(lambda act: act.process.ejecutor ).Next(this.revisor_check) ) revisor_check = ( flow.View( views.ReView, ).Assign(lambda act: act.process.revisor) #.Assign(lambda act: act.process.nuevo_revisor) .Next(this.add_review) ) add_review = ( flow.View( UpdateProcessView, fields=['estado_de_aprobacion', 'revisor'], task_description='Conclusion sobre el entregable' ).Next(this.split) ) split = ( #If(lambda activation: activation.process.aprobacion_final) flow.Switch() .Case(this.join, cond=lambda act: act.process.estado_de_aprobacion=='APROBACION_FINAL') .Case(this.revisor_check,cond=lambda act: act.process.estado_de_aprobacion=='APROBACION_NUEVO_REVISOR') .Case(this.ejecutar, cond=lambda act: act.process.estado_de_aprobacion=='DEVOLVER_EJECUTOR') ) join = ( … -
We are planning to do a poc wrt to Azure B2C and Django. Are there any getting started tips on this please
Are there any previous examples who achieved this already? If so is there any reference guide to follow to get started. -
Django Rest Framework- foreign key throwing error
I am using django rest framework wherein the model has composite primary key, one of the them being a foreign key. models/TestSuite.py class TestSuite(models.Model): team_name = models.ForeignKey('Team', on_delete=models.DO_NOTHING, db_column='team_name') suite_name = models.CharField(max_length=100) description = models.CharField(max_length=200, blank=True, null=True) schedule = models.CharField(max_length=100, blank=True, null=True) email_list_ok = models.CharField(max_length=200, blank=True, null=True) email_list_fail = models.CharField(max_length=200, blank=True, null=True) template_name = models.ForeignKey('EmailTemplates', on_delete=models.DO_NOTHING, db_column='template_name') class Meta: managed = False db_table = 'test_suite' unique_together = (('team_name', 'suite_name'),) models/Team.py class Team(models.Model): team_name = models.CharField(primary_key=True, max_length=30) description = models.CharField(max_length=100, blank=True, null=True) class Meta: managed = False db_table = 'team' TestSuiteSerializer.py class Meta: model = models.TestSuite fields = '__all__' here TestSuiteViewSet.py class TestSuiteViewSet(viewsets.ModelViewSet): queryset = models.TestSuite.objects.all() serializer_class = serializers.TestSuiteSerializer def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data, many=isinstance(request.data, list)) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) Now when I do a post request, it throws below errors When the post() has team_name already existing in team table { "team_name": [ "test suite with this team name already exists." ] } When the post() has team_name not existing in team table Exception Type: ValueError Exception Value: Cannot assign "'dummy'": "TestSuite.team_name" must be a "Team" instance. Can someone please help me here. I am assuming I am missing something. -
Django migrations gives error from an app that is used in another project
I'm getting some odd errors when I execute python manage migrate.py. It is a fresh new project and it complains about an app that is not even there. In fact, is an app from another project that is at the same path level of this new fresh project. This is not the first time I get this error related to an app I use in another project. Any idea why this happens? -
how to get a value of a field in django
I'm currently working on a django app like IMDB.com that have a Media ( contains tvshows and movies ) model and an Episode model with a one-to-many relationship between them to display these episodes at the TvShow page. I managed to be able to show the episodes of a tvshow inside the page with: def tvshow(request, tvshow_title): tvshow = get_object_or_404(Media, title=tvshow_title) episodes = Episode.objects.all().filter(is_published=True, tvshow=tvshow) context = { 'tvshow': tvshow, 'episodes': episodes } return render(request, 'media/tvshow.html', context) and this worked perfectly fine but I also needed to display episodes based on season and this got me kinda confused how do I know how many seasons does a tv show have when there's no field for it in the Media model, but the Episode model had a season_number field, so I tried to get to query the last episode of a tv show based on the season_number: latest_episode = Episode.objects.order_by('-season_number').filter(is_published=True, tvshow=tvshow)[:1] and I managed to indeed get the episode but I don't know now how to get what is the number of the season in it. I tried seasons = latest_episode.season_number and seasons = latest_episode['season_number'] and neither of them worked. please tell me if there's a better way to do it … -
Getting an error when trying to set input_formats for Django TimeField
I am using the following model to represent a Class: class Class(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE) day = models.CharField(max_length=10, choices=WEEK_DAYS) timing = models.TimeField(input_formats = ['%I:%M %p', ]) room = models.CharField(max_length=10) I want to set my TimeField's format to 12 hours with am and pm. Django's documentation mentions using an input_formats argument to accomplish this here. However, when I run makemigrations, I get the following error: Traceback (most recent call last): File ".\manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "D:\Applications\Python\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "D:\Applications\Python\lib\site-packages\django\core\management\__init__.py", line 347, in execute django.setup() File "D:\Applications\Python\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\Applications\Python\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "D:\Applications\Python\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "D:\Applications\Python\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "D:\plannerly\timetable\models.py", line 15, in <module> class Class(models.Model): File "D:\plannerly\timetable\models.py", line 18, in Class timing = models.TimeField(input_formats = ['%I:%M %p', ]) File "D:\Applications\Python\lib\site-packages\django\db\models\fields\__init__.py", line 2146, in __init__ super().__init__(verbose_name, name, **kwargs) TypeError: __init__() got an … -
creating tests for forms
I'm currently trying to create test for my form which for sure is valid because i were testing him manually in my app, but in my test show me that my form.is_valid == False. I don't know what I'm doing wrong in my test, is there way to check every field seperately to find what causes invalidation in my tested form? My code: forms.py from django.forms import ModelForm from django import forms from .models import Comment class CommentForm(ModelForm): class Meta: model = Comment fields = ['nick', 'rate', 'content'] widgets = {'nick': forms.HiddenInput()} test_forms.py from django.test import TestCase from django.contrib.auth.models import User from ..forms import CommentForm class CommentFormTest(TestCase): def test_form(self): user = User.objects.create(username='Testowy') form_data = { 'nick': user, 'rate': '1', 'content': 'test content', } form = CommentForm(data=form_data) self.assertEqual(form.is_valid(), True) -
Django Query - Filter - Aggregation - error if no value
I get the below errors in my browser: "Matching query does not exist" "bad operand type for unary -: 'NoneType'" I have the impression it is because I'm running Aggregations on Querysets.Though when the filter returns nothing. The aggregation doesn't return '0' but an error. Can this be? I believe it is this way because when I add a single figure (for instance 1) it works. How can I solve it? Below example from my code (aggregation). many thanks ! calcul1 = Flow.objects.filter(name__slug=nameslug).filter(type='Call').aggregate(sum=Sum('amount'))['sum'] calcul2 = Flow.objects.filter(type='Dist').aggregate(sum=Sum('amount'))['sum'] calcul3 = BaseNV.objects.filter(name__slug=nameslug).values('amount').latest('date')['amount'] -
Django ERR_BLOCKED_BY_XSS_AUDITOR
I have a FormView which allows our users to edit the content of an HTML page. class PrelanderUpdate(LoginRequiredMixin, SuccessMessageMixin, UpdateView): model = Prelander form_class = PrelanderForm template_name = 'generic/form.html' success_message = 'Prelander updated successfully.' def get_success_url(self): return reverse('mediabuying:prelander:list') This is my form: class PrelanderForm(forms.ModelForm): class Meta: model = Prelander fields = [ 'is_active', 'vertical', 'angle', 'description', 'static_prefix', 'content' ] help_texts = { 'description': '<i>Keep this short:</i> This will be shown in the dropdown', # noqa 'content': 'HTML code only.', 'static_prefix': 'folder name in s3', } vertical = forms.ChoiceField(choices=Choices.Verticals) def clean_content(self): data = self.cleaned_data['content'] if '<meta name="referrer" content="always">' not in data: raise forms.ValidationError( 'Missing <meta name="referrer" content="always">' ) return data When I edit the content of a prelander, if the prelander does not have <meta name="referrer" content="always"> and the validation error is thrown, I am seeing this error: Why is this happening? Why does this only happen when the exception is thrown? (The content of a prelander is an html page) -
Django ldap authentication, problem with multi-valued DN groups
I'm getting crazy cause of Django LDAP authentication. I'm able to connect to the LDAP server (MS Active Directory), search for the user but unable to verify against groups (using the config param AUTH_LDAP_REQUIRE_GROUP). Asking more detail about the AD structure, I found that the group use a multi-valued DN to store the users, named member Studying the documentation, I found many AUTH_LDAP_GROUP_TYPE that manage that attribute, like: MemberDNGroupType NestedMemberDNGroupType and their subclasses, but none of it can find the user in one of two groups A screenshot of the group member attribute: member list This is the Django configuration related to LDAP AUTH_LDAP_CONNECTION_OPTIONS ={ ldap.OPT_PROTOCOL_VERSION:ldap.VERSION3, ldap.OPT_REFERRALS:0 } AUTH_LDAP_GROUP_TYPE = NestedActiveDirectoryGroupType() # Baseline configuration. AUTH_LDAP_SERVER_URI = 'ldap://ldap.xxxx.com' AUTH_LDAP_BIND_DN = 'auth_user@xxxx.com' AUTH_LDAP_BIND_PASSWORD = 'qwerty' AUTH_LDAP_REQUIRE_GROUP = ( LDAPGroupQuery('cn=group_1,ou=group_container,dc=xxxx,dc=com') | LDAPGroupQuery('cn=group_2,ou=group_container,dc=xxxx,dc=com')) AUTH_LDAP_USER_SEARCH = LDAPSearch( 'ou=user_container,dc=xxxx,dc=com', ldap.SCOPE_SUBTREE, '(UserPrincipalName=%(user)s)', ) AUTH_LDAP_GROUP_SEARCH = LDAPSearch( 'ou=group_container,dc=xxxx,dc=com', ldap.SCOPE_SUBTREE, '(objectClass=nestedActiveDirectoryGroup)', ) AUTH_LDAP_ALWAYS_UPDATE_USER = True AUTH_LDAP_CACHE_TIMEOUT = 3600 AUTHENTICATION_BACKENDS = ( 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ) The DN,OU,DC are correct for both users and groups. Could be the problem related to the member attribute type? Any idea on how to resolve it? -
Dependency on app with no migrations: %s" % key[0]) in the Django
I need create custom user. I'm using a user model with AbstractUser: from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.html import escape, mark_safe class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) settings.py: INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'crispy_forms', 'backend.classroom', ] I believe that problem is in the following line: AUTH_USER_MODEL = 'classroom.User' error: File "/home/davi/.local/share/virtualenvs/django-vue-template-Wl6a6m2J/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 82, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/home/davi/.local/share/virtualenvs/django-vue-template-Wl6a6m2J/lib/python3.6/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/home/davi/.local/share/virtualenvs/django-vue-template-Wl6a6m2J/lib/python3.6/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/home/davi/.local/share/virtualenvs/django-vue-template-Wl6a6m2J/lib/python3.6/site-packages/django/db/migrations/loader.py", line 226, in build_graph self.add_external_dependencies(key, migration) File "/home/davi/.local/share/virtualenvs/django-vue-template-Wl6a6m2J/lib/python3.6/site-packages/django/db/migrations/loader.py", line 191, in add_external_dependencies parent = self.check_key(parent, key[0]) File "/home/davi/.local/share/virtualenvs/django-vue-template-Wl6a6m2J/lib/python3.6/site-packages/django/db/migrations/loader.py", line 173, in check_key raise ValueError("Dependency on app with no migrations: %s" % key[0]) ValueError: Dependency on app with no migrations: classroom obs: The app classrom app is in the backend folder. I tried the following code too: AUTH_USER_MODEL = 'backend.classroom.User' -
Django pass parameters
I'm trying to pass pk key urlpatterns = [ path('api/products', ProductAPI.as_view()), path('api-admin/products/', ProductAdminAPI.as_view()), url(r'^api-admin/products/(?P<pk>[0-9]\d+)', ProductAdminAPI.as_view()), ] with this URL localhost:8000/api-admin/products/3/ but I'm getting 404 -
average spending per day - django model
I have a model that looks something like that: class Payment(TimeStampModel): timestamp = models.DateTimeField(auto_now_add=True) amount = models.FloatField() creator = models.ForeignKey(to='Payer') What is the correct way to calculate average spending per day? I can aggregate by day, but then the days when a payer does not spend anything won't count, which is not correct -
Displaying model data that is constantly being updated
So I've got a model that is automatically updated with new data via a raspberry pi and I'm using the standard queryset to display the information in an HTML template. Currently, the data is being updated however I have to refresh the page to see the changes. Is there any way to update the data being displayed without refreshing the page? I have looked into AJAX request however struggling to understand how to implement them, I am new to web development and this my first time using Django so any help would be appreciated! -
How can I limit the user to create only up to 3 products? Thank you
This is create method in views.py enter image description here This is a model enter image description here This is create.html enter image description here -
How to link two datepickers on django boostrap datetimepicker plus?
I am creating two different date pickers, and I want them to be at least 90 days apart. So if the 'start_date' changes i would like the 'end_date' to update or clean itself so the user must input the correct date. How could I do it? class ProjectCreateForm(forms.ModelForm): class Meta: model = Project fields = ['title','start_date', 'end_date',] widgets = { 'start_date': DatePickerInput( options={ 'minDate': (datetime.datetime.today() + datetime.timedelta(days=1)).strftime('%Y-%m-%d'), 'format':'DD/MM/YYYY' } ), 'end_date': DatePickerInput( options={ 'minDate': (datetime.datetime.today() + datetime.timedelta(days=91)).strftime('%Y-%m-%d'), 'format':'DD/MM/YYYY' } ) } -
Use local settings with Pycharm and Django
I'm using Pycharm in order to develop my Django project and I have a question with settings. I have a base.py settings file which contains all settings (especially databases and emails settings) : ... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'app_db', 'USER': 'app_user', 'PASSWORD': get_secret("DB_PWD", SECRETS), 'HOST': 'localhost', 'TEST': { 'NAME': 'test_app_db', 'USER': 'app_user', } } } DEFAULT_FROM_EMAIL = 'noreply@test.fr' EMAIL_SENDER = DEFAULT_FROM_EMAIL EMAIL_HOST = 'smtp.test.fr' EMAIL_PORT = 25 EMAIL_USER = '' EMAIL_PASSWORD = '' ... This configuration works on my distant server, but when I develop in localhost, I would like to take into account this same parameters in local.py file : from .base import * ... DATABASES['default']['USER'] = 'app_user2' EMAIL_HOST = 'localhost' EMAIL_PORT = 1025 ... My wsgi.py file looks like this : import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "main.settings.base") application = get_wsgi_application() And with Pycharm, I configured : Issue: My database parameter in local.py has been taken into account, but not my email HOST and PORT parameters. How I can overwrite these parameters in local.py in order to not take base.py paramaters into account but parameters in local.py file ? -
I want to auto-input field "id" for (django) Many-to-Many tables
I experienced the "ValueError" while trying to add model instances with a many-to-many relationship. ValueError: "" needs to have a value for field "id" before this many-to-many relationship can be used. A lot of responses were given here, but none was helpful. And i used a manual solution to "manually" input the "id" values. >>> import django >>> django.setup() >>> from myapp1.models import Category, Idea >>> id2=Idea.objects.create( ... title_en='tre', ... subtitle_en='ca', ... description_en='mata', ... id=5, ... is_original=True, ... ) >>> id2.save() >>> cat22=Category(title_en='yo') >>> cat22.save() >>> id2.categories.add(cat22) >>> Idea.objects.all() <QuerySet [<Idea: tre>]> >>> exit() Notice that i manually added an "id". How do i command django to auto-add the "id" field? Note: I tried adding "autoField" but failed, thanks -
Django migration error: Field 'name' doesn't have a default value
I' ve a Django application which has been upgraded recently from 1.4.5 to 1.11.16. It was running on an older version of debian linux, which has been reinstalled and is now 9.6 . Originally the database was mysql (default debian installation), and now it' s mariadb (also default installation) . Since the projects are small, there were basically no db optimization, almost everything was running with the default settings. Before the reinstall and upgrade the db has been dumped and later loaded. Originally it was using myisam table types, but now the default is innodb. Whenever i' m trying to create a new table (django model) with the simpliest setup, e. g.: class Sth(models.Model): car = models.CharField(max_length=128) i face the following warning: /home/user/.virtualenvs/prj/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py:101: Warning: Field 'name' doesn't have a default value return self.cursor.execute(query, args) . What does it mean, and why is it appearing? If strict mode is set, it even turns to be an error. What would be the solution for this problem? Knowing the change of the debian system (mysql -> mariadb) and django upgrade (1.4.5 -> 1.11.16) what should i think of? I also tried changing the current tables to innodb, and also change the default mariadb … -
type object 'Book' has no attribute 'order_by'
I have a model for book: class Book(models.Model): publish_house = models.ForeignKey(PublishHouse, on_delete=models.DO_NOTHING) author = models.ForeignKey(Author, on_delete=models.DO_NOTHING) title = models.CharField(max_length=50) price = models.DecimalField(max_digits=5, decimal_places=2) objects = models.Manager() img = models.ImageField(upload_to='books/', default='books/no.png') img_inside = models.ImageField(upload_to='books/', default='books/no_inside.png') is_available = models.BooleanField(default=True) book_date = models.DateTimeField(default=datetime.now, blank=True) is_best_selling = models.BooleanField() def __str__(self): return self.title class Meta: db_table = 'Book' I want to display books in templates by date (showing books that added recently), and this is the view: def index(request): new_books = Book.order_by('-book_date')[:4] bestselling_books = Book.objects.filter('is_best_selling')[:4] book_context = { 'new_books': new_books, 'bestselling_books': bestselling_books, } advertises = Advertise.objects.all() adv_context = { 'advertises': advertises } return render(request, 'pages/index.html', adv_context, book_context) i want to display books in order by the date they were added it keeps giving that error: type object 'Book' has no attribute 'order_by' i'm new to Django and can't understand what's went wrong as i'm following some tutorials and didn't missed any step -
DRF YASG Customizing
I'm trying to customize my api documentation buuild with yasg. First off, I would like to determine the naming of my own sections, and what endpoints should be included in this section. It seems that the naming of sections is based on the first prefix not belonging to the longest common prefix e.g.: if we have the urls api/v1/message and api/v1/test than the sections will be named message and test. Is there a way for me to determine A custom naming for this section? Furthermore, the introduction of every section is empty, how do I add text here? And last but not least, Stripe has these amazing section dividers how can I add these in drf yasg. -
Creating a virtualenv with already created django app
I am trying to deploy my django app in to production on a centos server. I have an app running on my computer(not server) with a code repository that doesn't utilize a virtual environment, and i wish i had set that up to begin with. I would like the production stage of the django app be run with a virtual environment, and was wondering what was the best way to go about this. I am very cloudy on how this would work out. Would i need to set up the django app on my computer with a virtual environment, and then move the code repository to the server and go about it that way? My understanding is the purpose of the virtual environment is to keep tabs and easily install any dependecies and software updates need to run the django app. So the question is: Should i not worry about setting up a virtual environment on my computer, but start one on my server and start from there? Or would i run into problems when i try to git clone my project to the server because there isnt a virtualenv setup from the repository. And if i should have it …