Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: can't login after editing user details
I'm trying to find a solution for 2 days now... can't figure out why login does not work for me once I have changed any user details. Normal flow works fine for me: user registers, logs in and out without a problem. But I thought it would be good to have profile change option where a user can change username, password or email. I did implement this, but after a user changes anything (even email), the login form does not admit him. Here is my views.py: class ProfileView(UpdateView): template_name = 'boat_app/edit_profile.html' form_class = UserChangeForm success_url = reverse_lazy('anchored') def get_object(self): return self.request.user class LoginView(TemplateView): template_name = 'boat_app/login.html' success_url = reverse_lazy('category_home') def post(self, request): print(request) user = authenticate(request, username=request.POST.get('username'), password=request.POST.get('password')) if user is not None: print('user not none') login(request, user) return HttpResponseRedirect(reverse('anchored')) else: print('user none') messages.info(request, 'Username OR password is incorrect') return HttpResponseRedirect(reverse('login')) And forms.py class EditUserForm(forms.ModelForm): class Meta: model = User fields = ('username', 'email') After changing a user I see this change in admin interface, so it does work. But I can't see a reason why the system does not see this relation. Any way to debug what exactly is going on there? -
Getting Error: AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
I am completely new to Django i've some that error when i want to run my django.cgi configuration: python3.7 and django3.1.6 error traceback: Traceback (most recent call last): File "django.cgi", line 80, in <module> run_with_cgi(django.core.handlers.wsgi.WSGIHandler()) File "/home/lesproh/.local/lib/python3.7/site-packages/django/core/handlers/wsgi.py", line 127, in __init__ self.load_middleware() File "/home/lesproh/.local/lib/python3.7/site-packages/django/core/handlers/base.py", line 40, in load_middleware middleware = import_string(middleware_path) File "/home/lesproh/.local/lib/python3.7/site-packages/django/utils/module_loading.py", line 17, in import_string module = import_module(module_path) File "/usr/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/lesproh/.local/lib/python3.7/site-packages/django/contrib/auth/middleware.py", line 3, in <module> from django.contrib.auth.backends import RemoteUserBackend File "/home/lesproh/.local/lib/python3.7/site-packages/django/contrib/auth/backends.py", line 2, in <module> from django.contrib.auth.models import Permission File "/home/lesproh/.local/lib/python3.7/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/lesproh/.local/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 48, in <module> class AbstractBaseUser(models.Model): File "/home/lesproh/.local/lib/python3.7/site-packages/django/db/models/base.py", line 108, in __new__ app_config = apps.get_containing_app_config(module) File "/home/lesproh/.local/lib/python3.7/site-packages/django/apps/registry.py", line 253, in get_containing_app_config self.check_apps_ready() File "/home/lesproh/.local/lib/python3.7/site-packages/django/apps/registry.py", line 136, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. my django app settings INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_mysql', 'crispy_forms', 'captcha', 'django_countries', … -
Which is the best CSS framework for Django [closed]
I'm starting my first project but I don't know which framework to use. -
AMU Jobs and Recruitments [closed]
As we all know that Aligarh Muslim University is understood for its best working environment among all Universities of India. Getting AMU jobs are one among the dreams of a person in India. AMU recruited many students per annum. There are some steps and directions which should be followed by every candidate who want to be the part of AMU. vist here for more - https://notesmyfoot.com/amu-jobs-and-vacancy/ -
Checkbox booleanfield modelform in Django
So I'm making a to-do list and I made a booleanfield modelform which has attribute "complete". I want that user to check it when it's complete and I tried wriring if task.complete == True cross out the item and it didn't work(it only worked when I checked it from the admin panel). Then I tried form.complete instead of task.complete and it doesn't do anything. models: class Task(models.Model): title = models.CharField(max_length=200) complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title forms: from .models import * class TaskForm(forms.ModelForm): title = forms.CharField(widget= forms.TextInput(attrs={'placeholder':'Add new task...'})) class Meta: model = Task fields = '__all__' views: def index(request): tasks = Task.objects.order_by('-created') form = TaskForm() if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = { 'tasks': tasks, 'form': form, } return render(request, 'to-do.html', context) html: [![<div class="main-container"> <form method="POST" action="/"> {% csrf_token %} <input type="submit"/> {{ form.title }} </form> {% for task in tasks %} {{ form.complete }} {% if form.complete == True %} <h1><strike>{{task.title}}</strike></h1> {% else %} <h1>{{task.title}}</h1> {% endif %} {% endfor %} </div>] -
Send mail when more than 10 matches are assigned to user in a month
I have two models. A User model and a Match model. A user can subscribe to my service for either 6/12/18 months on any given date. I want to limit a user to a maximum of 10 matches per month. If the user crosses 10 matches in a month, I want to send an alert email. The 10 match quota should reset the following month. How do i achieve this? Following are the models: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(verbose_name='email address', max_length=255, unique=True) MembershipStart = models.DateTimeField(blank=True, null=True, verbose_name="Membership Start Date") MembershipLength = models.IntegerField(verbose_name='Length of membership in months from MembershipStart') class Match(models.Model): user = models.ManyToManyField(User, blank = True) name = models.CharField(max_length = 100) created_on = models.DateTimeField(default=timezone.now) -
PyCharm: ImportError: libmysqlclient.so.20 only when I run django app from IDE
I am working on a simple Django app using PyCharm community edition, python 3.9 and ubuntu 20.04. The project's virtual environment is in folder [project root]/venv/ When I start the app from the pycharm terminal window I execute the following commands and everything works fine (no import errors): source ./venv/bin/activate python manage.py runserver When I start the app from the IDE running configuration, I get an ImportError: libmysqlclient.so.20: cannot open shared object file: No such file or directory. Given that the project runs via the terminal, I believe that my python installation and my virtual environment are ok. I guess that this should not happen if the IDE run/debug configuration was using the same virtual environment hosted in [project root]/venv/. Therefore, I suppose the run/debug configuration is not correctly configured, or there is something missing in my paths. I have checked other posts but I could not find a solution. The following screenshots depict my run/debug configuration and the setup of my virtual environment in the PyCharm IDE (also showing the respective packages). Could somebody please guide me? Is there a setting in PyCharm IDE that I should check for? Do I miss something fundamental about how do python virtual … -
Webpage using Django opening but not loading in browser
I am using Visual Studio Code for coding python using django framework. But when I open the http://127.0.0.1:8000/ on my browser it always shows waiting for 127.0.0.1:8000 but the page never loads. I have been using the command python manage.py runserver still the page does not load. Can someone help me with where am I going wrong? -
django nesting TextField within ArrayField for postgres
Django provides a nice to way to write ArrayFields in PGSql: https://docs.djangoproject.com/en/3.1/ref/contrib/postgres/fields/#arrayfield eg: class Board(models.Model): pieces = ArrayField(ArrayField(models.IntegerField())) I also see other examples using CharField - which I have used in the past and works just fine. Now, I was wondering if I can do the same with TextField like so: class Board(models.Model): extra_array = ArrayField(models.TextField(blank=True), default=list) Is this legit to do this? Are there any gotachas I need to be aware of? None of the examples seem to use TextField and I wondered why! -
Notifications didn't work for me in django
I try to build a notification system, in which anyone (user) clicks like in the video then send a notification, and after this didn't work for me I don't know why my notification model class Notification(models.Model): NOTIFICATION_TYPE = ((1, 'like')) video = models.ForeignKey("videos.Video", on_delete=models.CASCADE, related_name="noti_video", blank=True, null=True) sender = models.ForeignKey(Account, on_delete=models.CASCADE, related_name="noti_from_user") user = models.ForeignKey(Account, on_delete=models.CASCADE, related_name="noti_to_user") notification_type = models.IntegerField(choices=NOTIFICATION_TYPE) text_preview = models.CharField(max_length=90, blank=True) date = models.DateTimeField(auto_now_add=True) is_seen = models.BooleanField(default=False) the notification in the video model class Notification(models.Model): NOTIFICATION_TYPE = ((1, 'like')) video = models.ForeignKey("videos.Video", on_delete=models.CASCADE, related_name="noti_video", blank=True, null=True) sender = models.ForeignKey(Account, on_delete=models.CASCADE, related_name="noti_from_user") user = models.ForeignKey(Account, on_delete=models.CASCADE, related_name="noti_to_user") notification_type = models.IntegerField(choices=NOTIFICATION_TYPE) text_preview = models.CharField(max_length=90, blank=True) date = models.DateTimeField(auto_now_add=True) is_seen = models.BooleanField(default=False) the view of the notification def showNotifications(request): user = request.user notifications = Notification.objects.filter(user=user).order_by('-date') template = loader.get_template('notifications/notifications.html') context = { 'notifications': notifications, } return HttpResponse(template.render(context, request)) -
Data retrieval from two models that are related to each other with user model
I have two models that are not related to each other but both of them are related to the user model. // modelA class ModelA(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(null=False) ... // modelB class ModelB(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) category = models.CharField(null=False) ... When I want to return ModelB information, I need to return the name field of ModelA that their user is the same. How can I do this? I tried several times but to no avail like this: @api_view(['GET']) def retrieve_model_b(request, id): try: from django.db.models import Q _qs = ModelB.objects.filter(Q(company__sahamdar__exact=id)) serializer = SahamdarSerializer(_qs, many=True) return Response(serializer.data, status=status.HTTP_200_OK) ... Serializer is as follow: class ModelBSerializer(serializers.ModelSerializer): name_of_user = PrimaryKeyRelatedField( source='modela_set', many=False, read_only=True, ) class Meta: model = ModelB fields = ('id', 'name_of_user', 'category') -
Inner join and group by in django REST framework
I am new in Django Rest Framework This is my query in SQL SELECT p7_test.professionals.full_name,count(p7_test.job_applications.pro) totalapply FROM p7_test.professionals inner join p7_test.job_applications on p7_test.professionals.id= p7_test.job_applications.pro group by p7_test.professionals.full_name; I want to do it in Django REST Framework -
How to use Djoser with multiple extended users?
Hello I am new to django django rest framework and djoser I was just wondering. How do I use djoser with multiple extended users. Below is my model, serializers and views. Model: I am trying to inherit user with the student model and teacher model (as seen below). I want djoser to use these two model to create the users. from django.db import models from django.contrib.auth.models import User from django.conf import settings # Create your models here. class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='student') age = models.IntegerField() address = models.CharField(max_length=200) def __str__(self): return self.user.username class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='teacher') description = models.TextField() def __str__(self): return self.user.username class Course(models.Model): name = models.CharField(max_length=200) description = models.TextField() price = models.FloatField(default=25.00) def __str__(self): return self.name Serializer: My serializer is not finished yet I still have to override the create and update methods. from rest_framework import serializers from api.models import * from django.contrib.auth.models import User class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = ('age', 'address') class StudentUserSerializer(serializers.ModelSerializer): student = StudentSerializer() class Meta: model = User fields = ('id', 'username', 'email', 'password', 'first_name', 'last_name', 'student') extra_kwargs = {'password': {'write_only': True, 'required': True}} class TeacherSerializer(serializers.ModelSerializer): class Meta: model = Teacher fields = … -
Error in Django Channel during WebSocket handshake: Unexpected response code: 500
I was following the this tutorial on youtube. The browser gives an error "(index):21 WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/asas/' failed: Error during WebSocket handshake: Unexpected response code: 500 (anonymous) @ (index):21" Code: chatroom.html <script> const roomName = JSON.parse(document.getElementById('room-name').textContent); const chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/' + roomName + '/' ); chatSocket.onmessage = function (e) { const data = JSON.parse(e.data); console.log(data) document.querySelector("#user-hello").innerHTML = (data.tester) } </script> chat/routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatRoomConsumer), ] chat/comsumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() await self.channel_layer.group_send( self.room_group_name, { 'type': 'tester_message', 'tester': 'Hello World', } ) async def tester_message(self, event): tester = event['tester'] await self.send(text_data = json.dumps({ 'tester':tester })) async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) settings.py STATIC_URL = '/static/' ASGI_APPLICATION = "core.routing.application" CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer" } } -
heroku procfile problem : ModuleNotFoundError: No module named 'myApp.wsgi'
I' m deploying my first django app on heroku. After deploy the heroku doesn't launch my app. After checking heroku logs --tail I have got an error: : ModuleNotFoundError: No module named 'tabele.wsgi' My procfile looks like: web: gunicorn tabele.wsgi:application --log-file - I tries also: web: gunicorn tabele:app web: gunicorn tabele.wsgi --log-file - I'm beginner and I don't understand if (in my case 'tabele') should be folder containing manage.py or the different one? In my project folders including manage.py and another one including settings.py and wsgi.py has the same name "tabele" Could you explain me what is what in procfile file for better understanding? Any idea what I'm doing wrong? -
Django get all Model Instances that are within 2 hours of timeframe
As a Django beginner I struggle with a very basic problem: Filter a table based on the date difference of two rows. I have the following model: class DataPoint(models.Model): uid = models.CharField(max_length=128) timestamp = models.DateTimeField(auto_now_add=True) and I want to extract data points that have the same UID and are all within the range of e.g. 2 hours. I could of course use something like: DataPoint.objects.filter(uid=uid, timestamp__range=[timezone.now - timedelta(2), timezone.now]) but that would only return everything within the same 2 hour frame from now, but not dynamically given the DataPoint's timestamp. So this data set: (1) DataPoint: 2021-03-07 12:40 (2) DataPoint: 2021-03-07 11:40 (3) DataPoint: 2021-03-07 10:50 (4) DataPoint: 2021-03-07 08:55 would only return (1), (2), (3) with the query above, even though (4) is still considered connected, as it's within a 2h timeframe of (3). Been trying to get this to work with a RECURSIVE RAW SQL, as I thought this was the only way to do it with Django, but it's not working as expected either. WITH RECURSIVE previous AS ( SELECT id, uid_id, timestamp FROM core_datapoints WHERE id = %s UNION ALL SELECT s.id, s.uid_id, s.timestamp FROM core_datapoints s WHERE uid_id = s.uid_id AND (timestamp - INTERVAL '2 … -
Django group by Many to many in models
I have Model like this Class TaskEntry name = date = goals = models.ManyToManyField(Goal, blank=True) I want to get no of tasks done per goal on per day Example ENtry will be like Task1 5 March goals['Goal1', 'Goal2'] Task2 5 March goals['Goal1', 'Goal3'] Task3 5 March goals['Goal2', 'Goal3'] Task5 5 March goals['Goal1', 'Goal7'] I want result like 5 March Goal1 3 5 March Goal2 2 5 March Goal3 2 5 March Goal7 1 -
NoReverseMatch at /article/add/
I've been building my blog in Django and been able to add a list view and an article detail view but my add view isn't working. I have tried every suggestion I saw online. None of them work for me. Here is my add post HTML {% extends "base.html" %} {% load static %} {% block content %} <br> <br> <br> <div class="container" style="margin-top: 2rem; margin-bottom: 2rem;"> x <h1>Add Blog Post</h1> <form action="{% url 'article-detail' post.slug %}" method="POST"> {% csrf_token %} {{form.as_p}} <button type="submit" class="btn btn-primary"> Post </button> </form> </div> {% endblock content %} Here is my urls.py from django.urls import path from .views import ArticleListView, AddPostView, ArticleDetailView urlpatterns = [ path('', ArticleListView.as_view(), name='index'), path('article/add/', AddPostView.as_view(), name='add-post'), path('article/<slug:slug>/', ArticleDetailView.as_view(), name='article-detail'), ] Here are my class based views from django.db import models from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView from .models import Post # Create your views here. class ArticleListView(ListView): model = Post template_name = 'index.html' paginate_by = 3 class AddPostView(CreateView): model = Post template_name = 'add_post.html' fields = '__all__' context_object_name = 'post' class ArticleDetailView(DetailView): model = Post template_name = 'article_detail.html' context_object_name = 'post' -
how to can i insert varients and UOM as ManyToManyField
Hello I am trying to build and e-commerce project using django and vue. Here is my Product Model: class UOM(models.Model): title = models.CharField(max_length=20) def __str__(self): return self.title class Varients(models.Model): title = models.CharField(max_length=120) def __str__(self): return self.title class Product(models.Model): title = models.CharField(max_length=100, null=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) price = models.IntegerField() brand = models.ForeignKey(Brand, null=True, on_delete=models.CASCADE) img = models.ImageField(upload_to="images/", null=True, blank=True) uoms = models.ManyToManyField(UOM, null=True, blank=True, default="Please Enter UOM") varients = models.ManyToManyField(Varients, null=True, blank=True, default="Please Select Varients") description = models.TextField(max_length=350, null=True, blank=True) def __str__(self): return self.title Here i have UOM and vairents model which i took in product as ManyToMany Field. But i dont know how can i add to cart using django and vue.js Though i can only pass these : HEre is my api.py for add to cart : def api_add_to_cart(request): data = json.loads(request.body) jsonresponse = {'success': True} product_id = data['product_id'] update = data['update'] quantity = data['quantity'] cart = Cart(request) product = get_object_or_404(Product, pk=product_id) if not update: cart.add(product=product, quantity=1, updated_quantity=False) else: cart.add(product=product, quantity=quantity, updated_quantity=True) return JsonResponse(jsonresponse) here is add function for adding a product to a cart def add(self, product, quantity=1, updated_quantity=False): product_id = str(product.id) price = product.price if product_id not in self.cart: self.cart[product_id] = {'quantity':0, 'price': price, 'id': product_id} … -
django.contrib.auth.login does not log the user in
I created a custom User model like the following: class User(AbstractBaseUser): class Types(models.TextChoices): CUSTOMER = 'CUSTOMER', 'Customer' SUPPLIER = 'SUPPLIER', 'Supplier' OPERATOR = 'OPERATOR', 'Operator' base_type = Types.CUSTOMER objects = UserManager() phone = models.IntegerField(unique=True) code = models.IntegerField(blank=True, null=True) type = models.CharField(max_length=20, choices=Types.choices, default=base_type) date_joined = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) USERNAME_FIELD = 'phone' REQUIRED_FIELDS = [] class Meta: verbose_name = 'user' verbose_name_plural = 'users' def __str__(self): return str(self.phone) def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin And a manager for the User model: class UserManager(BaseUserManager): def create_user(self, phone, code=663322, password=None): if not phone: raise ValueError('Users must have a phone number') user = self.model( phone=phone, code=code, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, phone, code=663322, password=None): user = self.create_user( phone=phone, code=code, password=password, ) user.is_admin = True user.save(using=self._db) return user I wanted to have 3 different user types (customer, supplier, operator) so I created 3 profile models and having a OneToOneField to the base user model for each profile model (with some specific fields related to the user type). I also created 3 proxy models like so: class Customer(User): objects = CustomerManager() base_type = User.Types.CUSTOMER class Meta: proxy = True class Supplier(User): … -
Django dj-rest-auth registration
I'm using dj-rest-auth registration, which enables to override register serializer and that's what I'm trying to do. Unfortunately I don't know how I am supposed to do that given my models: class CustomUser(AbstractUser): username = models.CharField(max_length=50, unique=True) email = models.CharField(max_length=100, unique=True) date_joined = models.DateTimeField('date joined', default=timezone.now) year = models.IntegerField(blank=True, null=True) university = models.ForeignKey(University, related_name='students', on_delete=models.CASCADE) class RegisterSerializer(serializers.Serializer): username = serializers.CharField( max_length=40, min_length=3, required=True ) email = serializers.EmailField(required=True) password1 = serializers.CharField(write_only=True) password2 = serializers.CharField(write_only=True) year = serializers.IntegerField(required=True, write_only=True) def validate_username(self, username): username = get_adapter().clean_username(username) return username def validate_email(self, email): email = get_adapter().clean_email(email) if allauth_settings.UNIQUE_EMAIL: if email and email_address_exists(email): raise serializers.ValidationError( "A user is already registered with this e-mail address." ) return email def validate_password1(self, password): return get_adapter().clean_password(password) def validate(self, data): if data['password1'] != data['password2']: raise serializers.ValidationError("The two password fields didn't match.") return data def custom_signup(self, request, user): user.year = self.validated_data.get('year', '') user.university = University.objects.filter(name=self.validated_data.get('university', '')) user.save(update_fields=['year']) def get_cleaned_data(self): return { 'username': self.validated_data.get('username', ''), 'password1': self.validated_data.get('password1', ''), 'email': self.validated_data.get('email', ''), 'year': self.validated_data.get('year', '') } def save(self, request): adapter = get_adapter() user = adapter.new_user(request) self.cleaned_data = self.get_cleaned_data() adapter.save_user(request, user, self) self.custom_signup(request, user) setup_user_email(request, user, []) return user My question is how to add my university foreign key to a register serializer, to enable … -
Rename the default django table
Rename the default django table. I can't change the default table name django_sessions Could anyone help? Thanks for listening model.py from django.contrib.sessions.models import Session Session._meta.db_table = "my_session" -
Exception Value: Field 'id' expected a number but got ''
(I searched this error on stackoverflow and tried the solution ideas bu they did not work.) In my Django Project, I tried to add a like button into my article detail page. If users like the article they click the like button and return the same article page. I saw this video on Youtube and wrote the same code by changing name of the some values according to my project. But I encountered an error which says Field 'id' expected a number but got ''. I read some solutions on Stackoverflow and tried to delete migrations files (except init.py) and then I wrote python manage.py makemigrations and then python manage.py migrate. Unfortunately , it did not work. I want to share my code so maybe, I hope, you can give me some solution ideas. model.py class Article(models.Model): author = models.ForeignKey("auth.User", on_delete = models.CASCADE, verbose_name="Kullanıcı") title = models.CharField(max_length = 50, verbose_name="Başlık") content = RichTextField() created_date = models.DateTimeField(auto_now_add = True, verbose_name="Oluşturma Tarihi") likes = models.ManyToManyField(User, related_name='blog_post') urls.py urlpatterns = [ path('dashboard/',views.dashboard, name ="dashboard"), path('addarticle/',views.addarticle, name ="addarticle"), path('article/<int:id>',views.detail, name ="detail"), path('update/<int:id>',views.updateArticle, name ="update"), path('delete/<int:id>',views.deleteArticle, name ="delete"), path('',views.articles, name ="articles"), path('comment/<int:id>',views.addComment, name ="comment"), path('like/<int:id>',views.LikeView, name ="like_post"), ] views.py def LikeView(request, id): post = get_object_or_404(Article, … -
Django web page opening but not loading in browser
I am using Visual Studio Code for coding python using django framework. But when I open the http://127.0.0.1:8000/ on my browser it always shows waiting for 127.0.0.1:8000 but he page never loads -
.map is not a function reactjs
So I'm following this tutorial, https://www.udemy.com/course/django-with-react-an-ecommerce-website/, but with some custom HTML template that I made. I keep getting the error .map() is not defined. As the udemy course is more so for Django developers, I am a little lost of the react side. Below is my HomeScreen.js page that is supposed to display products. import React from 'react'; import products from '../products' function HomeScreen() { return ( <section class = "w3l-ecommerce-main"> <div class = "ecom-contenthny py-5"> <div class = "container py-lg-5"> <h3 class = "hny-title mb-0 text-center">Shop With<span>Us</span></h3> <p class = "text-center">Handpicked Favourites just for you</p> <div class = "ecom-products-grids row mt-lg-5 mt-3"> { products.map(products => ( <div key = {products._id} class = "col-lg-3 col-6 product-incfhny mt-4"> <div class = "product-grid2 transmitv"> <div class = "product-image2"> <a href = "#"> <img class = "pic-1 img-fluid" src = "/images/shop-1.jpg"/> <img class = "pic-2 img-fluid" src = "/images/shop-11.jpg"/> </a> <ul class = "social"> <li><a href = "#" data-tip = "Quick View"> <span class = "fa fa-eye"></span></a></li> <li><a href = "#" data-tip = "Add to Cart"><span class = "fa fa-shooping-bag"></span></a></li> </ul> <div class = "transmitv single-item"> <form action="#" method = "post"> <input type="hidden" name="cmd" value="_cart"> </input> <input type="hidden" name="add" value="1"> </input> <input type="hidden" …