Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
calling external API results in alert messages
I havwe a fine working script, that behaves odly: def get_info(self, env, limit = None): token = self.get_token()["access_token"] if limit == None: url = f"""{env}infos""" else: url = f"""{env}infos?limit={limit}""" payload = {} headers = {"Authorization": f"""Bearer {token}"""} response = requests.request("GET", url, headers = headers, data = payload) if response.status_code != 200: return False return json.loads(response.text) There is a simple view returning the data to the frontend: class TheView(TemplateView): template_name = "apihlp/index.html" def get_context_data(self, *args, **kwargs): context = super().get_context_data(**kwargs) data = get_data() context.update({"data": data}) return context with get_data looking like this: def get_data(): infos = get_infos("some_url", limit = 20) ORGADATA = [] counter = 0 for info in infos: name = f"""<h3 style="color:green">{counter}: {info["organization"]}</h3>""" try: owners = "".join([f"""<li>{info["mail"]}""" for info in infos["owner"]]) except: owners = "" ORGADATAHTML = f"{name}<h4>owners:</h4>{owners} ORGADATA.append({"counter": counter, "id": info["id"], "name": info["organization"], "HTML": ORGADATAHTML}) html part is even simpler: {% for item in data %} {{ item.HTML|safe }} {% endfor %} I know from doing the same call in postman, I can receive 50+ objects. When I set limit to 10 or 20 everyhing works fine (works fine in Postman with set to 10000 as well ...). But in Django I get: [![enter image description here][1]][1] and after … -
How to use count() in serializers?
I am trying to get count of article likes,but the problem is that i am facing with various errors. Here is my code: class ArticleLikeSerializer(serializers.ModelSerializer): class Meta: model = ArticleLike fields = ('id',"author","article",'timestamp') class ArticleSerializer(serializers.ModelSerializer): articlelikes_set = ArticleLikeSerializer(source='articlelikes',required=False,many=True) total_likes = serializers.SerializerMethodField(read_only=True) class Meta: model = Article fields = ('id','author','caption','total_likes','articlelikes_set') def get_total_likes(self, language): return articlelikes_set.count() Here is my error: name 'articlelikes_set' is not defined How can i solve the problem? -
python: dynamic keys in nested dictionary
i am using the django shell to try to create such a dictionary: {'SECTION ONE': {'Category One': [<Price: price element one>], 'Category Two': [<Price: price element one>, <Price: price element two>]}, 'SECTION TWO': {'Category One': [<Price: price element one>, <Price: price element two>]}} but this pieces of code: dict[section][category] = [x] change the "price element one" in "two" like the result below. dict = dict() for x in price.objects.all(): if section not in dict: dict[section] = { category: [x] } else: dict[section][category] = [x] dict[section][category].append(x) {'SECTION ONE': {'Category One': [<Price: price element two>], 'Category Two': [<Price: price element two>, <Price: price element two>]}, 'SECTION TWO': {'Category One': [<Price: price element two>, <Price: price element two>]}} how can you keep all the elements? -
How to share localhost port over local network
I created webpage on local server with django framework (python). I have acces to it under address http://localhost:8000/. Now I want to share it over local network. I try to do it with Windows firewall Inbound/outbound rules, but it seems either I do something wrong or it's not enough. -
Add filter Comment in Django
I have a problem with adding comments only spaces or enters. I don't know how filter that. If the user sends a normal comment it is transferred to the current page but if send only spaces or enters it is transferred to the URL comment. This my is code: models.py class Post(models.Model): """Post Model""" hash = models.UUIDField(default=uuid.uuid4, editable=False) title = models.CharField("Title", max_length=200) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey( settings.AUTH_USER_MODEL, related_name="created_by", on_delete=models.CASCADE, default=current_user.CurrentUserMiddleware.get_current_user, ) category = TreeForeignKey(Category, verbose_name="Category", related_name="items", on_delete=models.CASCADE) tags = TaggableManager() image = models.ImageField("Image", upload_to=get_timestamp_path) content = RichTextUploadingField() create_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.title}" def get_absolute_url(self): return reverse("main:post_detail", args=[self.slug]) def save(self, *args, **kwargs): if str(self.hash) not in self.slug: self.slug = f"{self.slug}-{self.hash}" super().save(*args, **kwargs) def get_comment(self): return self.comment_set.all() class Comment(models.Model): user = models.ForeignKey(User, verbose_name="User", on_delete=models.CASCADE) post = models.ForeignKey(Post, verbose_name="Post", on_delete=models.CASCADE) text = models.TextField(verbose_name="Comment") create_at = models.DateTimeField("Date of creating", auto_now=True) class Meta: verbose_name = "Comment" verbose_name_plural = "Comments" def __str__(self): return str(self.user) views.py class PostDetail(DetailView, MultipleObjectMixin): model = Post context_object_name = 'post' paginate_by = 10 template_name = 'main/post_detail.html' def get_context_data(self, **kwargs): comments = Comment.objects.filter(post=self.get_object()) context = super(PostDetail, self).get_context_data(object_list=comments, **kwargs) return context class AddComment(LoginRequiredMixin, CreateView): """Add Comment""" model = Post form_class = CommentForm def form_valid(self, form): form.instance.user = self.request.user form.instance.post_id … -
I want to make a simple face detection program with opencv and django
I found out how to get the webcam going in django and how to detect faces but i cant seem to find out how to combine both , any help would be appreciated face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') def home(request): context = {} return render(request, "home.html", context) class VideoCamera(object): def __init__(self): self.video = cv2.VideoCapture(0) (self.grabbed, self.frame) = self.video.read() threading.Thread(target=self.update, args=()).start() def __del__(self): self.video.release() def get_frame(self): image = self.frame _, jpeg = cv2.imencode('.jpg', image) return jpeg.tobytes() def update(self): while True: (self.grabbed, self.frame) = self.video.read() def gen(camera): while True: frame = camera.get_frame() yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') def detection(camera): while True: _, img = gen(camera) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.1, 4) for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2) k = cv2.waitKey(30) & 0xff if k==27: break return img this is how i tried to combine both @gzip.gzip_page def detectme(request): cam = VideoCamera() return StreamingHttpResponse(detect(cam), content_type="multipart/x-mixed- replace;boundary=frame") this is the home.html incase i messed something up in there {% load static %} {%load widget_tweaks %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>DJAGO_OPENCV</title> </head> <body> {% block body %} <h1></h1> <table> <tr> <td width="50%"> <img src="http://127.0.0.1:8000/detectme" style="width:1200px;" /> </td> <td width="50%"> … -
Django: count every same value in a object.filter
I have a CourseEmailPersonEven model that has this: class CourseEmailPersonEvent(models.Model): uid = models.UUIDField(primary_key=True, default=uuid.uuid4) action = models.CharField(max_length=32) is_filtered = models.BooleanField(default=False) user_agent = models.CharField(max_length=255, null=True, blank=True) ip = models.GenericIPAddressField(null=True, blank=True) ip_address = models.ForeignKey(Ip, on_delete=models.SET_NULL, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) course_email_person = models.ForeignKey( CourseEmailPerson, related_name="events", on_delete=models.CASCADE ) In a viewset (retrieve), i'm getting CourseEmailPersonEvent's informations about one single account. But I wanna add the amount of same "ip_address" used from every accounts (even mine). And I don't know what to do: class UtilsViewSet(viewsets.ViewSet): @action(detail=False, methods=["get"], url_path="emails/events/ips") def emails_events_ip(self, request, *args, **kwargs): account = get_object_or_404(models.Account, uid=self.kwargs["account_pk"]) ips_events_count = ( models.CourseEmailPersonEvent.objects.filter( course_email_person__account=account, action="open", ip_address__isnull=False, ) .values("ip_address") .annotate(Count("ip_address")) .order_by("-ip_address__count") )............ Here the result I wanna have in final: (to add that "ip_address_used_all_account" line) [ { "ip_address": "4ead446d-28c5-4641-b44d-f1e3aa7d26f8", "ip_address__count": 1, "ip_address_used_all_account: 2, "is_filtered": false, "ip": "80.150.22.32", "country_code": "FR", "asn": "4b2698b3-bf86-4674-8d69-f4a038a8200a", "asn_name": "FREE SAS" } ] -
Show list of related objects in Django
I have an issue with displaying list of related articles in my Q&A DetailView. I have a field where user can connect an article to Q&A from admin site. What I want is to display these related article models.py class QA(models.Model): id = models.AutoField(primary_key=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL) #settings INSTALLED_APPS title = models.CharField(max_length=750) category = models.ForeignKey(Category, on_delete = models.CASCADE, blank=True) related_articles = models.ManyToManyField(Article, default=None, blank=True, related_name='related_article') slug = models.SlugField(unique=True, blank=True) class Article(models.Model): id = models.AutoField(primary_key=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL) #settings INSTALLED_APPS title = models.CharField(max_length=200) category = models.ForeignKey(Category, on_delete = models.CASCADE, blank=True) slug = models.SlugField(unique=True, blank=True) views.py class QADetailView(LoginRequiredMixin, DetailView): login_url = 'login' redirect_field_name = 'login' template_name = 'QADetailView.html' model = QA def get_context_data(self, **kwargs): categories = Category.objects.all() related_articles = Article.objects.filter(related_article=self.kwargs['id']) #No idea what to put in filter context['related_article'] = related_articles context['categories'] = categories return context QADetailView.html {% for article in related_article %} {{article.title}} {% endfor %} -
Saving dropdown menu selection as a cookie in Django
I'd like to save a user selection from a dropdown menu as a cookie. I've seen this question asked before but never fully in python. I wish to use these two cookies in running a simple piece of code so there is no need for a database to be used. Here is my current HTML code: <form role="form" method="post"> {% csrf_token %} <div class="form-group"> <label for="dog-names">Choose a dog name:</label> <select name="dog-names" id="dog-names" onchange="getSelectValue"> <option value="rigatoni">Rigatoni</option> <option value="dave">Dave</option> <option value="pumpernickel">Pumpernickel</option> <option value="reeses">Reeses</option> <option value="{{ current_name }}"> {{ current_name }}</option> </select> <br/> <label>Current dog: {{ current_name }}</label> </div> <button type="submit" value="Submit" class="btn btn-info">Submit</button> </form> Python def cookies_test(request): template_name = 'cookies.html' current_name = "Rigatoni" # default name if request.method == 'GET': if 'name' in request.COOKIES: current_name = request.COOKIES['name'] elif request.method == 'POST': current_name = request.POST.get('name') response = render(request, 'test.html', { "current_name": current_name }) response.set_cookie('name', current_name) return response The python works if I give a value to {{ current_name }} All I want is to be able to save a value from a dropdown menu in a variable so I can save it as a cookie Any advice at all would be appreciated :) -
Is there a more faster and efficient ways to send email in django so that the user does not have to wait the entire time the page loads
I am making a website where a user registers to book an instructor for a certain period of time according to a plan he chooses. There are three plans from which a user can choose namely 7days, 14days and 21days. After registering, the user needs to accept an agreement and then based on the plan he has chooses an expiration date is set from the day the user has accepted the agreement. Now after the user, has accepted the agreement, a copy of the agreement is sent to the user as well as the owners of the website through email. The owners want this system, where the copy of agreement is recieved by both the user and them. I am able to make this happen, and the site is working fine in the testing phase. So basically, two emails are sent after the user accepts and a Contract model is updated. Now, I have noticed that sending two emails takes a good of time, and the page keeps on loading until both the emails are sent, and then the redirects and all happens for the user. This waiting time may trigger some users to press back interrupting the smtp connection, … -
I want to created a rsa key put want to return single key at a time for models
def Create_Keys(): publicKey, privateKey = rsa.newkeys(512) For Models PublicKey = models.CharField(max_length=1000, blank=True, default=#From Function create Keys publicKey) PrivateKey = models.CharField(max_length=1500, blank=True, default=#From Function create Keys privateKey) To make Like this hidden_url = models.CharField(max_length=20, blank=True, default=utlis.create_random_codes()) -
DeleteView - confirm by Popup windows
I want to ask you, if you know, is here some point or solution how to do confirm delete item with DeleteView class by Popup bootstrap window. So I will not use template_name, but popup windows on current page. Thank you so much for everything...!!! -
Push rejected failed to compile python app
so i get this error when i try to deploy my master branch, i have set my requirements.txt, runtime.txt and Procfile but i still get this error -----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> Python app detected -----> Using Python version specified in runtime.txt ! Requested runtime (python - 3.9.7) is not available for this stack (heroku-20). ! Aborting. More info: https://devcenter.heroku.com/articles/python-support ! Push rejected, failed to compile Python app. ! Push failed my requirements.txt file asgiref==3.4.1 dj-database-url==0.5.0 Django==3.2.7 django-heroku==0.3.1 gunicorn==20.1.0 Pillow==8.4.0 psycopg2==2.9.2 python-decouple==3.5 pytz==2021.3 sqlparse==0.4.2 whitenoise==5.3.0 please help -
Using pymongo but still getting improperly configured database error
Having read through a lot of posts on the following error, I have understood that if you connect to your MongoDB database via pymongo, you should remove the DATABASES section in your settings.py file: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. I have removed it, but I still get this error. Nonetheless, I have tried the suggestions in related posts, to no avail... In my settings.py file, I have my database connection: DB_NAME = 'mongodb+srv://User2021:TestMe@cluster0.j9jz1.mongodb.net/test' In my views.py file, I have written a simple method, just to start off: @csrf_exempt def consumers(request): data = ConsumerModel.objects.all() if request.method == 'GET': print("consumers") serializer = ConsumerModelSerializer(data, many=True) return JsonResponse(serializer.data, safe=False) When I enter the http://localhost:8000/consumers/, I just wanna see that the python print statement writes consumers. What am I missing? -
unable to install MYSQLDB
sudo pip install MySQL-python Collecting MySQL-python Using cached MySQL-python-1.2.5.zip (108 kB) ERROR: Command errored out with exit status 1: command: /usr/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-4dq45q4u/MySQL-python/setup.py'"'"'; file='"'"'/tmp/pip-install-4dq45q4u/MySQL-python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-4dq45q4u/MySQL-python/pip-egg-info cwd: /tmp/pip-install-4dq45q4u/MySQL-python/ Complete output (7 lines): Traceback (most recent call last): File "", line 1, in File "/tmp/pip-install-4dq45q4u/MySQL-python/setup.py", line 13, in from setup_posix import get_config File "/tmp/pip-install-4dq45q4u/MySQL-python/setup_posix.py", line 2, in from ConfigParser import SafeConfigParser ModuleNotFoundError: No module named 'ConfigParser' ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. neosoft@neosoft:~$ ^C -
Django admin missing models in one enviroment but not in other?
We have a weird problem with our development right now. Two of us are developing a softare using django. In my enviroment, I have full admin page with all the models and management options we have added. On our deployed test server, both me and him have the same options. However, on his own local server, running the exact same codebase that I do, these options are missing and he can only see handful of options. Any idea what might be causing this? It is making testing difficult. -
DRF:user registration serializer for proxy models with nested serializers
i have a User model that inherits from AbstractBaseUser and also a proxy model that inherits from the User model with extended fields and a manager what I want to do is serialize and validate both the User model and the proxy model at the same time with nested serializers: ##manager for the user model class CustomAccountManager(BaseUserManager): def create_superuser(self, email, firstname, lastname, password, **other_fields): .... ##user model class User(AbstractBaseUser, PermissionsMixin): class TYPES(models.TextChoices): OWNER = "OWNER", "Owner" OTHERUSER = "OTHERUSER", "other user" ##user types base_type = TYPES.STUDENT type = models.CharField( _("User Type"), max_length=50, choices=TYPES.choices, default=base_type) email = models.EmailField( _("Your Email"), max_length=254, unique=True, blank=False, null=True) firstname = models.CharField(max_length=150, blank=False, null=True) lastname = models.CharField(max_length=150, blank=False, null=True) joined_date = models.DateTimeField( _("created date"), auto_now=True, auto_now_add=False) is_superuser = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) last_login = models.DateTimeField( _("last login"), auto_now=True, auto_now_add=False) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['firstname', 'lastname'] def __str__(self): return self.firstname # owner model manager class OwnerManager(models.Manager): def get_queryset(self, *args, **kwargs): return super().get_queryset(*args, *kwargs).filter(type=User.TYPES.OWNER) class OwnerMore(models.Model): user = models.OneToOneField( User, on_delete=models.CASCADE, blank=False, null=True) #extra fields dedicated to this user type class Owner(User): base_type = User.TYPES.OWNER objects = OwnerManager() @property def extra(self): return self.OwnerMore class Meta: proxy = True this is my … -
Django forms passed instance object gets overridden in is_valid
I was working on a Django view that updates the a certain model object x. In POST method, I initiate a ModelForm and pass an instance of the model object x. But when I try to use x object inside if form.is_valid(): block, some values in vars(x) go None. Here's the snippet to explain the scenario. class MyUpdateView(generic.View): form_class = MyModelForm def post(self, request, *args, **kwargs): model_obj = MyModel.objects.get(id=kwargs.get("pk")) # Example: {"emp": 113, "project": 22, "salary": 28000} form = self.form_class(request.POST, instance=model_obj) print(vars(model_obj)) # works fine, shows all the data if form.is_valid(): print(vars(model_obj)) # few values go None, not reusable # Example: {"emp": None, "project": None, "salary": 28000} As we can see, when the vars checked inside the form.is_valid(), something happens to the passed instance object. What could be possibly reason behind this? -
How do I validate Azure AD token?
I have a DJANGO API and wanted to set up API authentication. How do I verify the API token? -
how can i prevent duplicate signals? am having a user being assigned to both 'client' and 'worker' instead of one group respectively
What could i be doing wrong, the code is executing two times. instead of loading the user to his specific group from django.db.models.signals import post_save from django.contrib.auth.models import User from django.contrib.auth.models import Group from .models import Client, Worker def client_profile(sender, instance, created, **kwargs): if created: group = Group.objects.get(name='client') instance.groups.add(group) Client.objects.create( user=instance, name=instance.username, ) print('Profile created!') post_save.connect(client_profile, sender=User, dispatch_uid="client_profile") def worker_profile(sender, instance, created, **kwargs): if created: group = Group.objects.get(name='worker') instance.groups.add(group) Worker.objects.create( user=instance, name=instance.username, ) print('Profile created!') post_save.connect(worker_profile, sender=User, dispatch_uid="worker_profile") -
unable to create superuser in django getting error "django.db.utils.OperationalError: no such table: auth_user"
I am unable to create superuser in django. Things I have done till now: Created Django Project Created Django App Went to settings.py added the app name in installed apps list Successfully able to runsever Tried creating a superuser using the command python manage.py createsuperuser Error received : django.db.utils.OperationalError: no such table: auth_user It would be very nice if someone could instruct me how to fix it. -
"Invalid block tag on line 3: 'providers_media_js', Did you forget to register or load this tag?"
"Invalid block tag on line 3: 'providers_media_js', Did you forget to register or load this tag?" why this is happening. What modification should I do to solve this {% load static %} {% load socialaccount % } {% providers_media_js %} <!DOCTYPE html> <html> <head> <title>Creative Colorlib SignUp Form</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script> <!-- Custom Theme files --> <link href="{% static 'login.css'%}" rel="stylesheet" type="text/css" media="all" /> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <!-- //Custom Theme files --> <!-- web font --> <link href="//fonts.googleapis.com/css?family=Roboto:300,300i,400,400i,700,700i" rel="stylesheet"> <!-- //web font --> </head> <body> <div class="login-page"> <div class="form" text-align="center"> {% for message in messages %} <div class="alert {{ message.tags }} alert-dismissible" role="alert"> {{ message }} </div> {% endfor %} <form class="login-form" action="" method="post"> {% csrf_token %} <input type="text" name="userid" placeholder="id" required="" /> <input type="password" name="password" placeholder="password" required="" /> <button action="" type='submit'>Login</button> <p class="message">Not registered? <a href="{% url 'signup' %}">Create an account</a></p> <p> or sign in with</p> <button> <a style="color:#fff;text-decoration:none;" href="{% provider_login_url "google" %}">Google Login </a></button> <button> <a style="color:#fff;text-decoration:none;" href="#">Facebook Login </a></button> </form> </div> <script src="{% static 'login.js'%}"></script> </div> </body> </html> help me find the solution -
Heroku Django Login Routing
I am trying to make sure my url.com go straight to a login page and then route around properly. The issue is Trying to follow https://learndjango.com/tutorials/django-login-and-logout-tutorial but trying to make it into a dedicated pages app which I am unsure of. url.com -> should display login.html which is extended from base.html if user isn't signed in pages/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] Think I need to change path here to something for base.html pages/views.py from django.shortcuts import render def index(request): return render(request,'registration/login.html') So these two make up how to request the login.html from the url. settings.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! import os SECRET_KEY = os.getenv("SECRET_KEY", default="dev key") # SECURITY WARNING: don't run with debug turned on in production! DEBUG = os.environ.get('DJANGO_DEBUG', '') ALLOWED_HOSTS = ["url.com"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages.apps.PagesConfig', ] MIDDLEWARE = [ '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 = 'portfolio.urls' TEMPLATES … -
django API views 404 not found
I am having trouble figuring this out. I can access http://127.0.0.1:8000/api/ But this returns 404 not found: http://127.0.0.1:8000/api/projects I have been looking at the codes and couldn't find any errors. the terminal also showing this upon runserver: Not Found: /api/projects/ What could be the problem? urls.py from django.urls import path from . import views urlpatterns = [ path('', views.getRoutes), path('projects/', views.getProjects), path('project/<str:pk>/', views.getProjects), ] views.py from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated, IsAdminUser from rest_framework.response import Response from .serializers import ProjectSerializer from projects.models import Project @api_view(['GET']) def getRoutes(request): routes = [ {'GET': '/api/projects'}, {'GET': '/api/projects/id'}, {'POST': '/api/projects/id/vote'}, {'POST': '/api/users/token'}, {'POST': '/api/users/token/refresh'}, ] return Response(routes) @api_view(['GET']) def getProjects(request): projects = Project.objects.all() serializer = ProjectSerializer(projects, many=True) return Response(serializer.data) The 404 error page showing this: Using the URLconf defined in djangoProject1.urls, Django tried these URL patterns, in this order: admin/ projects/ login/ [name='login'] logout/ [name='logout'] register/ [name='register'] [name='profiles'] profile/<str:pk> [name='user-profile'] account/ [name='account'] edit-account/ [name='edit-account'] create-skill/ [name='create-skill'] update-skill/<str:pk>/ [name='update-skill'] delete-skill/<str:pk>/ [name='delete-skill'] inbox/ [name='inbox'] message/<str:pk>/ [name='message'] create-message/<str:pk>/ [name='create-message'] api api projects/ api project/<str:pk>/ reset_password/ [name='reset_password'] reset_password_sent/ [name='password_reset_done'] reset/<uidb64>/<token>/ [name='password_reset_confirm'] reset_password_complete/ [name='password_reset_complete'] ^images/(?P<path>.*)$ ^static/(?P<path>.*)$ The current path, api/projects/, didn’t match any of these. -
django tuple has no attribute get
i am trying to restrict the dropdown options according to the user type withinf the same form i.e usertype a has certain dropdown options and usertype b has certain dropdown options i tried to write my logic as below but am getting error as tuple has no attribute get forms.py class EditForm(forms.ModelForm): class Meta: model = Model fields = ('title', 'info','status') def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super().__init__(args, **kwargs) if self.user.is_usertypeA == True: self.fields['status'].choices = ( ('C','C'), ) else: self.fields['status'].choices = ( ('A','A'), ('b','b'), ) models.py class EditView(LoginRequiredMixin,UpdateView): template_name = 'edit.html' model = model form_class = EditForm context_object_name = '' success_url = reverse_lazy('') def get_form_kwargs(self): kwargs = super().get_form_kwargs() kwargs['user'] = self.request.user return kwargs def form_valid(self,form): [![Error looks as this][1]][1] error trace back Internal Server Error: /app/dev/ticket/complete/39 Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/handlers/base.py", line 204, in _get_response response = response.render() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/template/response.py", line 105, in render self.content = self.rendered_content File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/template/response.py", line 83, in rendered_content return template.render(context, self._request) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/template/base.py", line 170, in render return self._render(context) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/template/base.py", line 162, in _render return self.nodelist.render(context) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/template/base.py", line 938, in render bit = …