Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Azure App Service: How to run management command for dockerized django application
I've a django applicaiton running in docker-compose in local along with an nginx and frontend applicaiton. I've tried to deploy the applicaiton in azure app service using my custom docker image for the django application. The app deployment was successfull but now i need to run django management command like python manage.py migrate and python manage.py createsuperuser. I tried to use SSH in my django container, but when i tried to connect its showing az webapp create-remote-connection --subscription <id> --resource-group <rg-name> -n <app-anme> & Is there any other way to run django management commands in azure app service with a multi-container application. -
Can't open lib 'ODBC Driver 17 for SQL Server' : file not found (0) (SQLDriverConnect)") on Azure Linux
I'm trying to deploy python django app on azure linux using azure cli and after deployment it is showing me database connectivity error for drivers. error message is "Can't open lib 'ODBC Driver 17 for SQL Server' : file not found (0) (SQLDriverConnect)") on Azure Linux" enter image description here -
What is context_object_name=None in django class CeateView?
Get the name to use for the object. For context_object_name=None Doc:For example Article will be article Why we use context_object_name in createview.We don't have a object,we just have a simple for to show users. def get_context_object_name(self, obj): """Get the name to use for the object.""" if self.context_object_name: return self.context_object_name elif isinstance(obj, models.Model): return obj._meta.model_name else: return None Please somebody help me??? -
Graphene without Django ORM models
I am using 2 DBs (Postgre as primary & Redshift for Big Data). All basic migrations are connected with Postgre DB & ORM based. But, All complex quries for reports & analysis on big data is using Redshift through RAW quries of django. (no Model class or migration on redshift, some external resource dumping data to Redshift). I am struggling to integrate Graphene-Django with my Redshift tables, but Docs mention DjangoObjectType conversion of django model as 1st step, which I don't have in my case. Currently, I am using cursor.execute(query) & cursor.fetchall() to get my results from Redshift tables. How I can bind these tables with Graphene in schema.py. class CategoryType(DjangoObjectType): class Meta: model = Category fields = ("id", "name") -
Django django module not found error no module listings
Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1776.0_x64__qbz5n2kfra8p0\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1776.0_x64__qbz5n2kfra8p0\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "C:\Users\Acer\Desktop\Project_Real\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Acer\Desktop\Project_Real\venv\lib\site-packages\django\core\checks\urls.py", line 42, in check_url_namespaces_unique File "C:\Users\Acer\Desktop\Project_Real\venv\lib\site-packages\django\urls\resolvers.py", line 715, in url_patterns ...... ModuleNotFoundError: No module named 'listings.urls' -
ERROR: Must appear in the GROUP BY clause or be used in an aggregate function "DJANGO"
I get the following error with my queryset: django.db.utils.ProgrammingError: column "u0.color" must appear in the GROUP BY clause or be used in an aggregate function LINE 1: ...."payment_amount"), 0)) AS "owed_amount", (SELECT U0."color"... These are my models: class DebitFileScore(CustomModel): minimum_amount = models.PositiveIntegerField(verbose_name=_("Monto minimo"), help_text=_("Monto minimo para semaforo"),unique=True) color = models.CharField(max_length=8, verbose_name=_("Color asignado"), help_text=_("Color asignado para semaforo")) class DebitFile(CustomModel): debit_file_section = models.ForeignKey(DebitFileSection, on_delete=models.PROTECT, related_name='debit_files', verbose_name=_("Departamento de expediente"), help_text=_("Referencia foranea al modelo 'DebitFileSection'")) debit_amount = models.FloatField(default=0, verbose_name=_("Monto de aduedo")) name = models.CharField(null=True, blank=True, max_length=100, verbose_name=_("Nombre del acredor"), help_text=_("Nombre del acredor")) comments = models.TextField(null=True, blank=True, verbose_name=_("Comentarios"), help_text=_("Comentarios libres")) cut_off_date = models.DateField(default=date.today,verbose_name=_("Fecha de Corte")) phone = models.CharField(null=True, blank=True, max_length=200, verbose_name=_("Teléfono"), help_text=_("Teléfono de acredor")) date = models.DateField(verbose_name=_("Fecha Registro")) timestamp = models.DateTimeField(auto_now=True) objects = querysets.DebitFileQueryset.as_manager() class DebitFilePayment(CustomModel): debit_file = models.ForeignKey(DebitFile, on_delete=models.PROTECT, related_name='debit_file_payments', verbose_name=_("Operador"), help_text=_("Referencia foranea al modelo 'Operator'")) payment_amount = models.FloatField(default=0, verbose_name=_("Monto de aduedo")) comments = models.TextField(null=True, blank=True, verbose_name=_("Comentarios"), help_text=_("Comentarios libres")) date = models.DateField(verbose_name=_("Fecha Registro")) timestamp = models.DateTimeField(auto_now=True) This is the queryset I'm trying to create, it's the withScore() method that fails: class DebitFileQueryset(models.QuerySet): def withPaymentsAmount(self): return self.annotate( owed_amount=models.F("debit_amount") - models.functions.Coalesce(models.Sum("debit_file_payments__payment_amount"),0), ) def withScore(self): from GeneralApp.models import DebitFileScore score = DebitFileScore.objects.filter(minimum_amount__lte=models.OuterRef('owed_amount')).exclude(minimum_amount__gt=models.OuterRef('owed_amount')) return self.annotate( score_color=models.Subquery(score.order_by('minimum_amount','color').values('color')), ).order_by("score_color") I followed the example of the documentation https://docs.djangoproject.com/en/4.1/ref/models/expressions/#subquery-expressions My Django version … -
Create calculated column with if expression django
I want to create a new calculated column on my django queryset (Models.objects) that will be calculated as: field_one if field_one is not null else field two I've tried some like this in django: from models.models import Model from django.db.models import F data = Model.objects.annotate(start_date= F('better_date') if F('better_date') is not None else F('field_2')) data[0].__dict__['start_date'] # Result #'start_date': None But I get a 'start_date' attribute as None How do I create the column mentioned to use later while iterating the objects? -
How to sort queryset by another table's record count in Django
I have a Product table and order table the Product table record product info,and the Order table record customer's purchases records Now I want to get the products queryset and sort by the store with the most purchases in a customer's order history Product Model id product_name store_id store_name price ..... 1 iPhone 14 1 Amazon 100 ..... 2 iPhone 14 2 Shopee 1 ..... 3 iPhone 12 3 Taobao 100 ..... 4 iPhone 13 1 Amazon 80 ..... 5 iPhone 14 3 Taobao 100 ..... Order Model id product_id customer_id customer_name 1 1 1 Mike 2 2 1 Mike 3 4 1 Mike 4 1 2 Jhon 5 3 3 Simon in my case,I want to get the product's queryset and sort by the store with the most purchases in a customer's order history For example: when customer_id is 1(Mike),the product queryset should be like below because Mike have spent the most times on Amazon, so the ordering of products should put Amazon's products first id product_name store_id store_name price ..... 1 iPhone 14 1 Amazon 100 ..... 4 iPhone 13 1 Amazon 80 ..... 2 iPhone 14 2 Shopee 1 ..... 3 iPhone 12 3 Taobao 100 ..... … -
How to get logged in user ID and pass to backend or set via backend. Djano, DRF, Vue.js, Djoser
So when a user submits a form via frontend (Vue.js), I want to be able to set the created_by attribute in the backend. What is the best way of achieving this? Views class ProjectView(generics.RetrieveAPIView): queryset = Project.objects.order_by('-created_at') def get(self, request): queryset = self.get_queryset() serializer = ProjectsSerializer(queryset, many=True) return Response(serializer.data) def post(self, request): if request.method == 'POST': serializer = ProjectsSerializer if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) Serializer class ProjectsSerializer(serializers.ModelSerializer): interest_category = serializers.StringRelatedField() class Meta: model = Project fields = ( 'project_title', 'project_description', 'interest_category', 'created_by', 'created_at', 'updated_at', ) The data I am passing from Frontend project_title: this.project_title, project_description: this.project_description, interest_category: this.interest_category, I do have a token saved in localStorage, but I do not know how to get the ID of the currently logged in user id and pass to backend or set in backend. Any and all help is greatly appreciated! What is the best way of setting created_by the submitting/requesting user in the backend? -
Building a custom canonical url in python
I want to build a canonical url for my website: my.com here are the requirements: always include www subdomain always use https protocol remove default 80 and 443 ports remove trailing slash Example: http://my.com => https://www.my.com http://my.com/ => https://www.my.com https://my.com:80/ => https://www.my.com https://sub.my.com/ => https://sub.my.com https://sub.my.com?term=t1 => https://sub.my.com?term=t1 This is what I have tried: from urllib.parse import urlparse, urljoin def build_canonical_url(request): absolute = request.build_absolute_uri(request.path) parsed = urlparse(absolute) parsed.scheme == 'https' if parsed.hostname.startswith('my.com'): parsed.hostname == 'www.my.com' if parsed.port == 80 or parsed.port == 443: parsed.port == None # how to join this url components? # canonical = join parsed.scheme, parsed.hostname, parsed.port and parsed.query But I don't know how to join these url components? -
How to set user that submits on frontend to DRF API
So when a user submits a form via frontend (Vue.js), I want to be able to set the created_by attribute in the backend. What is the best way of achieving this? Views class ProjectView(generics.RetrieveAPIView): queryset = Project.objects.order_by('-created_at') def get(self, request): queryset = self.get_queryset() serializer = ProjectsSerializer(queryset, many=True) return Response(serializer.data) def post(self, request): if request.method == 'POST': serializer = ProjectsSerializer if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) Serializer class ProjectsSerializer(serializers.ModelSerializer): interest_category = serializers.StringRelatedField() class Meta: model = Project fields = ( 'project_title', 'project_description', 'interest_category', 'created_by', 'created_at', 'updated_at', ) The data I am passing from Frontend project_title: this.project_title, project_description: this.project_description, interest_category: this.interest_category, What is the best way of setting created_by the submitting/requesting user in the backend? -
Password reset confirm page not loading
I am building the reset password page, the first page where the users enter his email work fine, he receive the reset password email with success. The problem it with the page where the user actually write his new password. When I click on the link / go to the page it give me this error: assert uidb64 is not None and token is not None # checked by URLconf I am following this docs here: https://docs.djangoproject.com/en/1.8/_modules/django/contrib/auth/views/ here is my views.py @sensitive_post_parameters() @never_cache def password_reset_confirm(request, uidb64=None, token=None, template_name='users/password_reset_confirm.html', token_generator=default_token_generator, set_password_form=SetPasswordForm, post_reset_redirect=None, current_app=None, extra_context=None): """ View that checks the hash in a password reset link and presents a form for entering a new password. """ UserModel = get_user_model() assert uidb64 is not None and token is not None # checked by URLconf if post_reset_redirect is None: post_reset_redirect = reverse('password_reset_complete') else: post_reset_redirect = resolve_url(post_reset_redirect) try: # urlsafe_base64_decode() decodes to bytestring on Python 3 uid = force_text(urlsafe_base64_decode(uidb64)) user = UserModel._default_manager.get(pk=uid) except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist): user = None if user is not None and token_generator.check_token(user, token): validlink = True title = ('Enter new password') if request.method == 'POST': form = set_password_form(user, request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(post_reset_redirect) else: form = set_password_form(user) else: validlink … -
Select2 on explicit through model in Django admin
Using autocomplete_fields/search_fields in Django's admin works well to cause a Select2 widget to be used for a ForeignKey field, but I'm getting an error when I set things up to have Select2 widgets rendered on a declared through model in a ManyToManyField relationship. My models are different than the following, but using the example from the Django docs where through models in the admin are discussed as a starting point, I have things set up something like this (the example in the docs has an implicit through model, but I have an explicitly declared through model): class Person(models.Model): first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership', related_name='groups') class Membership(models.Model): person = models.ForeignKey('Person', ...) group = models.ForeignKey('Group', ...) and in admin.py: class PersonAdmin(admin.ModelAdmin): inlines = [MembershipInline,] search_fields = ('first_name','last_name,) class MembershipInline(admin.TabularInline): model = Membership autocomplete_fields = ('person',) class GroupAdmin(admin.ModelAdmin): inlines = [MembershipInline,] When I go to the GroupAdmin and try to create a membership, the Select2 widget is rendered, but when I try to look up a person, I get this error: Forbidden (Permission denied): /admin/autocomplete/ Traceback (most recent call last): File "/virtualenvs/my_virtualenv/lib/python3.8/site-packages/django/utils/datastructures.py", line 84, in __getitem__ list_ = super().__getitem__(key) KeyError: 'app_label' During handling … -
Django set/list/array + indexed?
I want to add a SET type column to my Django model. Seems like I can add it with SetTextField(). When I run my Django migrations, I get a longtext column instead of the MySQL set type. db_index=True is ignored. If I try to add an index through the Meta class then it complains with MySQL 1107. Basically, I need something where I can quickly look up if a set contains a string. I.e. check if abc,def contains def, obviously accounting for the commas. Also need to be able to add/remove, although I might get away with just setting a new list. The docs say SetTextField is deprecated and to use JsonField, which I can do and store as [ 'abc', 'def' ], but would I be able to have an index on whether or not "def" is in the list? -
Why isn't my return statement working in react?
I have a piece of code that looks like this: export async function getMyProfile() { try { const response = await Axios.get("http://127.0.0.1:8000/lover/lovers/?jwt=" + token) console.log(myUserId); response.data.forEach(response => { console.log(response.id); if (response.id == myUserId) { console.log("Got response"); return "i hate my life"; } //end if }); } catch (e) { concatBackendSignupErrors(e); return false; } return "fucking die"; } And my console has a record of "Got response" as it should on like 8, but then it prints "fucking die" instead of "i hate my life". AND if I take the return statement that says "fucking die" off, it returns undefined. Why isn't this returning "i hate my life" and how can I fix it? -
Understanding docker compose port wiring for django, react app and haproxy
I came across a docker-compose.yml which has following port configuration: wsgi: ports: - 9090 // ?? Is it by default mapped to host port 80 ?? nodejs image: nodejs:myapp ports: - 9999:9999 environment: BACKEND_API_URL: http://aa.bb.cc.dd:9854/api/ haproxy ports: - 9854:80 I am trying to understand how the port wiring is happening here. nodejs UI app settings needs to specify backend port which is 9854 here. This port is exposed by haproxy setting and is mapped to port 80. I know that wsgi is a django backend app. From its entrypoint.sh (in PS below) and port specification in above docker-compose.yml, I get that django listens to port 9090. But I am unable to get how this port 9090 maps to port 80 (which is then exposed by haproxy at 9854, which in turn is specified in BACKEND_API_URL by nodejs settings). PS: Django wsgi app has following in \wsgi\entrypoint.sh: nohup gunicorn myapp.wsgi --bind "0.0.0.0:9090" And nodejs react app has following in its server.js file: const port = process.env.PORT || 9999; -
MultiValueDictKeyError when trying to send an image from react-native to django
I am building my first react-native app with a Django backend. In order for my app to work properly, I need to upload an image from react-native to Django and then save it to a model. But when I try to send the image, I get "raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'profileImage'." here's my code: frontend const [ sentI, setSentI ] = useState(null) const sendI = (image) => { const formData = new FormData() image_data = { uri : image.uri, name : "profileImage", type : 'image/jpg' } if (image != null){ formData.append( 'profileImage', image_data,) setSentI(formData) console.log('recieved') } console.log(formData) } const showImagePicker = async () => { // Ask the user for the permission to access the media library const permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync(); if (permissionResult.granted === false) { alert("You've refused to allow this appp to access your photos!"); return; } let result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.All, allowsEditing: true, aspect: [4, 3], quality: 1, }); // Explore the result console.log(result); if (!result.cancelled) { await setProfileImage(result); console.log(result.uri); sendI(result); } } const image = () => { fetch(`http://192.168.5.234:8000/home/imagetest/`, { method: 'POST', body: { sentI }, }) .then( res => res.json()) .then( res => { console.log(res) }) .catch( error => console.log(error)) } return ( <View … -
Django website deploy error: Failed building wheel for Pillow, Reportlab in cPanel
I am trying to use xhtml to pdf libray my code is on goddady cpanel. i have tried pip install reportlab pip install xhtml2pdf pip install --pre xhtml2pdf and no one works non of these commands works on the cpanel i am very sad for the errors they are not disappering i tried soo many things only pip install pillow==8.0.0 works copying src/reportlab/fonts/zy______.pfb -> build/lib.linux-x86_64-3.7/reportlab/fonts running build_ext creating build/temp.linux-x86_64-3.7 creating build/temp.linux-x86_64-3.7/src creating build/temp.linux-x86_64-3.7/src/rl_addons creating build/temp.linux-x86_64-3.7/src/rl_addons/rl_accel /usr/bin/gcc -pthread -Wno-unused-result -Wsign-compare -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -I/home/udowyxdf/virtualenv/downloader/3.7/include -I/opt/alt/python37/include/python3.7m -c src/rl_addons/rl_accel/_rl_accel.c -o build/temp.linux-x86_64-3.7/src/rl_addons/rl_accel/_rl_accel.o error: command '/usr/bin/gcc' failed: Permission denied [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for reportlab Running setup.py clean for reportlab Failed to build Pillow reportlab Installing collected packages: Pillow, oscrypto, lxml, importlib-metadata, html5lib, future, tzlocal, reportlab, cssselect2, click, arabic-reshaper, svglib, pyhanko-certvalidator, pyHanko, xhtml2pdf Attempting uninstall: Pillow Found existing installation: Pillow 8.0.0 Uninstalling Pillow-8.0.0: Successfully uninstalled Pillow-8.0.0 Running setup.py install for Pillow ... error error: subprocess-exited-with-error × Running setup.py install for Pillow did not run successfully. │ exit code: 1 ╰─> [130 lines of output] … -
Suggestions on using SQLAlchemy with a large vendor oracle database?
We are upgrading a custom application from PHP to Python / Django / SQLAlchemy. The vendor database it is built on is huge... several thousand tables with 100's of columns, multiple keys, and many layers of dependencies. The PHP application uses OCI and SQL to interact with the database. Database queries can involve as many as 10 tables with complex join conditions, and there are 100s of queries in the application. Trying to create models for all these tables doesn't seem practical. Is it possible to use SQLAlchemy without creating models for all these tables?--just execute the sql directly? -
why pagination is not showing ? django
def allProductCat(request, c_slug=None): c_page = None products_list = None if c_slug is not None: c_page = get_object_or_404(Category, slug=c_slug) products_list = Product.objects.all().filter(category=c_page, available=True) else: products_list = Product.objects.all().filter(available=True) paginator = Paginator(products_list, 6) try: page = int(request.GET.get('page', '1')) except: page = 1 try: products = paginator.page(page) except(EmptyPage, InvalidPage): products = paginator.page(paginator.num_pages) return render(request, "category.html", {'category': c_page, 'product': products}) // Code for Html // <div class="mx-auto"> {% if product.paginator.num_page %} <hr> <div class="text-center"> {% for pg in product.paginator.page_range %} <a href="?page={{pg}}" class="btn btn-light btn-sm {% if product.number == pg %} active {% endif %}">{{pg}}</a> {% endfor %} </div> {% endif %} </div> when i add all these codes pagination doesnt shows up anything when i type the links to next page manually its working perfectly i dont understand whats wrong in this code, also these div doesnt shows anything inside it when i type anything... -
Django-parler fetching translations from the wrong database
I'm a big fan of Django-parler, but I've run into a problem when storing a translated model in two different databases. My model is: class InstrumentFamily(TranslatableModel): primary_key = True translations = TranslatedFields( label=CharNullField(_('Label'), max_length=100, unique=False, null=True,) I have 2 database aliases 'default' and 'test' and my database router directs my model to 'test'. I insert models in both databases by doing this: fam = InstrumentFamily(code=TEST_CODE) with switch_language(fam, 'en'): fam.label = "test_family_test EN" with switch_language(fam, 'fr'): fam.label = "test_family_test FR" fam.save() which stores the object and its translations in database 'test', or by doing this: fam = InstrumentFamily(code="TEST_FAM") with switch_language(fam, 'en'): fam.label = "test_family_default_EN" with switch_language(fam, 'fr'): fam.label = "test_family_default_FR" fam.save(using='default') which saves the object and its translations to database 'default'. So far, so good. But when accessing the object previously saved in 'default' by doing this (after properly clearing all caches to force a database read): fam = InstrumentFamily.objects.using('default').get(code=TEST_CODE) print(f" label: {fam.label}") django-parler properly retrieves the object from database 'default', but looks for the translation from database 'test' ! (SQL trace below, see the very end of each line): SELECT "orchestra_instrumentfamily"."id", "orchestra_instrumentfamily"."code" FROM "orchestra_instrumentfamily" WHERE "orchestra_instrumentfamily"."code" = 'TEST_FAM' LIMIT 21; args=('TEST_FAM',); alias=default SELECT "orchestra_instrumentfamily_translation"."id", "orchestra_instrumentfamily_translation"."language_code", "orchestra_instrumentfamily_translation"."label", "orchestra_instrumentfamily_translation"."master_id" FROM "orchestra_instrumentfamily_translation" WHERE … -
Exclude used items in a one to many relationship
I'm trying to realize this relationship: -A user can have multiple social networks, but each social ONLY ONCE -A social network can have multiple users. I need to avoid a user choose more than one time the same social. Is somethig that has to be done in the model, or later filtering a user choice class Social(models.Model): name = models.CharField(max_length=200) link = models.CharField(max_length=200) def __str__(self): return self.name class Social2User(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) social = models.ForeignKey(Social, null=True, on_delete=models.CASCADE) class Meta: constraints = [ models.UniqueConstraint( fields=['user', 'social'], name='unique_migration_host_combination' ) ] def __str__(self): return self.user.username + '-' + self.social.name class UserInfos(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) bio = models.TextField(null=False) def __str__(self): return self.user.username Thank you -
Django Page Not Found (404) but the current path matched the last one
So.. this is the error: No Category matches the given query. Request Method: GET Request URL: http://127.0.0.1:8000/category/food/ Raised by: blog.views.CategoryArticlesListView This is my view: class CategoryArticlesListView(ListView): model = Article paginate_by = 12 context_object_name = 'articles' template_name = 'category/category_articles.html' def get_queryset(self): category = get_object_or_404(Category, slug=self.kwargs.get('sklug')) return Article.objects.filter(category=category, status=Article.PUBLISHED, deleted=False) def get_context_data(self, **kwargs): context = super(CategoryArticlesListView, self).get_context_data(**kwargs) category = get_object_or_404(Category, slug=self.kwargs.get('slug')) context['category'] = category return context And this is the routing: path('category/<str:slug>/', CategoryArticlesListView.as_view(), name='category_articles') I can't find where I've wronged the code. And the contradictory "Page Not Found" and "the current path matched the last one" is very confusing. -
Using variables across django templates
I have a link in a layout template that another template extends. i want the link to pass in a variable thats in the template that extends the other. I want to pass the name variable in the documentPage template through the editDoc link in the layout template. can anyone think of a way to do this? thanks -
Use Escaped url in Django url regex mismatch
I'm trying to use an escaped url as a re_path variable for an object identifier in my API. The logic to connect the escaped url to an object is there, but I can't figure out why the regex is not matching. In my head, a GET request with the following url /objects/http%3A%2F%2F0.0.0.0%3A3030%2Fu%2F%3Fid%3Dc789793d-9538-4a27-9dd0-7bb487253da1/foo should be parsed into obj = 'http%3A%2F%2F0.0.0.0%3A3030%2Fu%2F%3Fid%3Dc789793d-9538-4a27-9dd0-7bb487253da1' and field = 'foo' for further processing. Ultimately, returning the object and 200. However I am getting a 404 with a very specific Django error that only proliferates when Django unfruitfully iterates through all the paths available. <HttpResponseNotFound status_code=404, "text/html"> (Pdb) response.content b'\n<!doctype html>\n<html lang="en">\n<head>\n <title>Not Found</title>\n</head>\n<body>\n <h1>Not Found</h1><p>The requested resource was not found on this server.</p>\n</body>\n</html>\n' I know the path exists as when I examine the urlpatterns, the path is present: (Pdb) pp object_router.get_urls() [ ... <URLPattern '^(?P<obj>https?[-a-zA-Z0-9%._\+~#=]+)/(?P<field>foo|bar)\/?$' [name='test-detail-foobar']> ] The url is escaped with urllib.parse.quote(obj.url, safe="") Regexs tried: r"https?[-a-zA-Z0-9%._+~#=]+" r"https?[%23A](www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}(\.[a-z]{2,6})?\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)(?=\/foo)" https://regexr.com/6ue7b r"(https?://(www.)?)?[-a-zA-Z0-9@:%.+~#=]{2,256}(.[a-z]{2,6})?\b([-a-zA-Z0-9@:%+.~#?&//=]*)