Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Assiging a css file located in static after deploying website
I have deployed a Django project using Apache2, everything is working fine except for weazyprint which creates PDF file for forms. The pdf was working fine in testing and local host. Now everytime I access the pdf it is showing this error: FileNotFoundError at /business_plan/businessplan/admin/info/2/pdf/ [Errno 2] No such file or directory: '/home/ahesham/Portfolio/static\\css\\report.css' I have tried to change the \ and adding it twice but it didn't work here is the views.py def admin_order_pdf(request, info_id): info = get_object_or_404(Info, id=info_id) html = render_to_string('businessplan/pdf.html', {'info': info}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format( Info.id) weasyprint.HTML(string=html,base_url=request.build_absolute_uri()).write_pdf(response, stylesheets=[weasyprint.CSS(settings.STATICFILES_DIRS[0] + '\css\\report.css')], presentational_hints=True) return response The error is comming from this \css\\report.css knowing that the report.css file is in the static folder and all css and js of the deplyed site is working perfectly fine and I tried python manage.py collectstatic did not work My question: What am I doing wrong and how do I fix it? Please let me know if additional information required -
Why django migrate command don't insert to django_migrations table
There was a change in the DB and the Model was modified. After running Makemigrations, I ran migrate. The DB has been changed normally, but the history is not added to the django_migrations Table. Because of this problem, a warning to continue to migrate appears even after migrating. And when I try to migrate again, the history is not added to the django_migrations table, so I try to change the DB as before, and this is of course an error. This is migrations file. class Migration(migrations.Migration): dependencies = [ ('common_py', '0001_initial'), ] operations = [ migrations.AddField( model_name='customer_company', name='del_date', field=models.DateTimeField(default=None, null=True, verbose_name='삭제일'), ), ] Run command "python manage.py migrate" Result (venv) PS D:\Projects\AFF\AFF> python manage.py migrate Operations to perform: Apply all migrations: auth, common_py, contenttypes, sessions Running migrations: Applying common_py.0002_customer_company_del_date... OK Change Table Success But didn't add history to "django_migrations" Table Have you any idea? I Couldn't find any information about this. Thank you. -
Named url kwargs in authenticate method
I'm trying to create a custom authentication class in the Django rest framework. In the authenticate(self, request) method, at first glance, it seems that there is no way to get named kwarg from the URL. Is there a way to accomplish this? -
Non containerised Nginx not serving files from django docker container
I'm so close to solving this, it's actually painful, and so any help would be awesome. New to Django. New to Nginx. New to Docker. But love a challenge. Have a virtual server at DigitalOcean. Following a number of tutorials and reading endless documentation I've got the following, the problem is, nginx is serving the wesbite, but not the staticfiles. I'm sure it's something to do with my settings.py or nginx.conf, but can't tell what. settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "devops", "staticfiles") STATICFILES_DIRS = [ BASE_DIR / "static", ] MEDIA_URL = "/mediafiles/" MEDIA_ROOT = os.path.join(BASE_DIR, "devops", "mediafiles") docker-compose If I'm doing this correctly, I need to have my staticfiles outside of my container so that the standalone nginx can serve them. I'm doing it this way as I think I'm reading that it's easier to have LetsEncrypt and certbot set up with nginx outside of a container than inside. version: '3.7' services: web: image: <dockerimage> container_name: <name> command: gunicorn <site>.wsgi:application --bind 0.0.0.0:8000 --workers 5 volumes: - $HOME/devops/staticfiles:/home/app/web/staticfiles - $HOME/devops/mediafiles:/home/app/web/mediafiles ports: - 8000:8000 env_file: - .env.docker depends_on: - db labels: - com.centurylinklabs.watchtower.enable=true restart: "on-failure" db: image: index.docker.io/postgres:12.0-alpine container_name: db env_file: - .env.docker volumes: - postgres_data:/var/lib/postgresql/data/ restart: "on-failure" volumes: postgres_data: … -
Is there a way to use 'query' and 'forloop' together in Djang templates?
{% for game in game_query %} {% for i in game.data.participantIdentities %} {% if i.player.summonerName == summoners_result.name %} {% if i.participantId == game.participants.forloop.counter0.participantId %} {% if game.participants.forloop.counter0.stats.win == true%} win {% else %} false {% endif %} {% endif %} {% endif %} {% endfor %} {% endfor %} The game_query is json data with game data. The summoners_result.name is a user nickname. The problem is the game.participants.forloop.counter0.participantId Is there a way to use 'forloop counter' from 'for' with query? -
Django, Factory boy - can't create subfactory
I have created three factories where User and Profile are associated as onetoone field, also Label is sub factory of Profile. import factory from users.models import User, Label, Profile from .models import Release import random from django.db.models.signals import post_save @factory.django.mute_signals(post_save) class ProfileFactory(factory.django.DjangoModelFactory): class Meta: model = Profile user = factory.SubFactory("releases.factories.UserFactory", profile=None) @factory.django.mute_signals(post_save) class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User email = factory.Faker("email") password = factory.Faker("password") profile = factory.RelatedFactory(ProfileFactory, factory_related_name='user') class LabelFactory(factory.django.DjangoModelFactory): profile = factory.SubFactory(ProfileFactory) name = factory.Faker("name") class Meta: model = Label but when I try to create a label (LabelFactory.create()) it throws the error RelatedObjectDoesNotExist: User has no profile. What is wrong? Please help! -
How to send data from django to Vue3 component
I am trying to send some data from django to a Vue3 component, but i can`t manage to send it to Vue. html code snippet {{object_list|json_script:"team_members"}} <script> const team_member_list = JSON.parse(document.getElementById('team_members').textContent); </script> <cardcarousel :team=team_member_list></cardcarousel> <script> console.log(team_member_list[0]['first_name'])0 </script>` My component app.component('cardcarousel', { data(){ return { } }, props:{ team:{ type: Array, required: true, } } , template:/*html*/` <div v-for="team_member in team" class="card_carousel"> <teamcard :first_name = "team_member.id"></teamcard> </div> `,})` In the console log i can see my Array, but from Vue i receive the following warning: [Vue warn]: Invalid prop: type check failed for prop "team". Expected Array, got Undefined. -
Django image not showing up in template (not URLs issue)
I've added the neccessary elements to the URLs.py. The image is NOT stored in the database. URLs.py from django.conf import settings from django.conf.urls.static import static ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) . I'm trying all of the following <link rel="apple-touch-icon" sizes="76x76" href="./assets/img/image.png"> <img src="static/storiesapp/img/image.png"> <img class='img-responsive' src="{{ MEDIA.URL }}{{ image.png }}" /> -
How do I change Django Index CSS?
I am working on a django web application and I am trying to change the background for my application. But the style for the whole project seems to be hardcoded in the (index) file and no matter what I do, I am unable to change it. Any idea how I would be able to change it? -
Deploying Django app to Heroku - 'ModuleNotFoundError: No module named 'storages'
I am trying to deploy a Django app to Heroku. I have deployed many times before, but now that I have added integration with S3, I am getting a collectstatic error. I am new to this and appreciate your help! The error when I do git push heroku main: remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 22, in <module> remote: main() remote: File "manage.py", line 18, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 377, in execute remote: django.setup() remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/__init__.py", line 24, in setup remote: apps.populate(settings.INSTALLED_APPS) remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate remote: app_config = AppConfig.create(entry) remote: File "/app/.heroku/python/lib/python3.8/site-packages/django/apps/config.py", line 90, in create remote: module = import_module(entry) remote: File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import remote: File "<frozen importlib._bootstrap>", line 991, in _find_and_load remote: File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked remote: ModuleNotFoundError: No module named 'storages' remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. My settings.py file: INSTALLED_APPS = [ ... 'django.contrib.staticfiles', 'storages', ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' #mediaroot … -
Django Template Variable Failing as href Value
I have created a Django template which serves as an email template for my app. Upon certain actions, a celery task sends an email from this template using Sendgrid. Previously I hard-coded the URLs but now I need them to be dynamic. I am passing the url string as a variable called profile_url. I know that the URL is formatted correctly because I am printing it before calling the send_mail() function. If I use the value like so it works: <p>{{ profile_url }}</p> However, when I use it as an href value the link renders unclickable: <a href="{{ profile_url }}" target="_blank" style=" text-decoration: none; color: #ffffff; line-height: 40px; display: block; " >Go to your profile</a> If anyone can assist me or at least point me in the right direction here I'd greatly appreciate it! -
what can I do if django manage.py runserver is not working?
I am new to django and I use django 3.2. Whenever I run python manage.py with any other command. Like python manage.py runserver or python manage.py makemigrations i get this bulky error message. please what can i do.My server starts up immediately after I start the project withdjango-admin startproject dummy but a get the error message after working on my project. thank you Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Users\User\myenv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\User\myenv\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\User\myenv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\User\myenv\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "C:\Users\User\myenv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\User\myenv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\User\myenv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\User\myenv\lib\site-packages\django\apps\config.py", line 224, in create import_module(entry) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, … -
Django - How to display specific content in a template
Django newbie question - I need to display a specific entry in a template. So far I have not been able to get this to work. I have the following code: model: class BasicPage(models.Model): title = models.CharField(max_length=200) body = HTMLField() def __str__(self): return self.title view: class TermsPageView(TemplateView): model = BasicPage template_name = 'terms.html' def get_queryset(self): body = BasicPage.objects.filter(id=1) return body template: {% block content %} <h1>{{ body.title }}</h1> {% endblock content %} -
Profile Page for all Users blogs Django
everyone. I'm building a blog site and each user has a profile that should list their written blogs. But I'm finding it difficult to make a reference to individual users. My Views class ShowProfilePageView(LoginRequiredMixin, DetailView): model = UserProfile template_name= 'registration/user_profile.html' def get_context_data(self, *args, **kwargs): context = super(ShowProfilePageView, self).get_context_data(*args, **kwargs) page_user = get_object_or_404(UserProfile, id=self.kwargs['pk']) user = self.request.user user_posts = Post.objects.filter(author= user).order_by('-post_date') context['page_user'] = page_user context['user_posts'] = user_posts return context Note: The user, defined in the view above is self.request.user and this makes all the user profiles list out the blogs of the current logged in user instead of been based on particular users. Models The Post/Blog model class Post(models.Model): title = models.CharField(max_length=225) header_image = models.ImageField(blank= True, null=True, upload_to='images/header_image') author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextField(blank=True, null=True) post_date = models.DateField(auto_now_add = True) category = models.CharField(max_length=225) snippet = models.CharField(max_length=70) UserProfile models The user profile models class UserProfile(models.Model): user = models.OneToOneField(User, null=True, on_delete = models.CASCADE) bio = models.TextField(max_length=160) profile_pic = models.ImageField(blank= True, null=True, upload_to='images/profile_pics') website_url = models.CharField(max_length=250, null = True, blank = True) twitter_url = models.CharField(max_length=250, null = True, blank = True) github_url = models.CharField(max_length=250, null = True, blank = True) linkedin_url = models.CharField(max_length=250, null = True, blank = True) dribble_url = models.CharField(max_length=250, null … -
What's the best way to return to the previous page after Post? (Not login)
After a user updates a record and hits the 'Post' button, what's the best way to redirect them to the previous page? I know there's a potential issue with using the HTTP_REFERER method however the user will be using not be using a browser with custom settings. This does not work (it only refreshes the page) def form_valid(self, form): form.instance.fk_user = self.request.user form.save() return HttpResponseRedirect(self.request.META.get('HTTP_REFERER')) def test_func(self): post = self.get_object() if self.request.user == post.fk_user: return True return False If I remove the 'self.' i recieve an error where 'name 'request' is not defined' -
What framework should I use for my project?
all the developers, I am a member of a programming team and we want to create a large scale web application that requires a lot of user interactions and databases. 3 members of our team have experience with python and C#, 2 members have with javascript(the one has python too). Which framework is better for this kind of web application? Which one will take less time to code? 1.Django 2.Flask 3.MERN stack 4.ASP.Net Thanks before :) -
Beanstalk cannot connect to rds instance
Im in a similar boat to the user on this question; Connecting the elastic beanstalk environment with existing RDS instance I have a Codestar project (Django via Beanstalk) and i cannot get the application to access any rds instances. When attempting to deploy during the testing step (python manage.py test) the following error message is thrown; django.db.utils.OperationalError: could not connect to server: Connection timed out Is the server running on host "172.31.44.126" and accepting TCP/IP connections on port 5432? Things ive already tried Running locally works fine via django and psql using ipaddress and public hostname (name.key.eu-west-2.rds.amazonaws.com) both work fine locally and provide the same error message when deploying Connecting to rds via the EC2 instance This works fine connecting via local ip and name. Queries such as \d and \l return fine indincating the instance can see the database. Changing vpc / subnets Both EC2 and rds instances are in the same vpc (only have one) and subnet (eu-west, availability group 2a) Spinning up an attached beanstalk rds instance I have tried dedicated rds instances and a connected instance using the EBS tool and the application has been unable to connect to either. Settings.py if 'RDS_DB_NAME' in os.environ: DATABASES … -
Django Nested Serializer
I am pretty new to DRF/Django and want to create an endpoint that returns nested json from multiple models in the format: { "site": { "uuid": "99cba2b8-ddb0-11eb-bd58-237a8c3c3fe6", "domain_name": "hello.org" }, "status": "live", "configuration": { "secrets": [ { "name": "SEGMENT_KEY", # Configuration.name "value": [...] # Configuration.value }, { "name": "CONFIG_KEY", "value": [...] }, "admin_settings": { 'tier'='trail', 'subscription_ends'='some date', 'features'=[] } Here are the models: class Site(models.Model): uuid = models.UUIDField( default=uuid.uuid4, editable=False, unique=True) domain_name = models.CharField(max_length=255, unique=True) created = models.DateTimeField(editable=False, auto_now_add=True) modified = models.DateTimeField(editable=False, auto_now=True) class AdminConfiguration(models.Model): TRIAL = 'trial' PRO = 'pro' TIERS = [ (TRIAL, 'Trial'), (PRO, 'Professional'), ] site = models.OneToOneField( Site, null=False, blank=False, on_delete=models.CASCADE) tier = models.CharField( max_length=255, choices=TIERS, default=TRIAL) subscription_ends = models.DateTimeField( default=set_default_expiration) features = models.JSONField(default=list) class Configuration(models.Model): CSS = 'css' SECRET = 'secret' TYPES = [ (CSS, 'css'), (SECRET, 'secret') ] LIVE = 'live' DRAFT = 'draft' STATUSES = [ (LIVE, 'Live'), (DRAFT, 'Draft'), ] site = models.ForeignKey(Site, on_delete=models.CASCADE) name = models.CharField(max_length=255, blank=False) type = models.CharField( max_length=255, choices=TYPES) value = models.JSONField( null=True) status = models.CharField( max_length=20, choices=STATUSES) Logic behind serializer/viewset to achieve mentioned json: retrieves lookup_field: uuid filters query param: Configuration.status (either live or draft filters AdminConfiguration on site id (something like AdminConfiguration.objects.get(Site.objects.get(uuid)) filters Configuration on … -
ManyToManyField does not show
Want to use REST API to populate my tables but my field does not display on the API page. Models (Series, Roster): class Series(models.Model): (...) def __str__(self): return self.title class Roster(models.Model): (...) series = models.ManyToManyField(Series) (...) def __str__(self): return self.name Serializers: class SeriesSerializer(serializers.ModelSerializer): class Meta: model = Series fields = ('id', 'title', 'icon') read_only_fields = ('slug',) class RosterSerializer(serializers.ModelSerializer): series = SeriesSerializer(many=True, read_only=True) class Meta: model = Roster fields = ('id', 'name', 'number', 'primary_color', 'secondary_color', 'image', 'series') Views: class SeriesView(viewsets.ModelViewSet): serializer_class = SeriesSerializer queryset = Series.objects.all() class RosterView(viewsets.ModelViewSet): serializer_class = RosterSerializer queryset = Roster.objects.all() Unsure where I am mistepping here. -
DRF how to get items grouping by categories
I understand that my question is repeated often, but i'm stuck with this. I want to make simple api with DRF. I have two models: models.py class Rubrics(models.Model): id = models.AutoField(primary_key=True) rubric = models.CharField(max_length=255, blank=True, null=True) class Books(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=255, blank=True, null=True) author = models.CharField(max_length=255, blank=True, null=True) date = models.CharField(max_length=255, blank=True, null=True) rubrics = models.ForeignKey('Rubrics', on_delete=models.DO_NOTHING, related_name='books', blank=True, null=True) I'd like to view serialized result like this: [ rubric1: [ { title: "title1", author:"author1" }, book_obj2, so on ], rubric2: [ book_obj4, book_obj5 ] ] my views.py: class BooksByRubricView(APIView): """List of books by rubrics""" def get(self, request): last_date = Books.objects.latest("date").date books_last = Books.objects.filter(date=last_date) serializer = RubricsSerializer(books_last, many=True) return Response(serializer.data) I try a lot of examples in this theme, sorry this garbage class BookSerializer(serializers.ModelSerializer): class Meta: model = Books #fields = ("title",) exclude = () class RubricsSerializer(serializers.ModelSerializer): rubrics = BookSerializer(read_only=True) class Meta: model = Rubrics fields = ("rubrics",) #exclude = () """ class RubricSerializer(serializers.ModelSerializer): #rubrics = serializers.PrimaryKeyRelatedField(many=True, read_only=True) #books = RecursiveSerializer(many=True) #print(books) rubrics = RubricSerializer(read_only=True) #books = BooksListSerializer(many=True) class Meta: model = Books fields = ("title", "rubrics",) #fields = ['rubric', 'rubrics'] #fields = ['books', 'rubrics'] """ but maybe i don't understand principles of reverse relationships and serializing … -
Can't host my django website on shared hosting
I am trying to deploy my django project on shared hosting. I am trying from couple of hours but still now I can't host my django website and getting "Internal Server Error Error 500". this is my root passenger_wsgi.py from my_root_folder_name.wsgi import application #setting.py ALLOWED_HOSTS = ['mydomain.com','www.mydomain.com'] I also installed python app and django on my server. Now I am hopeless. I am trying from last five hours for host an website but still now I can't. Where I am doing mistake??? I am seeing those error from error log: File "/home/sellvqed/virtualenv/farhyn.com/3.8/lib/python3.8/site-packages/django/apps/registry.py", line 83, in populate raise RuntimeError("populate() isn't reentrant") RuntimeError: populate() isn't reentrant -
Why i get results of this ajax call instantly though I have async code?
I am studying async programming with Python and I cannot get why I get instant answer when I call route corresponding to this call (I call it as ajax call, platform is Django, this file is views.py file in Django app)? (When I click on button ajax calls buy method, it simulates buying some stock with sandbox and returns result, I want it to wait 5 secs and then return result, instead I get results of ajax call nearly immediately) async def buy(request): figi = request.GET.get('figi', 'missing') data = { 'result': 'success', 'figi': figi } SANDBOX_TOKEN = 'some_token' async def buy_stock(): try: async with TinkoffInvestmentsRESTClient( token=SANDBOX_TOKEN) as rest: order = await rest.orders.create_market_order( figi="BBG000BTR593", lots=1, operation=OperationType.BUY, ) await asyncio.sleep(5) result = await rest.orders.create_limit_order( figi="BBG000BTR593", lots=1, operation=OperationType.SELL, price=50.3, ) return 'result' except TinkoffInvestmentsError as e: print(e) result = await buy_stock() return JsonResponse({ 'result': 'success', 'message': result }, safe=False) In other words, seems call doesn't wait for async methods to finish and immediately sends JsonResponse -
How to upload a form image that comes in a request.FILES[] to an ImageField in my django db?
The problem here is that when I "upload" the image, it doesn't make any changes where it should It lets me make the upload with no errors but as I said, it doesn't update un db or anywhere. I need to write more to post this as I have too much code so dont read this part in parenthesis (Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis pharetra augue sed pharetra lobortis. Mauris sit amet pellentesque felis. Integer in magna nec enim placerat imperdiet vitae et justo. Integer vel est ultricies, faucibus urna id, consequat eros. Integer venenatis ut nisi a aliquam. Morbi leo sem, dictum porttitor nibh id, condimentum pellentesque purus. Quisque pellentesque et nibh nec hendrerit. Suspendisse in nulla urna. Nam sit amet congue quam. Duis tellus enim, tincidunt ac est eget, lobortis accumsan orci. Mauris laoreet iaculis ornare. Maecenas eget urna malesuada dolor mollis efficitur. Nullam vehicula vel justo nec suscipit. Morbi fermentum libero urna, feugiat tincidunt felis pharetra ut. Vestibulum at erat sed massa sodales malesuada et eget justo. Fusce at iaculis quam, non elementum quam.) This is my model from django.db import models from django.utils.timezone import now from django.contrib.auth.models import User from ckeditor.fields import … -
Django url re_path failed to redirect to the correct view
Django re_path did not match and I don't know the reason why. urls.py urlpatterns = [ .. re_path(r'^localDeliveryPayment\?paymentId\=(?P<UUID>[0-9-a-z]{32})$', verifyMobilePayReceived.as_view()), re_path(r'^localDeliveryPayment$', Payment.as_view(), name = 'localDeliveryPayment'), .. ] If url www.example.com/localDeliveryPayment the user is directed to Payment view. If url www.example.com/localDeliveryPayment?paymentId=00340000610febab0891e9008816d3e9 the user should be directed to verifyMobilePayReceived view. The problem is that right now www.example.com/localDeliveryPayment?paymentId=00340000610febab0891e9008816d3e9 is still directed to Payment view. -
NoReverseMatch in Django but no clear issues
I've been reading other solutions to this but none of them apply to my project. It's a database of family pictures. The Problem On the list view, which works fine, there are two types of links - one at the top of the page to create a new record and one for each of the listed items to update the selected record. When clicking either, I get the following error. If I simply enter the URLs, I also get the same error. NoReverseMatch at /stories/l_memories_update_people/4 Reverse for 'memories_people' not found. 'memories_people' is not a valid view function or pattern name. . Models class memories_people(models.Model): fk_user = models.ForeignKey(User, default='1', on_delete=models.CASCADE) name = models.CharField(max_length=750, default='', blank=True, null=True) def __str__(self): return self.name class Meta: ordering = ('name', ) Views class v_memories_list_people(LoginRequiredMixin, ListView): model = memories_people template_name = 'storiesapp/t_memories_list_people.html' context_object_name = 'people' ordering = ['name'] class v_memories_update_people(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = memories_people fields = ['fk_user', 'name'] template_name = 'storiesapp/t_memories_update_people.html' def form_valid(self, form): form.instance.fk_user = self.request.user form.save() return HttpResponseRedirect(self.request.path_info) def test_func(self): post = self.get_object() if self.request.user == post.fk_user: return True return False URLs path('l_memories_list_people',v_memories_list_people.as_view(), name='r_memories_list_people'), path('l_memories_update_people/<int:pk>',v_memories_update_people.as_view(), name='r_memories_update_people'), Template (List) {% load static %} {% load crispy_forms_tags %} {% load render_table from django_tables2 %} {% load …