Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error passing field to views, How do I correctly pass the model field to the view?
I am trying to pass a model field to the view to calculate the sum of time, but I get an error: Cannot resolve keyword 'hours_worked' into field. Choices are: car, car_id, date, deal_gts, deal_me, driver, driver_id, finish_work, gain, id, start_work models.py class Trip(models.Model): date = models.DateField(auto_now=False, verbose_name='Дата') car = models.ForeignKey(Cars, on_delete=models.CASCADE, verbose_name='Автомобиль') driver = models.ForeignKey(Driver, on_delete=models.CASCADE, verbose_name='Водитель') start_work = models.TimeField(verbose_name='Начало работы') finish_work = models.TimeField(verbose_name='Окончание работы') hours_worked = models.CharField(max_length=20, blank=True, verbose_name='Отработано часов') deal_me = models.IntegerField(verbose_name='Сделки МЭ', blank=True, default=0) deal_gts = models.IntegerField(verbose_name='Сделки ГТС', blank=True, default=0) gain = models.IntegerField(verbose_name='Выручка') class Meta: verbose_name = 'Доставка' verbose_name_plural = 'Достваки' def hours_worked(self): fw = self.finish_work sw = self.start_work hw = datetime.combine(date.today(), fw) - datetime.combine(date.today(), sw) hours_worked = str(hw).rsplit(':', 1)[0] return hours_worked wiews.py from django.shortcuts import render, redirect from .forms import TripForm from .models import Trip def home_view(request): trip = Trip.objects.all() # сумма чвасов sum_hour = 0 me = Trip.objects.values_list('hours_worked') # print(me) for el in me: for i in el: sum_hour = int(sum_hour) + int(i) context = { 'sum_hour': sum_hour } return render(request, 'driver_productivity/home.html', context) Tell me if I'm thinking in the right direction, or is it better to do the calculation not in the model? -
How to select from a subquery in Django's ORM?
I want to select all rows for which bet_index is not NULL: BetHistory.objects.values('account_id').annotate( bet_index=models.Case(models.When( models.Q(event_id=1, market_id=2) & (models.Q(account_id=3) | models.Q(account_id=4)), then=0), default=None, output_field=models.IntegerField()) ).exclude(bet_index=None) that yields the following SQL query SELECT "bet_history"."account_id", CASE WHEN ( "bet_history"."event_id" = 1 AND "bet_history"."market_id" = 2 AND ( "bet_history"."account_id" = 3 OR "bet_history"."account_id" = 4 ) ) THEN 0 ELSE NULL end AS "bet_index" FROM "bet_history" WHERE NOT ( CASE WHEN ( "bet_history"."event_id" = 1 AND "bet_history"."market_id" = 2 AND ( "bet_history"."account_id" = 3 OR "bet_history"."account_id" = 4 ) ) THEN 0 ELSE NULL end IS NULL ) but there the case is repeated, I would like to have the following query: SELECT * FROM (SELECT "bet_history"."account_id", CASE WHEN ( "bet_history"."event_id" = 1 AND "bet_history"."market_id" = 2 AND ( "bet_history"."account_id" = 3 OR "bet_history"."account_id" = 4 ) ) THEN 0 ELSE NULL end AS "bet_index" FROM "bet_history") AS "subquery" WHERE "subquery"."bet_index" IS NOT NULL; so I need a select from subquery, how to do it in Django? Thanks. -
Celery tasks don't run in docker container
In Django, I want to perform a Celery task (let's say add 2 numbers) when a user uploads a new file in /media. What I've done is to use signals so when the associated Upload object is saved the celery task will be fired. Here's my code and Docker configuration: signals.py from django.db.models.signals import post_save from django.dispatch import receiver from core.models import Upload from core.tasks import add_me def upload_save(sender, instance, signal, *args, **kwargs): print("IN UPLOAD SIGNAL") # <----- LOGS PRINT UP TO HERE, IN CONTAINERS add_me.delay(10) post_save.connect(upload_save, sender=Upload) # My post save signal tasks.py from celery import shared_task @shared_task(ignore_result=True, max_retries=3) def add_me(upload_id): print('In celery') # <----- This is not printed when in Docker! return upload_id + 20 views.py class UploadView(mixins.CreateModelMixin, generics.GenericAPIView): serializer_class = UploadSerializer def post(self, request, *args, **kwargs): serializer = UploadSerializer(data=request.data) print("SECOND AFTER") print(request.data) <------ I can see my file name here if serializer.is_valid(): print("THIRD AFTER") <------ This is printer OK in all cases serializer.save() print("FOURTH AFTER") <----- But this is not printed when in Docker! return response.Response( {"Message": "Your file was uploaded"}, status=status.HTTP_201_CREATED, ) return response.Response( {"Message": "Failure", "Errors": serializer.errors}, status=status.HTTP_403_FORBIDDEN, ) docker-compose.yml version: "3.8" services: db: # build: ./database_docker/ image: postgres ports: - "5432:5432" environment: POSTGRES_DB: test_db … -
duplicate key value violates unique constraint "usuarios_usuario_email_key" DETAIL: Key (email)=() already exists
I'm looking for users in an old model and saving in a new model, only that my new model the email is unique, I would like to know how I can do a check if there is an equal email, do not save this email and leave it blank @task(bind=True) @transaction.atomic def importa_usuario(self, id_usuarios=None): logger.info('Importando V2: %s', self.name) lock_id = '{0}-lock'.format(self.name) antes = datetime.datetime.utcnow().replace(tzinfo=timezone.utc) - datetime.timedelta(hours=2) agora = datetime.datetime.utcnow().replace(tzinfo=timezone.utc).time() with memcache_lock(lock_id, self.app.oid) as acquired: if settings.DEBUG: import pdb; pdb.set_trace() acquired = True if acquired: logger.info("Buscando usuario...\r") usuarios = list(Usuarios.objects.all().order_by('-id')[:100]) logger.info("{0} Amostra liga encontrada".format(len(usuarios))) dados_webmap = { "usuarios": usuarios } logger.info('Importando dados...') count = 0 erro = 0 total = len(usuarios) logger.info("Excluindo dados anteriores...\r") if id_usuarios: usuarios = list(filter(lambda lista: lista.id == int(id_usuarios), usuarios)) for usuario in usuarios: logger.info("Importando {0} dados...\r".format(len(usuarios))) usuario_atual = Usuario.objects.filter(id=int(usuario.id)) if usuario_atual.exists(): usuario_atual.delete() dado = Usuario() try: dado.id = usuario.id dado.email = usuario.email dado.first_name = usuario.nome dado.set_password("senha") dado.save() enter image description here -
how can I grab a number from URL and check it's length in django?
I need to verify the length of number grabbed from URL such as example.com/12345678 in django ? urlpatterns = [ path("", main.views.index, name="index"), path("admin/", admin.site.urls), path('<int:tnum>/', main.views.number, name="number") And if the number doesn't match a certain length I want to output number is invalid. -
Why am I getting a network error when trying to make an axios post request from a react-native app to my django server?
I am trying to set up a login service for my react-native app. When trying to send an axios post request to my django server i get a network error. The django server shows that it has received a request but gives it error 400. I have added CORS to the django server and the requests work fine using Postman. I have been following this tutorial on how to set it up: https://towardsdatascience.com/build-a-fully-production-ready-machine-learning-app-with-python-django-react-and-docker-c4d938c251e5 Please could somebody tell me what I've done wrong. Here is my code: settings.py (snippet) INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'corsheaders', 'prediction', 'users', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', '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 = 'mainapp.urls' CORS_ALLOW_ALL_ORIGINS = True actions.py export const authLogin = (username, password) => { return dispatch => { dispatch(authStart()); axios.post(`http://localhost:8000/api/auth/login/`, { username: username, password: password, }) .then(res => { const token = res.data.key; const expirationDate = new Date(new Date().getTime() + SESSION_DURATION ); localStorage.setItem('token', token); localStorage.setItem('expirationDate', expirationDate); dispatch(authSuccess(token)); dispatch(authCheckTimeout(SESSION_DURATION)); }) .catch(err => { console.log(err) dispatch(authFail(err)) }); } } I can provide any other parts of my code if required. -
Django, Path return 404
I've got an issue with my Django app, when i try to browse to http://127.0.0.1:8000/list/ it returns a 404 error : Using the URLconf defined in f_django.urls, Django tried these URL patterns, in this order: ^contact/$ ^description/$ ^$ myapp/ admin/ The current path, list/, didn't match any of these. Here my urls.py file : from django.contrib import admin from django.urls import path from django.conf.urls import url from django.urls import include from . import views urlpatterns = [ url(r'^contact/$',views.contact), url(r'^description/$',views.description), url(r'^$',include('myapp.urls')), path('myapp/',include('myapp.urls')), path('admin/', admin.site.urls), ] My myapp/urls.py file : from django.conf.urls import url from django.urls import path from . import views urlpatterns = [ url(r'^$',views.index), url(r'^list',views.list), url(r'^Articles/(?P<id>[0-9]+)$', views.details), ] And this line in my settings.py : INSTALLED_APPS = [ 'myapp.apps.MyappConfig', ] Thanks in advance for your help -
Simple to do app but with different tasks in a each group(many to one relationship)
Main problem: When user is at this url http://127.0.0.1:8000/8/, so group_id is already in url of his current page, he must choose group_id that he wants to assign task, if I do fields = ['title', completed'] in forms.py user can't choose group_id but he needs to. I have primary key but I don't know where to apply it in views P.S.: IndexView from views.py has no problem in it and works fine, also get method in GroupView works fine to. Anything works fine but user needs to choose a group that he want's to assign tasks forms.py: from django import forms from .models import * class AddTaskForm(forms.ModelForm): class Meta: model = Task fields = '__all__' class AddGroupForm(forms.ModelForm): class Meta: model = Group fields = '__all__' models.py from django.db import models from django.utils import timezone class Group(models.Model): title = models.CharField(max_length=255) def __str__(self): return self.title class Task(models.Model): title = models.CharField(max_length=255) group = models.ForeignKey(Group, on_delete=models.CASCADE) completed = models.BooleanField(default=False) def __str__(self): return self.title def task_is_expired(): return timezone.now() < self.deadline views.py from django.shortcuts import render, redirect from django.views import generic from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from .models import * from .forms import * class IndexView(generic.ListView): template_name = 'tasks/index.html' form_class = AddGroupForm … -
Send_mail() triggered at the same time by different users
Say that I have 10 different users that register at the same time and system is sending email to every registered user. I am wondering what would the process look like when Django send_mail() is triggered multiple times simultaneously - do those emails queue and are executed one by one and simply slower the registration process for some users and making them wait till their emails are sent (so they wait little longer to be redirected after hitting 'Register' button)? Or would that end up with some sort of error? I know that I could use Celery and make it asynchronous, but I am curious what happens without it and if the only problem that I should be concern of is website working slower in such case. -
Use Django ORM to take values from field that have some Set of values in enother field
How to get bellow by using django ORM myset = {2, 3} I need names from field 'name' that have '2'&'3' only in 'value' field: Table in DB (model.Mytable) 'name'|'value' -------------- 'Ann' |'2' 'Ann' |'3' 'Ann' |'5' 'John'|'2' 'John'|'3' 'Jim' |'3' 'Jim' |'2' 'Pit' |'7' 'Pit' |'8' Needed output: ['John', 'Jim'] # value '2','3' only So, I try to get construction like: QuerySet [('Ann', ['2','3','5']), ('John', ['2', '3']), ... using .annotatte(), .values() But i don't know how get it using Django ORM. Or i can use some filterin .filters()? -
Django allauth error. what can i do for this error
django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: account and then when i define app_label give me that error: django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'account.User' that has not been installed how can i fix it -
How to auto arrange height width media file inside HTML?
I have multiple files contain photo and video also. I want the file to auto adjust without creating the list of files and show a proper display with proper adjustment like facebook or instagram. I would be grateful for any help. HTML <div class="col-lg-12" id="post-box"> {% for object in newss %} <div class="hpanel blog-box"> <div class="panel-heading"> <div class="media clearfix"> <a class="pull-left"> <img src="{{ object.author.profile.image.url }}" alt="profile-picture"> </a> </div> </div> <div class="panel-image" id="media-output"> {% for i in object.filemodel_set.all %} {% if ".jpeg" in i.file.url or ".jpg" in i.file.url or ".png" in i.file.url %} <img src="{{i.file.url}}" alt="article" class="img-responsive card-img-top"> {% endif %} {% if ".mp4" in i.file.url or ".mpeg" in i.file.url or ".mov" in i.file.url %} <video class="afterglow" id="myvideo" width="1280" height="720" data-volume=".5"> <source type="video/mp4" src="{{i.file.url}}#t=0.9" /> </video> {% endif %} {% endfor %} </div> <div class="panel-body"> <div class="title"> <a href="{% url 'news-detail' pk=object.pk %}"> <h4>{{ object.title|slice:":100" }}</h4> </a> </div> </div> </div> {% endfor %} </div> -
How to embed img from external hosting in Django Template?
I am trying to use Gdrive image url in django template Django Template <li class="post"><a href="{{post.href}}"><img src="{{post.src}}" alt="{{post.alt}}" width=auto height="300px"><h4>{{post.name}}</h4></a></li> Django Model from django.db import models class Post(models.Model): catname = models.CharField(max_length=15) href = models.CharField(max_length=100) scr = models.CharField(max_length=100) alt = models.CharField(max_length=100) name = models.CharField(max_length=100) But actual url of scr is scr="https://drive.google.com/uc?id=xyz" There is a error in loading in image from external source (gdrive img link) <img src(unknown) alt="#img3" width="auto" height="300px"> How to pass a external img url as src url in Django -
How to remove username field and password2 field from RegisterSerializer in django rest framework?
When I call the api/seller/register api, the fields appear are username, password1 and password2. I want these removed and only want simple password, email and phone_num. How to remove this? I am trying to make a seller registration using RegisterSerializer. I tried with ModelSerailzers and provided fields as I want but this will lead to me the error saying save() only takes 1 argument.So, I just want these unnecessary fields removed using RegisterSerializer. My model: class CustomUserManager(BaseUserManager): """ Custom user model manager with email as the unique identifier """ def create_user(self, first_name, last_name, email, password, **extra_fields): """ Create user with the given email and password. """ if not email: raise ValueError("The email must be set") first_name = first_name.capitalize() last_name = last_name.capitalize() email = self.normalize_email(email) user = self.model( first_name=first_name, last_name=last_name, email=email, **extra_fields ) user.set_password(password) user.save() return user def create_superuser(self, first_name, last_name, email, password, **extra_fields): """ Create superuser with the given email and password. """ extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) extra_fields.setdefault("is_active", True) if extra_fields.get("is_staff") is not True: raise ValueError("Superuser must have is_staff=True.") if extra_fields.get("is_superuser") is not True: raise ValueError("Superuser must have is_superuser=True.") return self.create_user(first_name, last_name, email, password, **extra_fields) class CustomUser(AbstractUser): username = models.CharField(max_length=255,blank=False) first_name = models.CharField(max_length=255, verbose_name="First name") last_name = models.CharField(max_length=255, verbose_name="Last name") … -
<li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li> not working
I tried this code : <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li> and it gives me an error -
How to find by ObjectId Django, MongoDB
How to find by ObjectId (id field) record = Record.objects.filter(_id=id).first() -> None record = Record.objects.get(_id=id) -> Error DoesNotExists -
How do I get the first Item from this get?
Hi I'm trying to get the first item of a Django Model. How can I get it? I'm looking for the object with the same customer name as the customer (I'm building a webshop btw). Here is my model: class MessageItem(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) mItem = models.CharField(max_length=255, null=True) mQuantity = models.CharField(max_length=255, null=True) mOrderItem = models.CharField(max_length=255, null=True) Here is the create function: createModel = MessageItem for item in items: createModel.objects.create(customer=customer, mItem=item.product.name, mQuantity=str(item.quantity), mOrderItem=str(items)) And here is the Get function: orderMessage = MessageItem.objects.get(customer=customer) message_to_send = str(message) + " " + orderMessage Thanks for the Help! -
SCORM from chamilo Platform
I´m developing and e-learning platform in Django based on Chamilo LMS services and databases. Currently I´m facing a problem with course content because of cookies (I think is that). The data extracting using the api is used to fill an url with parameters to be passed on PHP file but in the iFrame nothing is shown, only shows a login form. -
CartItem matching query does not exist django
So i'm trying to remove an item from cart when user checkouts, When i click on checkout I get CartItem matching query does not exist. error. I'm using makeorder function as getting request and createorder function for creating an order. views.py from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User from django.contrib.auth import login, logout, authenticate from django.db import IntegrityError from .models import Book, CartItem, OrderItem from django.contrib.auth.decorators import login_required from .forms import BookForm from django.core.exceptions import ObjectDoesNotExist # Create your views here. removederror = '' def calculate(request): oof = CartItem.objects.filter(user=request.user) fianlprice = 0 for item in oof: fianlprice += item.book.price def signupuser(request): if request.user.is_authenticated: return render(request, 'main/alreadyloggedin.html') elif request.user != request.user.is_authenticated: if request.method == "GET": return render(request, 'main/signupuser.html', {'form':UserCreationForm()}) elif request.method == "POST": if request.POST['password1'] == request.POST['password2']: try: user = User.objects.create_user(request.POST['username'], password=request.POST['password1']) user.save() login(request, user) return render(request, 'main/UserCreated.html') except IntegrityError: return render(request, 'main/signupuser.html', {'form':UserCreationForm(), 'error':'That username has already been taken. Please choose a new username'}) else: return render(request, 'main/signupuser.html', {'form':UserCreationForm(), 'error':'Passwords did not match'}) def signinuser(request): if request.user.is_authenticated: return render(request, 'main/alreadyloggedin.html', {'error':'You are already logged in'}) elif request.user != request.user.is_authenticated: if request.method == "GET": return render(request, 'main/signinuser.html', {'form':AuthenticationForm()}) elif request.method == "POST": user = … -
custom role based login in Django
I am working on a project in Django 3.1.2 I have created customer and admin site separately, but the designer has some functionalities to modify some files, and entries in database from admin side, you can consider designer as staff. I can use @login_required validator to restrict unauthenticated user to access the pages, but I also want to make stop the designer to use all the functionalities of the admin site pages which admin can do, so I have taken a field role in user table so that I can easily identify the type of user, but don't know how to use is to create it in login so that I don't have to check in every view for the user role. My user models is as shown below : models.py class User(AbstractUser): GENDER = ( (True, 'Male'), (False, 'Female'), ) USER_TYPE = ( ('Admin', 'Admin'), ('Designer', 'Designer'), ('Customer', 'Customer'), ) user_id = models.AutoField("User ID", primary_key=True, auto_created=True) avatar = models.ImageField("User Avatar", null=True, blank=True) gender = models.BooleanField("Gender", choices=GENDER, default=True) role = models.CharField("User Type", max_length=10, choices=USER_TYPE, default='Customer') now here I want a function that will identify the user's role and according to role it redirects to the desired page and access contenet … -
Error "No Models matches the given query" after using get_next_by_FOO django
When using get_next_by_Foo, it doesnt show content in template file. I get data from this query: request.session['contract_posts_search'] is results I get from filtering in another view. def contract_detail_test(request, contract_id=None): context = {} contract_posts_search=request.session['contract_posts_search'] contract_filtered=[] for i in range(len(contract_posts_search)): contract_filtered.append(contract_posts_search[i]["fields"]["contract"]) contract_posts_search= Contracts.objects.filter(contract__in=contract_filtered).distinct() contract_posts = get_object_or_404(contract_posts_search, contract=contract_id) After having contract_post, I use get_next_by_created_at: if contract_posts is not None: print(contract_posts) try: the_next = contract_posts.get_next_by_created_at() except: the_next=None try: the_prev = contract_posts.get_previous_by_created_at() except: the_prev=None context = { "contract_posts": contract_posts, "the_next" : the_next, "the_prev": the_prev, } return render(request, "contract_detail_test.html", context) For example: I filter contract contain "2016" and get 10 results, using request_session in another view, I can print out 10 results. Then I use get_next_by_created_at, It will show first result correctly, but after clicking, it will show this error. There is no contract number 20170709-0010161 in contract_posts Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/contract_detail_test/20170709-0010161/ Raised by: test_upload_filter.views.contract_detail_test No Contracts matches the given query. -
Django Admin custom field in list_editable without fk
i have models class Supplier_items(models.Model): si_name = models.CharField(max_length=200, blank=True, null= True, verbose_name='Название поставщика') si_url = models.CharField(max_length=200, blank=True, null= True, verbose_name='URL поставщика') si_ean = models.CharField(max_length=200, blank=True, null= True) si_price = models.FloatField( blank=True, null= True, verbose_name='Price') def __str__(self): return self.si_name class Order(models.Model): order_id = models.CharField(max_length=50, blank=True, null= True) shop = models.CharField(max_length=50, blank=True, null= True) created = models.DateTimeField('Дата добавления', default=timezone.now) price = models.CharField(max_length=50, blank=True, null= True) price_real = models.CharField(max_length=50, blank=True, null= True) order_ean = models.CharField(max_length=100, blank=True, null= True) variant = models.CharField(max_length=50, blank=True, null= True) def __str__(self): return self.item_name def variant(self, *args, **kwargs): queryset = Supplier_items.objects.filter(si_ean__contains = self.order_ean) return queryset there is no way to link by key in list_display it shows how the text is normal, list_editable - gives an error (admin.E121) The value of list_editable [0]' refers to 'variant' I want to output the variant field in admin as a select field and write the selection to the corresponding field in the model. thanks for the help -
Django serializers nested data reformat
I have a three model course_category,course and sub_course which have Foreign key relationship between them serially. I am using DRF serializer to pull a nested data where i want a course_category as my first parent and course as second and subcourse as child but it is totally opposite while i use prefetch_related(). class course_categories(models.Model): deleted_flag = [('y', 'yes'), ('n', 'no')] category_name = models.CharField(max_length=50, unique=True) created_by = models.CharField(max_length=50) created_date = models.DateTimeField(auto_now_add=True) modified_by = models.CharField(max_length=50, blank=True, null=True) modified_date = models.DateTimeField( auto_now_add=False, blank=True, null=True) is_deleted_flag = models.CharField( max_length=1, choices=deleted_flag, default='n') def __str__(self): return self.category_name class courses(models.Model): deleted_flag = [('y', 'yes'), ('n', 'no')] course_name = models.CharField(max_length=70) course_categories = models.ForeignKey( 'course_categories', on_delete=models.CASCADE) created_by = models.CharField(max_length=50) created_date = models.DateTimeField(auto_now_add=True) modified_by = models.CharField(max_length=50, blank=True, null=True) modified_date = models.DateTimeField( auto_now_add=False, blank=True, null=True) is_deleted_flag = models.CharField( max_length=1, choices=deleted_flag, default='n') def __str__(self): return self.course_name class subcourse(models.Model): deleted_flag = [('y', 'yes'), ('n', 'no')] subcourse_name = models.CharField(max_length=50, unique=True) courses = models.ForeignKey( 'courses', related_name="subcourse", on_delete=models.CASCADE) subcourse_short_description = models.CharField(max_length=150, blank=True) created_by = models.CharField(max_length=50) created_date = models.DateTimeField(auto_now_add=True) modified_by = models.CharField(max_length=50, blank=True, null=True) modified_date = models.DateTimeField( auto_now_add=False, blank=True, null=True) is_deleted_flag = models.CharField( max_length=1, choices=deleted_flag, default='n') here is my models.py and serializers here class CourseSerializerView(serializers.ModelSerializer): # subcourse = SubcourseSerializerView() class Meta: model = courses fields = ('__all__') … -
Are Django and node.js can be implemented in same project?
Can I use both Django and node.js in the same application? if it is yes, How?👏 Some say Redis can be good for the implementation. But I did not understand how it can be implemented? -
"127.0.0.1:8000 says Url failed with 404 /ad/1/favorite/" not able to favorite/unfavourite [closed]
I think this issue might be trivial, but, can someone please suggest to me an alternative for this code I did change the structure and wrote it as : I pretty much just changed the way the URL was written, and when I ran my code on localhost and clicked on the star, this is what I get...a prompt saying: 127.0.0.1:8000 says Url failed with 404 /ad/1/favorite/ Kindly tell me, is there anything wrong I'm doing? I'm sure the mistake is somewhere here, but, if not I can also upload code from the views.py and urls.py files...