Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use model current object in django model form
I want to create queryset from current curriculum that pass from View. This is my form: class MyForm(ModelForm): valid_students = Enrollment.objects.filter(curriculum=self.curriculum) students = forms.ModelMultipleChoiceField(queryset=valid_students) class Meta: model = ArgumentGroup fields = ( 'title', 'curriculum', 'teacher_assistant', 'students', ) How can I get students that have specific curriculum that pass from the view? -
What is best practice to make website in container? How to start with developing Django+postgres app using containers?
I am new in container based application. I want to make a simple django based website. I have installed minishift and sample django+postgres template to start with.After making changes in this sample application and finsh with development on website. I am planning to use the same application and migrate entire application to google cloud or azure after development to make it live? PS: I want to learn end to end container based applications, (e.g. openshift). Now the question is: is this a good approach to build a new website or there is any other best practice? -
Error 5 Access denied on IIS (python.exe)
I have a project in Python 2.7.10/Django 1.8.5 this portal use a function that create a directory and store images and video in this directory I use this portal with IIS 7.5 but when this function is used gives me this error: WindowsError at /somedir/0001/ [Error 5] Acceso denegado: u'D:\\directory\\data\\something\\01' Request Method: POST Request URL: http://localhost:8001/somedir/0001/ Django Version: 1.8.5 Exception Type: WindowsError Exception Value: [Error 5] Acceso denegado: u'D:\\directory\\data\\something\\01' Exception Location: C:\Python27\lib\os.py in makedirs, line 157 Python Executable: C:\Python27\python.exe Python Version: 2.7.10 Python Path: ['.', 'C:\\inetpub\\wwwroot\\miproyect', 'C:\\Windows\\system32\\python27.zip', 'C:\\Python27\\DLLs', 'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', 'C:\\Python27', 'C:\\Python27\\lib\\site-packages'] I tried give all the permissions to the users/groups IUSR/IIS_IUSR on the directory and the python.exe but gives the same error. Thanks in advance for any help. -
Is it possible to use Django-Filter for a ManyToMany relationship?
Essentially, I've been using Django-Filter to filter a large list of publications on various fields. One field is keywords, which has a many to many relationship through a PublicationKeywords table. The models look as follows (withholding certain fields and information): class Publication(models.Model): keywords = models.ManyToManyField(Keyword, through='PublicationKeywords') class Keyword(models.Model): value = models.CharField(max_length=100) class PublicationKeywords(models.Model): keyword = models.ForeignKey(Keyword, db_column='keyword_id', on_delete=models.SET_NULL, null=True) publication = models.ForeignKey(Publication, db_column='publication_id', on_delete=models.SET_NULL, null=True) So, I'm wondering if it's at all possible to use a ModelChoiceFilter in this case to do something similar to PublicationKeywords.objects.filter(keyword__value_in=keyword_list).distinct('publication') Basic filter set up looks as follows class PublicationFilter(django_filters.FilterSet): title = django_filters.CharFilter(lookup_expr='icontains') state = django_filters.ChoiceFilter( choices=STATE_CHOICES) sac = django_filters.ModelChoiceFilter(queryset=Sac.objects.all()) published_date_after = DateFilter( field_name='published_date', lookup_expr=('gte')) published_date_before = DateFilter( field_name='published_date', lookup_expr=('lte')) data_begin_year = django_filters.NumberFilter( lookup_expr='gte') data_end_year = django_filters.NumberFilter( lookup_expr='lte') keywords = django_filters.ModelChoiceFilter(queryset=??????) # TODO figure out how to get this keywords filter to work like # PublicationKeywords.objects.filter(keyword__value_in=keyword_list).distinct('publication') class Meta: model = Publication strict = False fields = ['title', 'state', 'sac', 'published_date', 'data_begin_year', 'data_end_year', 'keywords'] def __init__(self, *args, **kwargs): super(PublicationFilter, self).__init__(*args, **kwargs) if self.data == {}: self.queryset = self.queryset.none() -
resets error during normal import on python django
I have an import error. I have a User model on models.py, I import it on serializer.py. Previously, everything worked as it should, I even worked with other files and suddenly an error appears on serializer.py. And sorry for my English writing via google translate. models.py class User(AbstractBaseUser, PermissionsMixin): phone_number = models.CharField('телефон номер', max_length=20, unique=True,db_index=True) avatar = models.ImageField('Аватар', blank=True, null=True, upload_to=get_timestamp_path, default='images/user.png') nickname = models.CharField('Никнейм', max_length=40, null=True, blank=True) register_date = models.DateField('Дата регистрация', auto_now_add=True) is_active = models.BooleanField('Активен', default=True) is_admin = models.BooleanField('Суперпользователь', default=False) region = models.ForeignKey(Region, verbose_name="", on_delete=models.CASCADE, null=True, blank=True) def save(self, *args, **kwargs): super(User, self).save(*args, **kwargs) self.nickname = 'User' + str(self.id) super(User, self).save(*args, **kwargs) def get_full_name(self): return self.phone_number def is_staff(self): return self.is_admin def get_short_name(self): return self.phone_number def __str__(self): return self.phone_number USERNAME_FIELD = 'phone_number' REQUIRED_FIELDS = [] objects = UserManager() class Meta: verbose_name= 'User' verbose_name_plural = 'Users' serializer.py from rest_framework import serializers from .models import User error File "/home/c2dent/afmoon/backend/afmoon/main/models.py", line 7, in <module> from .utilities import get_timestamp_path File "/home/c2dent/afmoon/backend/afmoon/main/utilities.py", line 8, in <module> from .serializers import HouseSerializer, LandSerialzier, VacancySerializer, ResumeSerializer, SecondSerializer, PersonalsClothesSerializer, PersonalsShoesSerializeres, CommonProductDetail, AvtomobilSerialzier, ApartmentSerializer File "/home/c2dent/afmoon/backend/afmoon/main/serializers.py", line 2, in <module> from .models import User, BaseProduct, Avtomobil, Apartment, House, Land, Vacancy, Resume, Second, Personals_clothes, Personals_shoes ImportError: cannot import name 'User -
takes exactly 2 arguments (1 given)
It is views def hi(request,hh_id): return HttpResponse(hh_id) it is local urls urlpatterns = [ url('<int:hh_id>',views.hi) ] 1.i create a django project but it appears 2.what can i do now ? -
django-channels nginx settings
My django app uses django-channels. I was able to configure django to run using gunicorn and nginx. The app run if i use python manage.py runserver and redis-server sends notification etc but i am unable to configure it using nginx. server { listen 80; server_name 159.65.160.71; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/amir/clientcode; } location / { include proxy_params; proxy_pass http://unix:/home/amir/clientcode/adminpanel.sock; } } However when I try to configure it for django-channels it is giving me status 502 upstream channels-backend { server localhost:8000; } server { listen 80; server_name 159.65.160.71; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/amir/clientcode; } location / { try_files $uri @proxy_to_app; include proxy_params; proxy_pass http://unix:/home/amir/clientcode/adminpanel.sock; } location @proxy_to_app { proxy_pass http://channels-backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } My asgi.py file import os import django from channels.routing import get_default_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "adminpanel.settings") django.setup() application = get_default_application() `` -
how to define global queryset object which i can use in my django views
I want to define global variable which stores data from database table. I need that data in every view functions defined. I dont want to fire a query every time when my function calls. I am using django framework for this. Any suggestion on this how can i optimize this solution? Thanks!! -
How can I display my comment form on the post detail page Django
So basically at the moment, if users want to add a comment to a post on my site, it takes them to another page with the form on it. However, I want the comment form to be on the actual Post Detail page, so users don't have to go to another page to comment. So far I have tried adding some context things and changed the url for the comment form's location to post_detail.html, and put the comment_form.html's code there, however this did not work. Here are the relevant views.py The add_comment_to_post view @login_required(login_url='/mainapp/user_login/') def add_comment_to_post(request,pk): post = get_object_or_404(Post,pk=pk) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.author = request.user # add this line comment.save() return redirect('mainapp:post_detail',pk=post.pk) # remove `def form_valid` else: form = CommentForm() return render(request,'mainapp/comment_form.html',{'form':form}) Here is the PostDetailView view. class PostDetailView(DetailView): model = Post Here is the comment_form.html code <form class="post-form" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="submitbtn">Comment</button> </form> And here is the relevant urls.py files path('post/<int:pk>/comment/', views.add_comment_to_post, name='add_comment_to_post'), path('post/<int:pk>', views.PostDetailView.as_view(), name='post_detail'), So at the moment, when doing my solutions I thought would work, I added the comment_form.html's code into the post_detail.html document, however it only showed … -
Django Templates - Check and Uncheck Checkbox
I have a django Task with a todo list inside it, this is a list of strings and checkboxes. When I tap a checkbox it changes value but doesn't send it to the model via a POST request. What I want to do is create two views, one that makes the value in the model Checker to 'True' and one that makes it 'False'. These are my Task and Checkbox Models: class Task(models.Model): name = models.CharField(max_length=150) description = models.CharField(max_length=1000) state = models.CharField(max_length=15) deadline = models.DateField(default=date.today) workers = models.ManyToManyField(UserProfile, blank=True, related_name="task") stickers = models.ManyToManyField(Sticker, blank=True, related_name="task") checkers = models.ManyToManyField(Checker, blank=True, related_name="task") files = models.ManyToManyField(File, blank=True, null=True) class Checker(models.Model): name = models.CharField(max_length=100) checked = models.BooleanField(default=False) This is the view To create a checkbox: @login_required def create_checker(request, task_id): if request.method == 'POST': name = request.POST.get('Checker-Name') userprofile = UserProfile(id=request.user.id) checker = Checker(name=name, sender=userprofile) checker.save() task = Task(id=task_id) task.checkers.add(checker.id) return redirect('detailTaskPage', pk = task_id) I want to do something like this when I check versus uncheck the boxes: //Check @login_required def check_checker(request, task_id, checker_id): if request.method == 'POST': checker = Checker(id=checker_id) checker.save() checker.checked=True checker.save() return redirect('detailTaskPage', pk = task_id) //Uncheck @login_required def un_check_checker(request, task_id, checker_id): if request.method == 'POST': checker = Checker(id=checker_id) checker.save() checker.checked=False checker.save() … -
Django files upload causes memory leak
I have an observation about memory leak: If we try to POST files to Django view, Django will not release memory even a response has been made. The memory will keep rising if you keep uploading files even if you do nothing in views.py. (I have tried uploading 100 files concurrently calling the same API). I know that if an uploaded file is smaller than 2.5 megabytes, Django will hold the entire contents of the upload in memory. So I am wondering this could be an issue for a possible memory leak because it will never release the memory. PS: Even if I set FILE_UPLOAD_MAX_MEMORY_SIZE=0, which means use disk to store the files instead of using memory, I can still see a memory rise at the background. Does anyone know how to solve this issue ? Thanks a lot. -
redirect authenticated user at Createview in django
i used CreateView for registration in my project and i wanna prevent authenticated user from accessing to the register url and redirect it to another page can anyone tell me how can i do it? hear is my register view code: class RegisterUserView(CreateView): model = ChatUser template_name = 'login/registration_page.html' form_class = UserForm second_form_class = ProfileForm -
Looking for an alternative way to filter my objects before using a django-filters class
I've implemented a filter using the django-filters third party framework but want to run the filter on an already filtered set which was giving errors. class BlogView(ListView): template_name="blog/blog.html" model = Post # def get_queryset(self): # return Post.objects.filter(posted_date__lte=timezone.now()).order_by("-posted_date")[:25] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = PostFilter(self.request.GET, queryset=self.get_queryset()) return context my view ^ my filter v class PostFilter(django_filters.FilterSet): class Meta: model = Post fields = ["title"] My blog needs the ability to schedule posts in the future meaning when i display them i am filtering posts by posted_date__lte=timezone.now() however this is causing a problem when i am then using the filter because i cannot filter an already spliced object. I've read through and understand the problem comes from the way the database works so i am looking for an alternative way to make only posts that posted_date__lte=timezone.now() show without using the currently commented out def get_queryset filter i was previously using. -
Django test: cannot find object already created
My goal is to have a sort of generic function that creates a row only if this one doesn't exists. A bit of an extension of [get-or-create][1] When I create self.created_object in the setUp, I get an id for the object, which seems to be the definition for an object being persisted on the database. However, when I then try to query MyObject.objects.all(), I get an empty set. The test fails, and the error I get is the following: AssertionError: UUID('b8680f60-1fc0-4bc5-8a26-735ee43247ea') != UUID('38d9b535-2f12-4e76-b637-d52030798f3d') Here's a simplified version of what I'm trying to do from django.test import TestCase from app.models import MyObject from utils import get_object_or_create_it # the implementation is not relevant here class TestCreateOnlyIfNotExists(TestCase): def setUp(self): self.created_object = MyObject.objects.create( name="nobody_cares" ) def test_get_object_or_create_it(self): create_object_only_if_exists = get_object_or_create_it( {'name': 'nobody_cares'}, ('name',), MyObject, ) self.assertEqual( self.created_object.id, create_object_only_if_exists.id ) [1]: https://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create Any idea of what's going on here? -
How to create a Enterprise Application with Django
I love to create webapps with Django. I would like to develop an app exclusively for my company. That means no access for people outside the company. Because I'm the only developer, I need a solution that focuses on developing rather than administrative work. Heroku and Azure are good for deploying django but I do not know, how to create a network, that only interacts with the employees of my company. Running a own web server like Apache in the internal company network is also a solution, but I have no skills for it. The appidea: Djangoapp is showing data from a SQL Database. My company mainly works with Microsoft. I am very happy about suggestions -
Error while updating user group in django?
Here I am trying to add/update group name and user permissions and i tried like this. For add it is working fine but while updating with function edit_user_group i got problem. The problem is Exception Type: IntegrityError Exception Value: (1062, "Duplicate entry 'Developer' for key 'name'") I think this is because of OneToOne relation. How can I update user group here ? views.py @permission_required('organization.add_user_group', raise_exception=True) def add_user_groups(request): form = AddUserGroupForm() user_permissions = Permission.objects.all() if request.method == 'POST': form = AddUserGroupForm(request.POST) if form.is_valid(): group_name = form.cleaned_data['name'] permissions = request.POST.getlist('user_permissions') new_group = Group.objects.create(name=group_name) new_group.permissions.set(permissions) messages.success(request, 'New group added.') return redirect('organization:view_user_groups') return render(request, 'organization/add_user_groups.html', {'user_permissions': user_permissions, 'form': form}) @permission_required('organization.edit_user_group', raise_exception=True) def edit_user_group(request, pk): group = get_object_or_404(Group, pk=pk) user_permissions = Permission.objects.all() form = AddUserGroupForm() if request.method == 'POST': form = AddUserGroupForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] permissions = request.POST.getlist('user_permissions') group = Group.objects.update(name=name) group.permissions.set(permissions) messages.success(request, '{} group Updated.'.format(group.name)) return redirect('organization:detail_user_group',group.pk) return render(request,'organization/edit_user_group.html',{'group':group,'form':form,'user_permissions':user_permissions}) forms.py class AddUserGroupForm(forms.Form): name = forms.CharField(max_length=255) template for edit group <form action="{% url 'organization:edit_user_group' group.pk %}" method="post"> {% csrf_token %} <label> Group Name : </label> <input type="text" value="{{group.name}}" name="name"> <b class="text-danger"> {{ form.name.errors|striptags }} </b> <label>Permissions ({{user_permissions|length}}):</label> {% for permission in user_permissions %} <input name="user_permissions" type="checkbox" id="permission-{{permission.id}}" value="{{permission.id}}" {% if permission in group.permissions.all … -
How to get url to action method from ModelViewSet(Django Rest Framework) with reverse function?
I have this ModelViewSet class: class DriveInvoiceViewSet(viewsets.ModelViewSet): filter_fields = ('location_id', 'logical_deleted') permission_classes = (UserCanManageFacilityPermission,) pagination_class = None def get_serializer_class(self): ... def get_queryset(self): ... @action(detail=False, methods=['GET']) def get_subtotals_by_unit(self, request): invoices_list = self.filter_queryset(self.get_queryset()) grouped_invoices = get_subtotals_by_unit(invoices_list) return Response(grouped_invoices) How can I get the URL from reverse function to test the get_subtotals_by_unit action? The ViewSet registred by the router router.register('drive_invoices', DriveInvoiceViewSet, base_name='drive_invoices') -
How to give full access (= anyone) POST to a JWT view?
I'm using djangorestframework with djangorestframework-simplejwt. Everything works fine except one thing: I want to access to a reset-password view with a POST method (= REST "create"). from django.views.decorators.csrf import csrf_exempt from rest_framework.generics import CreateAPIView # JSON views are never accessed through classical forms = no csrf possible: @method_decorator(csrf_exempt, name='dispatch') class UsersResetPasswordView(CreateAPIView): serializer_class = UserResetPasswordSerializer permission_classes = [permissions.AllowAny] def create(self, request, *args, **kwargs): return Response({'reset-url': 'test url'}, status=status.HTTP_202_ACCEPTED, headers=headers) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) permissions.AllowAny is not enough, I get a 401 "Given token not valid" (if I send the token, otherwise I get "forbidden"). I've tried to add authentication_classes = [] but nothing changes. I just want to make a simple view that anybody can access, via a POST! -
Online collaborative list of references
I am working in academia in a very wide field of research mixing a lot of different domains. This broadness is also a problem, since there is no proper references for the basis of the theory, and we have to deal with a lot of material scattered in very different places, often in the form of lecture notes, conference proceeding or unpublished documents. Therefore, I would like to propose a collaborative online list of these references, in a light way so that anyone could add or improve the list. The best current list of references is here, which is neither up to date nor really easy to use (no tags, list by authors, etc). I would like something slightly more powerful, I though about some framework like Django but don't really know if it is a suitable solution. I would like to be able for anyone to sort in different ways add tags add or edit references entries rate difficulty (this is a bonus) comment (this is a bonus) Moreover, it should be better if the list were accessible without any amount on a simple webpage. Any suggestion is welcome! -
How to use django-graphql-geojson - Problems with distance_Lte Filter
I want to use the distance_Lte filter as in the readme-file https://github.com/flavors/django-graphql-geojson described. But I didn´t get the expected result. Can someone tell me what my failure is? My django classes: class Location(models.Model): calendar = models.ForeignKey(Calendar, on_delete=models.CASCADE) name = models.CharField(max_length=255) location = models.PointField(srid=4326, unique=True) address = models.CharField(max_length=100) city = models.CharField(max_length=50) class LocationType(GeoJSONType): class Meta: model = Location geojson_field = 'location' filterset_class = LocationFilter interfaces = (relay.Node,) exclude = [] class LocationFilter(GeometryFilterSet): class Meta: model = Location fields = { 'city': ['exact', 'icontains', 'istartswith'], 'location': ['exact', 'intersects', 'distance_lte'] } class Query(graphene.ObjectType): location = relay.Node.Field(LocationType) locations = DjangoFilterConnectionField(LocationType) My graphql-Query: query{ locations(location_DistanceLte:{geometry:"{'type': 'Point', 'coordinates': [13.28702,52.4581]}", value:400, unit:"km"}){ edges{ node { id } } } } The error-msg: { "errors": [ { "message": "Argument \"location_DistanceLte\" has invalid value {geometry: \"{'type': 'Point', 'coordinates': [13.28702,52.4581]}\", value: 400, unit: \"km\"}.\nExpected type \"Geometry\", found {Geometry: \"{'type': 'Point', 'coordinates': [13.28702,52.4581]}\", value: 400, unit: \"km\"}.", "locations": [ { "line": 2, "column": 34 } ] } ] } I don´t know, what I´m doing wrong... It would be nice if you can help. Thanks -
Django 2.1 created migration with makemigrations did not show up in migrations folder
After running python manage.py makemigrations terminal showed Migrations for 'api_app': api_app/migrations/0004_analysis_error.py But the file didn't show up in the directory. I ran python manage.py migrate and it even showed: Applying api_app.0004_analysis_error... OK But still no api_app.0004_analysis_error.py in the directory. I also tried making an empty migration, the same behavior occurred. I also tried removing the changes and resetting the migrations, no changes were detected (even though there were). The application name has been included in the [INSTALLED_APP] module in settings.py. -
Django - saving manually generated ImageField raises error
I have anInvoice model which has qr_code = ImageField(...) field. In save method, I want to generate the qr_code file and save it to the field. The problem is a path. When I set path including /media/ - so /media/qr/myfile.png, Django then looks for it in templates this way: /media/media/qr/myfile.png. But when I not include /media/ it cannot be saved: FileNotFoundError: [Errno 2] No such file or directory: 'qr/myfile.png' I think the problem is either in first function or at the end of the other. Invoice.generate_qr def generate_qr(self, save=False): path = qr.generate_qr(self, f"Faktúra č. {self.number}") self.qr_code = path if save: self.save() qr file def generate_qr(invoice, note: str = None) -> Optional[str]: ... qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4, ) qr_php_script_path = os.path.join(settings.BASE_DIR, 'dashboard', 'faktury', 'qr.php') proc = subprocess.Popen( ["php", qr_php_script_path, str(total), splatnost, variable_symbol, "", "", note or "", iban, "", ], stdout=subprocess.PIPE) qr_string, _ = proc.communicate() qr.add_data(qr_string) qr.make(fit=True) img = qr.make_image(fill_color="black", back_color="white") img_path = os.path.join(settings.MEDIA_ROOT, 'qr', 'myfile.png') img.save(img_path) return img_path Do you know how to make it work? -
How to solve this celery Error: Unable to load celery application. Module 'forecast' has no attribute 'celery'
I am trying to seting up Celery and Amazon SQS for my project but faced with problems. I did following. I put celery.py file inside my project directory where settings py located. Here is snapshot of my project --predictions --forecast --dataflow --forecast ** __init__.py ** celery.py ** urls.py ** settings.py ** wsgi.py --manage.py --env I doted with "--" folders and with "**" files. Inside celery.py file i have the folliwing code from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault ('DJANGO_SETTINGS_MODULE', 'forecast.settings') app = Celery('forecast') app.config_from_object ('django.conf:settings') app.autodiscover_tasks() app.conf.beat_schedule = { 'display_time-30-seconds': { 'task': 'demoapp.tasks.display_time', 'schedule': 10.0 }, } @app.task(bind=True) def debug_task(self): print('Request: {0r}'.format(self.request)) Inside settings.py file i set up Amazon credentials,broker_url etc #settings.py # AWS Credentials AWS_ACCESS_KEY_ID = ('lol') AWS_SECRET_ACCESS_KEY = ('Lol') # Celery BROKER_URL = "sqs://%s:%s@" % (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_DEFAULT_QUEUE = 'test.fifo' CELERY_RESULT_BACKEND = None # Disabling the results backend BROKER_TRANSPORT_OPTIONS = {'region': 'us-west-2', 'polling_interval': 20,} Inside init.py file i put the following code from __future__ import absolute_import, unicode_literals from .celery import app as celery_app__all__ = ['celery_app'] Then i added in my django app task.py which contain the following code from datetime import datetime from celery … -
React BrowserRouter Route doesn't change url
I am trying to make my React Router change my actual url. Right now it changes the component but does not change the actual url in my browser Here is my app.js import React, { Component } from 'react'; import './App.css'; import { BrowserRouter, Route, Redirect, Switch} from 'react-router-dom'; import PaintingList from './paintings/PaintingList'; import PaintingDetail from './paintings/PaintingDetail'; import PaintingCreate from './paintings/PaintingCreate'; class App extends Component { render() { return ( <BrowserRouter> <Switch> <Route exact path='/' component={PaintingList}/> <Route path='/paintings' component={PaintingList}/> <Route path='/paintings/create' component={PaintingCreate}/> <Route path='/detailed-view/:slug' component={PaintingDetail}/> </Switch> </BrowserRouter> ); } } export default App; I am trying to make the PaintingDetail component point to the /detailed-view/:slug path but my actual browser keep displaying http://127.0.0.1:8000/paintings/sad-man (sad-man is the slug in this case) I have even tried to delete this line all together <Route path='/detailed-view/:slug' component={PaintingDetail}/> The component still works but the the browser still displays http://127.0.0.1:8000/paintings/sad-man I am using Django for my backend, I am not sure if that has anything to do with it. Here is my url.py for my paintings model from django.urls import path, re_path from .views import ( PaintingDetailAPIView, PaintingListCreateAPIView, ) app_name = 'paintings-api' urlpatterns = [ path('', PaintingListCreateAPIView.as_view(), name='list-create'), re_path(r'^(?P<slug>[\w-]+)/$', PaintingDetailAPIView.as_view(), name='detail'), ] here is my urls.py … -
How to hide some Usergroups from Django Admin in ManytoMany field
I have the following model: class Task(models.Model): site=models.OneToOneField(Site,on_delete=models.CASCADE,default=1) executor=models.ManyToManyField(People) It is related to the following model: class People(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True) phone_number = models.CharField(max_length=200, blank=True, null=True) #department = models.CharField(max_length=200, blank=True, null=True) title = models.CharField(max_length=200, choices= titles, blank=True, null=True) What I want is that in DjangoAdmin in the field executor only people__title='titleone' was displayed. So that the executor search field would not be overload with other people who cannot ever be related to the Tsk since I have them in the same database.