Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issue for user from an existing database to login in a Django website
There is my problem, so I need to create a Django app and I think I have to use an already existing database with users in. So I did some research and figured out some issues. So Django store the password with the salt and use it to check the password.But no one says that there will be salt + hashed type password in the database, but we can get read of this issue with the proper check function (related to the encryption function) I think, like this guy Django check_password() always returning False who used bcrypt.checkpw(password, hashedPassword) because in his database passwords are encrypted with bcrypt. The solution proposed was to create a custom authentification backend (even if I don't really see how we can do this I may be able to find out a tuto to do so) but the main issue is that how I can save a user password who register through the Django web site with the same type of hash that the one already existing in the database (with no salt). I'm a really sorry for not be able to give you more precision about how the password are stored in the database because … -
Django structure
I really need a way to print the structure of my Django app So I have an almost finished app and I need to print something like this: ~/projects/project_name/ docs/ # documentation scripts/ manage.py # installed to PATH via setup.py project_name/ # project dir (the one which django-admin.py creates) apps/ # project-specific applications accounts/ # most frequent app, with custom user model __init__.py ... settings/ # settings for different environments, see below __init__.py production.py development.py ... __init__.py # contains project version urls.py wsgi.py static/ # site-specific static files templates/ # site-specific templates tests/ # site-specific tests (mostly in-browser ones) tmp/ # excluded from git setup.py requirements.txt requirements_dev.txt pytest.ini Is this possible? I only can find a way to create an app based in other structure. I need the same but in the other way... Getting the structure of my app... Thanks!!!! -
Got an unexpected keyword argument 'my_id' (Dynamic URL Routing)
django 3.2.2 urls.py from django.contrib import admin from django.urls import path from pages.views import home_view, contact_view, about_view from products.views import product_detail_view, product_create_view, render_initial_data, dynamic_lookup_view urlpatterns = [ path('products/<int:my_id>/', dynamic_lookup_view, name='product'), path('', home_view, name='home'), path('about/', about_view), path('contact/', contact_view), path('create/', product_create_view), path('initial/', render_initial_data), path('product/', product_detail_view), path('admin/', admin.site.urls), ] views.py from django.shortcuts import render, get_object_or_404 from .forms import ProductForm, RawProducForm from .models import Product # Create your views here. def dynamic_lookup_view(request, my_id): obj = Product.objects.get(id=my_id) context = { "object": obj } return render(request, "products/product_detail.html", context) I want to see the products with the following link: http://127.0.0.1:8000/products/2/ this returns me: TypeError at / products / 2 / dynamic_lookup_view () got an unexpected keyword argument 'my_id' -
Django model class with multiple objects from other model class
I want to create a Django model schema to track yacht racing results. This is a highly simplified version, but want to only focus on the relationships and schema first; class Yacht(models.Model): name = models.CharField(max_length=50) class Event(models.Model): event_number = models.IntegerField() class Result(models.Model): yacht = models.ForeignKey(Yacht, on_delete = models.CASCADE) event_number = models.ForeignKey(Event, on_delete = models.CASCADE) result = models.IntegerField(default=0) Question: How would you approach this problem where I want to create an Event, and have it list all the yachts where I can enter their time? I'd like to be able to do this in the Admin 'all at once' instead of going to each yacht. Eventually, I want this to display as a form for a user. For example, if a user clicks on a race event, it loads a page with all the yachts and their time slot. Julien -
Inserting data from an array into a WORD document table
I have two arrays ['2021-04-30', '2021-05-02', '2021-05-04', '2021-05-06'] [1500, 450, 750, 900] There is a document template How do I insert data from the date array into {{ date }} and data from the price array into the {{ price }} variable?In this case, each new record in the table must start with a new cell doc = Document('Шаблон.docx') date = post_data.get('date', False) price = post_data.get('price', False) context = {'date': date, 'price': price} doc.render(context) doc.save('restyled.docx') This works when the data is not an array -
Django not detecting changes in app model
I have created an app called base and added a new model to it. However, whenever I run python3 manage.py makemigrations base It says no changes detected. I have already added my in installed apps INSTALLED_APPS = [ ... 'base.apps.BaseConfig', ... ] And it does have the migrations folder inside the app containing and __init__.py file. I was wondering what is causing this issue. This is my model: from django.db import models # Create your models here. class BaseModel(models.Model): created_at = models.DateTimeField(auto_now=True) modified_at = models.DateTimeField(auto_now_add=True) class Meta: abstract = True And my settings contains 4 files: settings: --__init__.py -- dev.py -- prod.py -- staging.py -- common.py My __init__.py: import os from .common import * from decouple import config environment = config('DEV_ENV', cast=str) if environment == "dev": from .dev import * elif environment == "staging": from .staging import * elif environment == "prod": from .prod import * I have also already tried running python3 manage.py makemigration base --settings=project.settings.dev and it still says no changes detected -
Issues, the courses appear to everyone and not to the users who purchased the course
Issues, the courses appear to everyone and not to the users who purchased the course , the problem is any one can access to the course if he type the url for course views.py : def coursePage(request,slug): course = Course.objects.get(slug = slug) serial_number = request.GET.get('lecture') videos = course.video_set.all().order_by('serial_number') if serial_number is None: serial_number = 1 video = Video.objects.get(serial_number = serial_number , course = course) # print("priview", video.is_preview) # print(request.user.is_authenticated) # print(request.user) if (video.is_preview is False): if (request.user.is_authenticated is False): return redirect('login') else: user = request.user try: user_course = UserCourse.objects.get(user = user , course = course) except: return redirect('checkout',slug = course.slug) data = { "course":course, "video":video, "videos":videos } return render(request,'courses\courses.html',data) how to fix this problem , i want user who purchased the course can see it not all also i want to ask how to store videos private in db and no body can access videos if he not purchased i mean like udemy -
Formset saving any decimal except 0 even though formset is saved and is_valid() passes
I have created a formset to let users log hours on a weekly basis. The issue I'm having is that I can't save "0" in the input fields - any decimal works but 0 (see gif at the end for illustration) TLDR: Formset saves any input except 0, see gif here for illustration: https://imgur.com/a/iCMexQk My Timesheet and TimesheetEntry models looks as following: class Timesheet(Model): year = PositiveIntegerField(validators=[MaxValueValidator(2500), MinValueValidator(1900)]) week = PositiveIntegerField() project = ForeignKey("projects.Project", on_delete=CASCADE) user = ForeignKey(User, on_delete=CASCADE) status = CharField( max_length=15, choices=STATUS_CHOICES, blank=True, default=STATUS_OPEN ) objects = TimesheetManager() class Meta: db_table = 'timesheet' ordering = ('id',) unique_together = (('year', 'week', 'user', 'project',),) def __getattr__(self, attr): allowed_days = ( 'day_1', 'day_2', 'day_3', 'day_4', 'day_5', 'day_6', 'day_7' ) if attr in allowed_days: day = int(attr[-1]) - 1 entry = self.timesheetentry_set.filter( date=Week(self.year, self.week).day(day) ).first() if entry: return entry.hours return None return super().__getattr__(attr) def total_duration(self): return self.timesheetentry_set.aggregate( total_duration=Coalesce(Sum('hours'), 0) ).get('total_duration') class TimesheetEntry(Model): timesheet = ForeignKey(Timesheet, on_delete=CASCADE) hours = DecimalField(max_digits=4, decimal_places=1, null=True, blank=True) date = DateField() class Meta: db_table = 'timesheet_entry' ordering = ('date',) And the forms.py looks as following: DAYS = ( 'day_1', 'day_2', 'day_3', 'day_4', 'day_5', 'day_6', 'day_7' ) class TimesheetModelForm(ModelForm): class Meta: model = Timesheet exclude = ("user", "status") class … -
How can i override, Django Rest Auth Registration?
I'm working on a small project using Django / Rest Auth, and I would like to know how can I override the registration, I would like to add some other fields in the registration, as I want to do some other things during the registration. PS: I checked already some questions here but I couldn't use them because each one explains a different approach that's why -
Django rest framework - serializer is not valid
Good day. I'm trying to create an entity by POST method. I have Serializer, and some javascript code - that sends me FormData , which I'm trying to serialize. This is my view: @api_view(['POST']) @parser_classes([MultiPartParser, FormParser]) def cocktail_create(request): """Создание коктейля""" pprint(request.data) serializer = CocktailCreateSerializer(data=request.data) pprint(serializer.fields) if serializer.is_valid(): serializer.create(serializer.validated_data) else: pprint(serializer.errors) request.data: {'author': '4', 'cocktail_tool': '[{"tool":"1","amount":"1"}, {"tool":"2","amount":"1"}]', 'csrfmiddlewaretoken': 'KFb9ZEBwWViF4Sm9pQxZn5KcfXpfu7t6OigeqsXZri9hoQQ1RPuS1lQDF3NJ3Aq5', 'description': 'asdasd', 'img': <InMemoryUploadedFile: pp,504x498-pad,600x600,f8f8f8.jpg (image/jpeg)>, 'name': 'Danya', 'recipe': '[{"ingredient":"1","amount":"1"},{"ingredient":"2","amount":"1"}]', 'recipe_text': '{"1":"asdasd","2":"asdasd"}', 'small_img': <InMemoryUploadedFile: pp,504x498-pad,600x600,f8f8f8.jpg (image/jpeg)>} serializer.fields : {'img': ImageField(allow_null=True, max_length=100, required=False), 'small_img': ImageField(allow_null=True, max_length=100, required=False), 'cocktail_tool': CocktailToolsForCocktailCreateSerializer(many=True): amount = IntegerField(max_value=2147483647, min_value=-2147483648) tool = PrimaryKeyRelatedField(queryset=BarTool.objects.all()), 'description': CharField(style={'base_template': 'textarea.html'}), 'name': CharField(max_length=255, validators=[<UniqueValidator(queryset=Cocktail.objects.all())>]), 'recipe': RecipeForCocktailCreateSerializer(many=True): amount = IntegerField(max_value=2147483647, min_value=-2147483648) ingredient = PrimaryKeyRelatedField(queryset=Ingredient.objects.all()), 'recipe_text': JSONField(decoder=None, encoder=None, style={'base_template': 'textarea.html'}), 'author': PrimaryKeyRelatedField(allow_null=True, queryset=BarbookUser.objects.all(), required=False)} serializer.errors: {'cocktail_tool': [ErrorDetail(string='This field is required.', code='required')], 'recipe': [ErrorDetail(string='This field is required.', code='required')]} my serializers : class CocktailToolsForCocktailCreateSerializer(serializers.ModelSerializer): class Meta: model = CocktailTool fields = ("amount", "tool") class RecipeForCocktailCreateSerializer(serializers.ModelSerializer): class Meta: model = CocktailRecipe fields = ("amount", "ingredient") class CocktailCreateSerializer(serializers.ModelSerializer): cocktail_tool = CocktailToolsForCocktailCreateSerializer(many=True) recipe = RecipeForCocktailCreateSerializer(many=True) class Meta: model = Cocktail fields = ("img", "small_img", "cocktail_tool", "description", "name", "recipe", "recipe_text", "author") my models: I have a cocktail model , ingredient model and bartool model, and many to many tables such as: class CocktailRecipe(models.Model): … -
refreshing audios makes them impossible to listen to
I want to make a whatsapp like message app but only with audios. I can get them in my vue app the by refreshing regularly the store, to see if new audios arrived: refresh() { this.$store.dispatch("audio/getAudios"); }, }, created() { setInterval(this.refresh, 1000); }, and I display them the following way in my vue app: <div class="audios" v-for="audio in audios" :key="audio"> <audio controls v-if="audio.rooms.split(',').includes(room)"> <source :src= "'http://localhost:8000'+audio.audiofile" type="audio/wav"> </audio> </div> </div> The problem is that by refreshing every second, all audios that are displayed are 're'-displayed and it makes impossible to listen to them. How can I use the v-for differently to avoid this trouble ? -
django not saving data to model
I am working on the cs50w commerce project. The page I am making should create an auction listing for an item the user wants to sell. After entering the info into the form and clicking the button the data is not saved to the model. going to the admin page shows that my listings model has 0 listings. I can not find the issue. I have been working on this portion of the code for 2 days. any help would be appreciated. HTML {% extends "auctions/layout.html" %} {% block body %} <h2>Create Listing</h2> <div class="text-left"> <form action="{% url 'createlisting' %}" method="POST"> {% csrf_token %} <div class="form-group"> <input class="form-control" autofocus type="text" name="title" placeholder="Title"> </div> <div class="form-group"> <textarea class="form-control" name="description" rows="4" placeholder="Add a Description"></textarea> </div> <div class="form-group"> <select class="form-control" name="category" placeholder="Category" required> <option value="">Select a Category</option> <option value="books">Books</option> <option value="clothes">Clothes</option> <option value="electronics">Electronics</option> <option value="games">Games</option> <option value="movies">Movies</option> <option value="tools">Tools</option> <option value="toys">Toys</option> <option value="other">Other</option> </select> </div> <div class="form-group"> <input class="form-control" type="text" name="starting_price" placeholder="Starting Price"> </div> <div class="form-group"> <input class="form-control" type="text" name="image_link" placeholder="Link to Image"> </div> <div class="form-group"> <input class="btn btn-primary" type="submit" value="Create"> </div> </form> </div> </div> {% endblock %} urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), … -
Cannot use a Django's foreign key result in the template
I have two tables in Django models.py connected by Foreign Key. class Category(models.Model): name = models.CharField(max_length=254) src = models.CharField(max_length=254, null=True, blank=True) friendly_name = models.CharField(max_length=254, null=True, blank=True) class Videos(models.Model): category_id = models.ForeignKey('Category', null=True, blank=True, on_delete=models.SET_NULL) title = models.CharField(max_length=254) content = models.URLField(max_length=1024) In a views.py I write the following code to use it in template def videos(request): videos = Videos.objects.all() categories = Category.objects.all() context = { 'videos' : videos, 'categories' : categories, } return render(request, 'videos/index.html', context) In the template I use the following jinja tags to output each category name followed by connected posts's titles. {% for category in categories %} <li class="nav-item mt-2"> <a class="nav-link ml-3 pl-0 pb-3 side-menu-section-name" href="#"> <img src="{{ category.src }}" width="45px" class="pr-2" alt="Video's Category's Icon">By {{ category.name }} </a> </li> {% for video in videos %} {% if video.category_id != None %} {% if video.category_id == category.name %} <!-- Here should be posts titles which are in current category --> {{ video.title }} {% endif %} {% endif %} {% endfor %} {% endfor %} So the problem is that the following comparison {% if video.category_id == category.name %} doesn't work. I print there's value separately and in print version booth's values are string with same … -
Create in Django objects linked list followed each to other
I'm trying to build in Django a kind of linked list of objects that will create objects by the user request. The main purpose is to build some kind of flowchart ob objects that will run some action. How to write the architecture by Django model/s? Thanks in advance. Daniel. -
Django logs not going to the expected log files
I have this LOGGING settings for my Django app. What I was expecting is that the views logs would go into their own separate folder when I have three different loggers in my views file. Logger in my view file: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'views_error_file': { 'class': 'logging.FileHandler', 'filename': 'logs/errors/views.debug.log', }, 'views_info_file': { 'class': 'logging.FileHandler', 'filename': 'logs/infos/views.debug.log', }, 'views_debug_file': { 'class': 'logging.FileHandler', 'filename': 'logs/debugs/views.debug.log', } }, 'loggers': { 'py_folder.views': { 'handlers': ['views_error_file'], 'level': 'ERROR', }, 'py_folder.views': { 'handlers': ['views_info_file'], 'level': 'INFO', }, 'py_folder.views': { 'handlers': ['views_debug_file'], 'level': 'DEBUG', } } } The views.py file: import logging # Get an instance of a logger logger = logging.getLogger(__name__) def sample_function(request): params_choices = ['param_1', 'param_2'] sample_param = request.POST.get('sample_param') # logger.debug should be logged at logs/debugs/views.debug.log logger.debug(sample_param) if sample_param in params_choices: if sample_param == 'param_1': # logger.info should be logged at logs/infos/views.debug.log logger.info("param_1 okay") return redirect("/param_1-req") else: # logger.error should be logged at logs/error/views.debug.log logger.error("param_2 okay") return redirect("/param_2-req") else: logger.error("param does not exist") return redirect("/param-invalid") But its only going in to the logs/debugs/views.debug.log. The logs/debugs/views.debug.log file: param_3 param does not exist I tried changing the logs/infos/views.debug.log to logs/infos/views.info.log and logs/error/views.error.log to logs/error/views.error.log but nothing changed. I don't know why … -
Check who is logged in Django admin panel
how to check whether the user is logged in or not from admin panel what are the changes i need to make in models.py and admin.py to achieve this from django.contrib.auth.models import User -
How to retrieve data from a model "function" with model.objects.values()?
this is my model class ArtWork(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT) title = models.CharField(max_length=40) desc = models.TextField(max_length=100) image = models.ImageField(upload_to=get_post_filename, null=True, blank=True) category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.SET_NULL) album = models.OneToOneField('PostImages', related_name='model', blank=True, null=True, on_delete=models.PROTECT) # identifier private_unique_id = models.CharField(max_length=200, blank=True, unique=True, default=uuid.uuid4) public_unique_id = models.CharField(max_length=200, blank=True, unique=True, default=uuid.uuid4) def __str__(self): return self.title def get_ratings(self): like = Vote.objects.filter(artwork=self, like=True, nope=False).count() nope = Vote.objects.filter(artwork=self, nope=True, like=False).count() return like, nope I'd like to get the ArtWork model function "get_ratings" in views with "values" filter posts = ArtWork.objects.filter(active=True).values('image', 'title', 'desc',) any help is appreciated, thanks in advance. -
How to allow users to select groups when register in django rest framework?
I am trying to create a custom registration in my rest framework API, in which users can make a POST request with the following data ['email', 'username', 'password', 'password2', 'groups'] ** my problem** : when I make a post request like this one in the photo I got an error {"groups":["Incorrect type. Expected pk value, received str."]} my goal : I need the user to be able to select the name of the group in the group field my files : # serializers.py class RegisterSerializer(serializers.ModelSerializer): password2 = serializers.CharField( style={'input_type': 'password'}, write_only=True) class Meta: model = User fields = ['email', 'username', 'password', 'password2', 'groups'] extra_kwargs = { 'password': {'write_only': True}, } def save(self): user = User( email=self.validated_data['email'], username=self.validated_data['username'] ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError( {'password': 'Passwords must match.'}) user.set_password(password) user.save() return user # views.py @api_view(['POST', ]) def Registration_view(request): if request.method == 'POST': serializer = RegisterSerializer(data=request.data) data = {} if serializer.is_valid(): account = serializer.save() data['response'] = 'successfully registered new user.' data['email'] = account.email data['username'] = account.username data['groups'] = account.groups else: data = serializer.errors # new_user = User.objects.all().get(username=data['username']) return Response(data) # return JsonResponse(serlize("json",modles.User.objects.get(username=data['username']))) -
what is the best way for updating (git pull) django app on ubuntu server with gunicorn and nginx?
last time when i git pull from github remote to ubuntu server(digital ocean) , server is down and gunicorn not working what is the safe way for update and git pull safely ? -
How can we set a model is as default=0 or defoult=null in django
Two month back I had created two models and it was working well, and now these models have lot of query which is filled by users. It is clear that both models are independent to each other. My previous models.py class State(models.Model): state_name = models.CharField(max_length=300, blank=False) state_code = models.CharField(max_length=100, blank=False,unique=True) @classmethod def get_all_states(self): return State.objects.all() def __str__(self): return self.state_name class College(models.Model): college_name = models.CharField(max_length=300, blank=False) college_code = models.CharField(max_length=100, blank=False,unique=True) university_name = models.CharField(max_length=300, blank=True) def __str__(self): return self.college_name Today I want to design College model according to state wise. If users have selected some state than related college list will come. For this condition I have created below models.py class State(models.Model): state_name = models.CharField(max_length=300, blank=False) state_code = models.CharField(max_length=100, blank=False,unique=True) @classmethod def get_all_states(self): return State.objects.all() def __str__(self): return self.state_name class College(models.Model): college_name = models.CharField(max_length=300, blank=False) college_code = models.CharField(max_length=100, blank=False,unique=True) university_name = models.CharField(max_length=300, blank=True) state_id = models.ForeignKey(State, on_delete=models.CASCADE) @classmethod def get_all_colleges(self): return self.College.objects.all() def __str__(self): return self.college_name In code you can see state_id (in College models) is a foreign key. When I did migration then It's showing the error You are trying to add a non-nullable field 'state_id' without a default; we can't do that (the database needs something to populate existing rows). … -
Serialize Nested Django models with Many to Many fields
I am trying to serialize a nested django model which is structured as below: class Ingredients(models.Model): ingredient=models.CharField(max_length=264) def __str__(self): return self.ingredient class Step(models.Model): Steps=models.CharField(max_length=264) Ingredient=models.ManyToManyField(Ingredients) def __str__(self): return self.Steps class Recipe(models.Model): user=models.ForeignKey(Users,on_delete=models.CASCADE) recipie_name=models.CharField(max_length=2640) Steps=models.ManyToManyField(Step) def __str__(self): return self.recipie_name I have a main Recipe model which consists of a "number of Steps" and the Steps have "different ingredients" to them. All linked using Many to Many field relation. So far, I have been able to serialize using the below code class IngredientSerializer(serializers.ModelSerializer): class Meta: model=Ingredients fields='__all__' class StepSerializer(serializers.ModelSerializer): ingredient=IngredientSerializer(many=True,read_only=True) class Meta: model=Step fields='__all__' class recipe_serialized(serializers.ModelSerializer): Step=StepSerializer(many=True,read_only=True) Steps = serializers.StringRelatedField(many=True) depth = 2 class Meta: model = Recipe fields = '__all__' Which gives me an output like: { "id": 1, "Steps": [ "Add two bananas together", "Then mix them with apples" ], "recipie_name": "strudel", "user": 1 }, My problem is, I am having a hard time trying to "expand" the Steps as well. As the Steps have ingredients linked to them using a Many to Many relations. So the ideal serializer will have the Step portion further broken down too. Would appreciate any guidance in this regard Thank you -
I have a problem with Django Admin. The screen is splitted
It maybe a very silly question but my Admin site splits the screen for the detail instead of opening a new page and it becomes very hard to interact with it. In this example, I select the Sequences option and the records are shown below on the bottom half of the screen. Any help would be appreciated. -
Unable to login in website when user is created django
I am not able to login in website i created from django.contrib import messages from django.shortcuts import HttpResponse, render, redirect from home.models import Contact from blog.models import Post from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.views.decorators.csrf import csrf_exempt def home(request): return render(request, 'home/home.html') def about(request): return render(request, 'home/about.html') def contact(request): if request.method == 'POST': name = request.POST['name'] email = request.POST['email'] phone = request.POST['phone'] description = request.POST['description'] if len(name)<3 or len(email)<5 or len(phone)<10 or len(description)<2: messages.error(request, 'Please fill the form correctly!') else: contact = Contact(name=name, email=email, phone=phone, description=description) contact.save() messages.success(request, 'Your message has been succesfully sent!') return render(request, 'home/home.html') return render(request, 'home/contact.html') def search(request): query = request.GET['query'] if len(query)>50: allposts = Post.objects.none() else: allposts_title = Post.objects.filter(title__icontains=query) allposts_content = Post.objects.filter(content__icontains=query) allposts = allposts_title.union(allposts_content) if allposts.count() == 0: messages.warning(request, 'No search results found!') params = {'allposts':allposts, 'query':query} return render(request, 'home/search.html', params) @csrf_exempt def signup(request): if request.method == 'POST': username = request.POST.get('username') fname = request.POST.get('firstname') lname = request.POST.get('lastname') email = request.POST.get('email') password = request.POST.get('password') confirm_password = request.POST.get('confirm_password') # validation if len(username) < 2: messages.error(request, 'Username must be more than 2 characters') return redirect('home') if len(username) >15: messages.error(request, 'Username must be under 15 characters') return redirect('home') if … -
(actual errors: ['Select a valid choice. That choice is not one of the available choices.']) when trying to test a form
I am trying to test that a form will redirect when it is successfully posted, but I am getting this error: (actual errors: ['Select a valid choice. That choice is not one of the available choices.']) Model.py class BookInstance(models.Model): """Model representing a specific copy of a book (i.e that can be borrowed from the library).""" id = models.UUIDField( primary_key = True, default = uuid.uuid4, help_text = 'Unique ID for this particular book across whole library' ) book = models.ForeignKey('Book', on_delete = models.RESTRICT, null = False, blank = False) imprint = models.CharField(max_length=200) due_back = models.DateField(null = True, blank = True) LOAN_STATUS = ( ('m', 'Maintenance'), ('o', 'On loan'), ('a', 'Available'), ('r', 'Reserved'), ) status = models.CharField( max_length=1, choices=LOAN_STATUS, blank='True', default='m', help_text = 'Book availability' ) borrower = models.ForeignKey( User, on_delete = models.SET_NULL, null = True, blank = True) @property def is_overdue(self): if self.due_back and date.today() > self.due_back: return True return False class Meta: """order queries according to due back dates""" ordering = ['due_back'] permissions = ( ("can_mark_returned", "set book as returned"), ) def __str__(self): """String for representing the Model object.""" """ representes it as 'id.title-status'""" return f"{self.id}({self.book.title})-{self.status}" view.py def renew_book_librarian(request, pk): book_instance = get_object_or_404(BookInstance, pk = pk) if request.method == 'POST': … -
Angular or React Frontend with Django Backend
I would like to switch to a custom frontend for my Django project instead of the classic Django template engine. The question is whether I should use the Angular Framework or React. I want to connect frontend and backend via Django REST API.