Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Two mutually exclusive many-to-many relations
Imagine an online shop. You have goods. Some goods have size, some don't. I've got an orders table id int not null, ... orders_products table order_id int not null, product_id int null, product_size_id int null, ... products table id int not null, ... product_sizes table id int not null, product_id int not null, ... Right now either product_id or product_size_id is not null. In other words, primary key is order_id + (product_id || product_size_id). Not both. In Django's terms that would be: class OrderProduct(models.Model): product = models.ForeignKey(Product, null=True, on_delete=models.CASCADE) product_size = models.ForeignKey(ProductSize, null=True, on_delete=models.CASCADE) order = models.ForeignKey('Order', on_delete=models.CASCADE) amount = models.PositiveSmallIntegerField() class Order(models.Model): products = models.ManyToManyField(Product, through=OrderProduct, related_name='orders') product_sizes = models.ManyToManyField(ProductSize, through=OrderProduct, related_name='orders') ... At least that's what I have right now. But I don't like having two mutually exclusive foreign keys in orders_products table. Or two attributes in Order model. One of which (product_sizes) is probably redundant. So, I probably have to remove product_sizes attribute from the Order model. Is that it? Or should I make product_id not null in orders_products table? And have product_size_id only when the product comes in different sizes? Any other suggestions? I've marked the question with django, python, postgresql tags. But I'm not stuck … -
Libraries available to create a plus button to add data to a view
For the following User model, each User has one primary coid, which identifies the facility they are assigned to. After pulling the User information detail in my profile view I want to have a plus button in my template that will allow me to add an additional coid or as many as the User would like to request because sometime a User is assigned to many coids, but they have one primary. My User model is defined as the following. class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) username = models.CharField(max_length=7, unique=True) formattedusername = models.CharField(max_length=11, unique=True, primary_key = True) first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=140) date_joined = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_cfo = models.BooleanField(default=False) facility = models.CharField(max_length=140) officename = models.CharField(max_length=100) jobdescription = models.CharField(max_length=140) positioncode = models.CharField(max_length = 100) positiondescription = models.CharField(max_length=140) coid = models.ForeignKey(QVDSSSecurityDimension, null=True, blank = True, db_constraint=False) streetaddress = models.CharField(max_length=140) title = models.CharField(max_length=100) USERNAME_FIELD = 'username' class Meta: app_label = 'accounts' db_table = "user" def save(self, *args, **kwargs): self.formattedusername = '{domain}\{username}'.format( domain='HCA', username=self.username) super(User, self).save(*args, **kwargs); def get_short_name(self): return self.username # REQUIRED_FIELDS = "username" def __str__(self): return '%s - %s %s' % (self.username, self.first_name, self.last_name) My profile view is very simple and I get the coid with … -
How to overcome NoReverseMatch for link inside if statement in the template?
I want to make some value if they exist to be links. In some case value will be None and in some case, it will have a record that user should be able to click at. So in my template, I put it inside the if statement {% if expense_row.noteunit.unit.id %} <a href="{% url 'unit_notes_details' pk=expense_row.noteunit.unit.id %}" class="btn btn-info">{{ expense_row.noteunit}}</a> {% else %} {{ expense_row.noteunit}} {% endif %} But despite the if statement I still get error NoReverseMatch at /expense/list/range/ Reverse for 'extra_notes_details' with arguments '()' and keyword arguments '{u'pk': ''}' not found. 1 pattern(s) tried: ['unit/extra_notes_details/(?P<pk>\\d+)$'] How can I make those occasional links without getting the error ? -
What if the hosting Django server don't have the module I imported?
I have imported "smtplib" in the code, and I doubt that the server won't have this installed. Is there a CDN for modules in python ? -
loading a project-wide CSS file inside an app-specific CSS file in Django
I'm working on a Django 1.10.5 project. I have a number of apps, each of which has an app-specific css file which must import a css file common to all the apps. But the import isn't working unless I put the common css file in each app's static folder (defeats the point). In the app template I have <link rel="stylesheet" rel="stylesheet" type="text/css" href="{% static 'app1/css/app1.css' %}"/> And my settings: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(os.path.dirname(BASE_DIR), "static-storage"), ] STATIC_ROOT = os.path.join(os.path.dirname(os.path.dirname(BASE_DIR)), "static-serve") The common css file is in static-storage/css. I have tried running collectstatic but it does nothing...right now DEBUG=True. Can anybody help? Thanks. -
Django pagination over the page limit showing still last results neverending
I have a Django function based API that inputs page number and on each page the size of the page. Here is my code. @api_view(['POST']) def attendance_all_get_list_by_page(request): # ----- YAML below for Swagger ----- """ description: attendance_all_get_list_by_page parameters: - name: page type: integer required: true location: form - name: page_limit type: integer required: true location: form """ attendance_list = Attendance.objects.all().order_by('id') page = request.GET.get('page', request.POST['page']) paginator = Paginator(attendance_list, request.POST['page_limit']) try: attendances = paginator.page(page) except PageNotAnInteger: attendances = paginator.page(request.POST['page']) except EmptyPage: attendances = paginator.page(paginator.num_pages) serializer = AttendanceSerializer(list(attendances), many=True) data = serializer.data[:] return Response(data, status=status.HTTP_200_OK) my serializer: class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ("id", "username") class AttendanceSerializer(serializers.ModelSerializer): employee = EmployeeSerializer(many=False, read_only=True) class Meta: model = Attendance fields = ('id','employee','created_at') Imagine I had attendance record of 16,17,18,19 So for example with page=2 page_limit=2, it will show the following (this should be the last page of 4 records) [ { "id": 18, "employee": { "id": 16, "username": "haha" }, "created_at": "2017-12-28T03:29:29.698339Z" }, { "id": 19, "employee": { "id": 16, "username": "haha" }, "created_at": "2017-12-28T03:38:53.639749Z" } ] if I did (page=3 page_limit=2) or (page=10 page_limit=2), it will still show [ { "id": 18, "employee": { "id": 16, "username": "haha" }, "created_at": "2017-12-28T03:29:29.698339Z" }, … -
Python module random has no attribute choices working on local server but not on live server
I have a script which selects a random number form available list at random. I have been testing it on django's local server and it worked fine but when I moved it to a live server I keep getting this error: AttributeError: 'module' object has no attribute 'choices' Here's my code: import json class singlePull(TemplateView): template_name = 'gacha/singlepull.html' def randomStar(self): choice = [5,4,3] probability = [0.1, 0.2, 0.7] star = random.choices(choice, probability) return star def post(self, request): result = self.randomStar() for key in result: character = Characters.objects.filter(stars=key).order_by('?')[:1] for obj in character: name = obj.name stars = obj.stars series = obj.series image = obj.image return JsonResponse({'name': name, 'stars': stars, 'series': series, 'image': image}, safe=False) How come I keep getting this error? What could be wrong here? -
SERVER error 500 on heroku deployment
Server 500 Error: heroku logs After running heroku open and heroku logs , i am getting the server 500 error. I have ran migrations and checked logs multiple times. Nothing really seems like an error... I have added the settings file, requirement.txt file and Procfile below. PS : i added heroku logs --app app_name, it said permission denied. settings import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY','2z9y6') DEBUG = bool( os.environ.get('DJANGO_DEBUG', False) ) ALLOWED_HOSTS = ['127.0.0.1', 'hackingonlineeducation.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #third party apps 'star_ratings', 'crispy_forms', #my_apps 'newsletter', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Books.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'Books.wsgi.application' # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.11/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ … -
$.get() gives error, on callback (?)
I know there are many questions like this, but I can't find the solution for my problem. MyScript.js: $('#id_tags').keyup(function(){ var query; query = $(this).val(); $.get('/blog/suggest-category/', {suggestion: query}, function(data){ console.log('data') $('#id_tags').html(data); }); }); My view.py: def get_category_list(max_results=0, starts_with=''): print('get_category_list') cat_list = [] if starts_with: cat_list = Tag.objects.filter(slug__istartswith=starts_with) if max_results > 0: if len(cat_list) > max_results: cat_list = cat_list[:max_results] return cat_list def suggest_category(request): print('suggest_category') cat_list = [] starts_with = '' if request.method == 'GET': starts_with = request.GET['suggestion'] cat_list = get_category_list(5, starts_with) print('cat_list', cat_list) #return render(request, 'blog/suggest_tag.html', {'suggestions': cat_list }) return cat_list query, in MyScript.js is a string. The view is called (I can read the print('cat_list', cat_list)) but then it throw an error: when the list is empty =>AttributeError: 'list' object has no attribute 'get' when isn't (for example: cat_list [<Tag: General>]) => ValueError: too many values to unpack (expected 2) -
Django annotation in a loop
I'm trying to create an unknown amount of columns with annotate: def add_daily_usage_record(query, days): for i in days: query.annotate('day_' + i + '_usage'= "doesn't matter" But it doesn't seem to work. Is there any way to give an annotation a name without writing it? or maybe if I have the name of the new column in a variable, is it possible to pass it to annotate? Thank you. -
Django abstract user model not migrating
So I am working on implementing a custom user model, and to do so i followed tutorial 'this tutorial. I am now trying to run python3 manage.py migrate and I get this error: [wtreston] ~/gdrive/mysite2/ $ python3 manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, reviews, sessions, users Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 164, in handle pre_migrate_apps = pre_migrate_state.apps File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/migrations/state.py", line 218, in apps return StateApps(self.real_apps, self.models) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/migrations/state.py", line 295, in __init__ raise ValueError("\n".join(error.msg for error in errors)) ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'users.user', but app 'users' doesn't provide model 'user'. The field reviews.Answer.student was declared with a lazy reference to 'users.user', but app 'users' doesn't provide model 'user'. The field reviews.ReviewBlock.teacher was declared with a lazy reference to 'users.user', but app 'users' doesn't provide model 'user'. The field users.Student.user was declared with a lazy reference … -
Django - User registration and login via REST API in the same project
I mainly have two questions. I haven't read this anywhere but, I am wondering whether or not it is a good idea to make it so that all the data that is going in and out of all apps in your project solely depended on REST API calls. So that if you, for instance, want to register a new user. Gather the data from a front-end, with no back-end work, and just send this data as a REST call to you "registration-app" where all validation and back-end work is done. I find this method effective when working in big teams as it makes dependencies even more decoupled, as well as making each part of the project more separated and "clear". My question is, therefore, is this a viable way of developing? Are there any security or performance issues with this? And where can I read more? Thanks Max -
Dynamically accessing a "Friend" model with two foreign-keys to "Profile"
I've created a Friend model that consists of two Profile model instances. The reason for a separate model in the first place is due to the Friend model having special attributes related to the "friend" relationship. In this Friend model, I am also tracking the requester & accepter of the relationship as it is significant to my site--this requires that I have a separate field for each of these, and they are FKs to the Profile model. Here are the two models: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) profile_picture = models.ImageField( upload_to=profile_photo_upload_loc, blank=True, null=True, created = models.DateTimeField(auto_now_add=True) class Friend(models.Model): requester = models.ForeignKey(Profile, related_name='is_requester') accepter = models.ForeignKey(Profile, related_name='is_accepter') requester_asks = models.CharField(max_length=60, null=True) accepter_asks = models.CharField(max_length=60, null=True) With this structure, in instances that I want to retrieve all of the Friend instances that a single Profile is a participant in, I need to make two queries: one for those in which he's the requester and another for those in which the profile is an accepter. The combination of these two querysets gives me the total list of all Friend relationships a Profile belongs to--I need this total list when making things like a message inbox. Attempting to create a message … -
How to achieve asynchronous execution of tasks united in celery group?
The first part The task was to inform the user about the performance of certain functions @task(base=NotifierTask) first(*args): # runs some time return json_resp @task(base=NotifierTask) second(*args): # runs some time return json_resp @task(base=NotifierTask) third(*args): # runs some time return json_resp # Get request # the number of execute functions can vary depending on the request # can run from 1 to 40 functions def main(request): # there we get some data data = request.POST.get('data') for some_func in data: if some_func == 'first': first.delay(args) elif some_func == 'second': second.delay(args) elif some_func == 'third': third.delay(args) # The whole thing gets into a celery worker # Notifier Task class NotifierTask(Task): """ Tasks that sends notification on completion. """ abstract = True def after_return(self, status, retval, task_id, args, kwargs, einfo): # The result of the execution and negotiates through a socket on the client side The second part For these purposes, try to combine all the tasks in the group to obtain the result of the completion of all tasks in the group. @task(base=NotifierTask) def celery_test(id, position): time.sleep(id) return "Time delay: %s, Position: %s" % (str(id), str(position)) def some_request(request): from django.http import JsonResponse if request.method == 'GET': job = group([ celery_test.s(10, 1), celery_test.s(2, 2), … -
Django rest framework conditionally required fields
I would like to write a drf validator that will mark a field as required based on the value of an other field. For example: class MySerializer(serializers.Serializer): has_children = fields.BooleanField() nb_childs = fields.IntegerField(min_value=1, validators=[RequiredIf(field='has_children', value=True)], required=False) At first i believed the class based validator was the way to do it, by retrieving the value of 'has_children' with a method like this: def set_context(self, serializer_field): print serializer_field.parent.initial_data but the 'initial_data' is not set. Any clue? -
Django URLs from different apps in just the base one
So I have 2 apps for my django project. In the default mysite folder, you have the urls.py file. I cant seem to find out how to write all my urls for all the apps in just the one urls.py file. I have tried this: from reviews.models import * however that isnt working. Thanks for any help! -
HTML5 video tag does not work on Safari
I'm a coding beginner and currently working on a fitness app. I'm facing the problem that my HTML5 sample video doesn't load in Safari 11, but works perfectly fine with Chrome and Firefox. Here is the html: <video id="VideoElement" width="200" height="160" muted controls src="/static/media/fitness/theraband1.mp4" type="video/mp4"></video> Yet, I don't think that the html is the problem, as I cannot even access the video on Safari with a direct link to the file. In case you want to try by yourself, here is the link: Placeholder video The app is programmed in Python 3 and Django 2. The video can neither be loaded by using the pythonanywhere page nor by my local Django development server. I already searched stackoverflow, but cannot not find a solution. However, I read in some posts that the problem could be related to http headers. -
Product will not appear for others user when current user add product in Cart
In Django, I want if a user adds a product to a cart or buy a product. The product will not show on other users product list or anywhere. Just show for current user who adds the product to a card or buys it. How I implement it? Thanks. product model class ProductManager(models.Manager): def get_queryset(self): return ProductQuerySet(self.model, using=self._db) def all(self): return self.get_queryset().active() def get_by_id(self, id): qs = self.get_queryset().filter(id=id) # Product.objects == self.get_queryset() if qs.count() == 1: return qs.first() return None def search(self, query): return self.get_queryset().active().search(query) class Product(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(blank=True, unique=True) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=20, default=39.99) image = models.ImageField(upload_to=upload_image_path, null=True, blank=True) gallery_image = models.ImageField(upload_to=upload_image_path_gallery, null=True, blank=True) genre = models.ForeingKey(Genre) active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True) is_digital = models.BooleanField(default=True) # User Library objects = ProductManager() def get_absolute_url(self): return reverse("products:detail", kwargs={"slug": self.slug}) def __str__(self): return self.title @property def name(self): return self.title def get_downloads(self): qs = self.productfile_set.all() return qs def product_pre_save_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = unique_slug_generator(instance) pre_save.connect(product_pre_save_receiver, sender=Product) cart model from decimal import Decimal from django.conf import settings from django.db import models from django.db.models.signals import pre_save, post_save, m2m_changed from project.products.models import Product User = settings.AUTH_USER_MODEL class CartManager(models.Manager): def new_or_get(self, request, *args, **kwargs): cart_id … -
Django Project: Link in base.html resulting in an error
I have a link to "Add Album" specified in the base.html in my Django project. The code is below <ul class="nav navbar-nav navbar-right"> <li class=""> <a href="{% url 'music:album-add' %}"> <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>&nbsp; Add Album </a> </li> When the "Add Album" link is clicked however, it results in an error: ValueError at /music/album-add/ invalid literal for int() with base 10: 'album-add' Request Method: GET Request URL: http://127.0.0.1:8000/music/album-add/ Django Version: 2.0 Exception Type: ValueError Exception Value: invalid literal for int() with base 10: 'album-add' Exception Location: C:\Python34\lib\site-packages\django\db\models\fields\__init__.py in get_prep_value, line 947 The music/views.py file code is below from django.views import generic from django.views.generic.edit import CreateView, UpdateView, DeleteView from .models import Album #=============HOME PAGE=================== class IndexView(generic.ListView): #specify template being used template_name='music/index.html' #when we get a list of all albums, plug them into this template context_object_name='all_albums' #if you don't use this variable it is automatically just object_list (which is used in index.html) #make a query set def get_queryset(self): return Album.objects.all() #=============DETAILS VIEW=============== details about one object class DetailView(generic.DetailView): #what model are we looking at /for model=Album template_name='music/detail.html' #===============For the add album form class AlbumCreate(CreateView): model=Album fields=['artist','album_title','genre','album_logo'] template_name='music/album_form.html' The urls.py code: from django.contrib import admin from django.urls import include, path from . import … -
method object is not JSON serializable
I am using ajax to refresh the cart items when cart item is removed. It works well, if i don't response object with image otherwise I get an error method object is not JSON serializable. If i use model_to_dict for the image part, i get an error 'function' object has no attribute '_meta'. here is the code def cart_detail_api_view(request): cart_obj, new_obj = Cart.objects.new_or_get(request) products = [{ "id": x.id, "url": x.get_absolute_url(), "name": x.name, "price": x.price, "image": x.first_image } for x in cart_obj.furnitures.all()] cart_data = {"products": products, "subtotal": cart_obj.sub_total, "total": cart_obj.total} return JsonResponse(cart_data) class Furniture(models.Model): name = models.CharField(max_length=100, blank=True, null=True) manufacturer = models.ForeignKey(Manufacturer, blank=True, null=True) slug = models.SlugField(max_length=200, unique=True) def __str__(self): return self.name def first_image(self): """ Return first image of the furniture otherwise default image """ if self.furniture_pics: return self.furniture_pics.first() return '/static/img/4niture.jpg' class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True) furnitures = models.ManyToManyField(Furniture, blank=True) I get 'function' object has no attribute '_meta' error while wrapping x.first_image to model_to_dict How do i resolve such issue? -
making gcp bucket default storage in django
I am not using Appengine. I have deployed my django server in my GCP instance and using django root location for the storage but I want to access the GCP bucket and make it as default storage location for uploading and sending the path to the function used in the views.py Here's a link Configure Django and Google Cloud Storage? From the above url I think the issue can be solved but i am unable to understand where to deploy the code whether in the settings.py or views.py file Is it possible that someone can help me with the steps in it. -
to_python() and from_db_value() methods overlapping in function?
I've been looking at this code example from the docs: import re from django.core.exceptions import ValidationError from django.db import models from django.utils.translation import gettext_lazy as _ def parse_hand(hand_string): """Takes a string of cards and splits into a full hand.""" p1 = re.compile('.{26}') p2 = re.compile('..') args = [p2.findall(x) for x in p1.findall(hand_string)] if len(args) != 4: raise ValidationError(_("Invalid input for a Hand instance")) return Hand(*args) class HandField(models.Field): # ... def from_db_value(self, value, expression, connection): if value is None: return value return parse_hand(value) def to_python(self, value): if isinstance(value, Hand): return value if value is None: return value return parse_hand(value) As far as I understand, from_db_value() is responsible for turning a string that's coming from the database to the right python type (please correct me if I'm wrong). to_python() is also responsible for turning a string value into a python type. If we look at the example, the two functions do similar stuff. No, not the exact same stuff, but very similar. My questions: What is the reason for having two very similar methods on the field? Why does to_python() have to be able to handle value = Hand()? I thought it was made for turning strings into Hand objects. Why does … -
popup UserCreationForm in django
Basically im very new to django only 5 days old. i need to know can i popup UserCreationForm of django? i'm building a website what i need to do is when i click on signup page popup signup page needs to show. right now i have a signup page and login page and they are working but i need to popup them and i'm using usercreationform of django and second thing can i add bootstrap and css in that form too? kindly please help me from django.contrib.auth.forms import UserCreationForm -
Django swagger- How to disable DjangoFilterBackend filters from delete, put methods?
I've created below AssetsFilter: from django_filters import Filter from django_filters import rest_framework as filters from django_filters.fields import Lookup from .models import Asset class ListFilter(Filter): def filter(self, qs, value): value_list = value.split(',') return super(ListFilter, self).filter(qs, Lookup(value_list, 'in')) class AssetsFilter(filters.FilterSet): name = filters.CharFilter(lookup_expr='icontains', help_text=u'Filter by Asset name') assets_criticality = ListFilter(name='assets_criticality', help_text=u'Filter by criticality id') class Meta: model = Asset fields = ['name', 'assets_criticality'] Now I'm using this filter in my viewset see in below: from .serializers import AssetSerializers from .filters import AssetsFilter class AssetViewSet(viewsets.ModelViewSet): """ This viewset automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. """ queryset = Asset.objects.all() serializer_class = AssetSerializers filter_backends = (DjangoFilterBackend,) filter_class = AssetsFilter http_method_names = ['get', 'post', 'put', 'delete'] def list(self, request): """ Returns a list of Asset. """ return super(AssetViewSet, self).list(request) def create(self, request): """ Creates a new Asset.<br> """ return super(AssetViewSet, self).create(request) def destroy(self, request, pk=None): """ Deletes a Asset. """ return super(AssetViewSet, self).destroy(request, pk=pk) def retrieve(self, request, pk=None): """ Returns a Asset with id={id} """ return super(AssetViewSet, self).retrieve(request, pk=pk) def update(self, request, pk=None, *args, **kwargs): """ Updates an existing Asset.<br> """ return super(AssetViewSet, self).update(request, pk=pk, *args, **kwargs) def partial_update(self, request, pk=None, *args, **kwargs): """ Partially updates an existing Asset.<br> """ return super(AssetViewSet, self).partial_update(request, … -
Reverse for 'create_song' not found. 'create_song' is not a valid view function or pattern name
I have a Django project in which the page that should load to show the album that has just been added, does not. It should go to the primary key for that album (auto generated) with the reference: http://127.0.0.1:8000/music/1/ but instead gives the error: Reverse for 'create_song' not found. 'create_song' is not a valid view function or pattern name. A variant of the same problem, I assume, Is that when I click on the VIEW DETAILS BUTTON (shown below in the index.html) it doesn't load: <div class="caption"> <h2>{{ album.album_title }}</h2> <h4>{{ album.artist }}</h4> <!-- View Details --> <a href="{% url 'music:detail' album.id %}" class="btn btn-primary btn-sm" role="button">View Details</a> <!-- Delete Album --> <form action="#" method="post" style="display: inline;"> {% csrf_token %} <input type="hidden" name="album_id" value="{{ album.id }}" /> <button type="submit" class="btn btn-default btn-sm"> <span class="glyphicon glyphicon-trash"></span> </button> </form> The code for the various sections is below: music/templates/music/album_form.html <div class="row"> <div class="col-sm-12 col-md-7"> <div class="panel panel-default"> <div class="panel-body"> <form class="form-horizontal" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {% include 'music/form_template.html' %} <!-- how form fields and inputs are laid out--> <div class="form-group> <div class="col-sum-offset-2 col-sm-10"> <button type="submit" class="btn btn-success">Submit</button> </div> </div> </form> </div> </div> </div> </div> </div> {% endblock %} music/views.py from django.views …