Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CSRF middleware token missing?
I'm novice adapting a simple address book database program using Django from a course I've done on Codemy. I have a page where I enter the names, surnames etc together with a DELETE and EDIT button next to each address. There's no problem when I click the EDIT button (the form populates automatically and takes me to website/edit1,2,3,4 etc/), but when I click the 'edit' button after editing the addressee info, I get the error as below. The btn1 is the name="btn1" of the button as indicated. GET /edit/3?csrfmiddlewaretoken=b4IkMxxxxxxxxxxxDHrDIgRnjvEWr53rL&**btn1**=140 HTTP/1.1" 200 5751 I cannot locate an issue with the CSRF token. it is included just like the tutorial on the edit.html page. Not even sure if the issue is with the token? I've gone through the tutorial time and again and cannot see an issue. I'm a noob, so any info would be great! -
Django signals not returning data when using celery
I have a Django signal which takes the content of some order data and outputs it to a text file on an Azure blob. I have been trying to run the signal using celery and the task executes fine. However the output is not written to the text file. The code works fine if running it solely as a Django signal. For some reason, my queryset doesn't load any data using celery. Please see code below: signals.py @receiver(post_save, sender=Order) def order_fully_paid_signal(sender, instance, created, **kwargs): if instance.get_payment_status() == "fully-charged": order_fully_paid_show.delay(instance.id) print("This signal is working for fully paid order") else: print("This signal won't working for fully paid order") tasks.py @app.task def order_fully_paid_show(instance_id): config_variables = ConfigurationSettings.objects.get(pk=1) azure_container_name = config_variables.config_azure_container_name azure_blob_name = config_variables.config_azure_blob_name azure_account_key = config_variables.config_azure_account_key get_order_items = OrderLine.objects.filter(order_id=instance_id) product_data = [] for item in get_order_items: product_data.append(str(item.quantity) + ';' + item.product_name + ' ' + '(' + item.variant_name + ')' + ';' + str(item.unit_price_net_amount) + ';;;') order_data = ''.join(product_data) block_blob_service = BlockBlobService(account_name=azure_container_name, account_key=azure_account_key) block_blob_service.create_blob_from_text(azure_container_name, azure_blob_name, order_data, content_settings=ContentSettings(content_type='text/plain')) The following code if I just place it in signals works fine: @receiver(post_save, sender=Order) def order_fully_paid_signal(sender, instance, created, **kwargs): if instance.get_payment_status() == "fully-charged": config_variables = ConfigurationSettings.objects.get(pk=1) azure_container_name = config_variables.config_azure_container_name azure_blob_name = config_variables.config_azure_blob_name azure_account_key = config_variables.config_azure_account_key get_order_items = … -
Make 2 ldap calls and populate user django
I can get the user logged in using ldap via built-in django.contrib.auth library and then calling the ldap_backend.populate_user() method to update the db. The problem is that this ldap server returns 90% of the data and the remaining 10% data needs to come from a different ldap server. Let's call it ldap2_server I can call the ldap2_server upon the user successfully but it's not populating the db with the new info. Any pointers would be highly appreciated. Cheers -
uwsgi in virtualenv but attach-daemon for django doesn't get venv
I'm building a django project (mailman3) and accessing it with uwsgi. I have it running successfully when launching uwsgi within the virtualenv from the command line. I'm trying to build a systemd service to manage uwsgi. It successfully loads the virtual environment for uwsgi and runs. But when it tries to run the django process with attach-daemon, manage.py can't find the django module, i.e., it's not picking up the virtual environment. In the /etc/uwsgi.ini file I have: virtualenv = /opt/mailman/venv chdir = /opt/mailman/mailman-suite/mailman-suite_project attach-daemon = ./manage.py qcluster The systemd service has: ExecStart=/opt/mailman/venv/bin/uwsgi --ini /etc/uwsgi.ini When systemd starts the service, my error log reports: [...] WSGI app 0 (mountpoint='') ready in 1 seconds on interpreter 0x558c5945bc30 pid: 15392 (default app) *** uWSGI is running in multiple interpreter mode *** spawned uWSGI master process (pid: 15392) spawned uWSGI worker 1 (pid: 15416, cores: 2) Traceback (most recent call last): File "./manage.py", line 8, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' -
Django cannot locate static files for the index page of the website
So, in my index page located in root/templates/home.html I have the following line for loading CSS: <link rel="stylesheet" href="{% static 'project/home.css' %}"> home.css is located at: root/static/project/home.css In settings.py: STATIC_ROOT = "static/" STATIC_URL = '/static/' And when I run the server, in the main page CSS fails to load raising 404 in the browser although the browser displaying the correct path where the home.css is located: http://127.0.0.1:8000/static/project/home.css For all apps in the projects everything works fine. When global static is defined in settings.py: STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) the problem is solved, but then, for obvious reasons I cannot perform collectstatic unless I rename it to "assets" for example. I am clearly missing something here but I want to know why it fails to load the home.css from the legit path? -
How to add gender to default userform Django
Hello my name is Danijel i am a 16. year computer science student(secondary school). I am doing a django project. Sooo basically i already have a CreateUserForm that is built in. So my code looks like this: forms.py #objekt za ustvajanje formov class CreateUserForm(UserCreationForm): #class meta class Meta: #model je že ustvarjen uporabnik model = User #izberemo katere stvari potrebujemo za registracijo fields = ['username', 'email', 'first_name', 'last_name','gender', 'password1', 'password2'] Views.py def registerPage(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request, 'Račun %s je bil uspešno registriran' %(user)) return redirect('login') context = {'form': form} return render(request, 'accounts/register.html', context) So i have tried to add 'gender' in the list of fields. But it gives me an error. Do i have any other options so i can maybe do it with built in functions? Or do i have to rewrite the whole Class? -
Django Query Using ORM: Delete all Users with No Posts
I'm after Corey Django Tutorial. Given the User model & this Post model: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField(max_length=10000)## was unrestircated date_posted = models.DateTimeField(default=timezone.now)#auto_now_add=True - cant updated author = models.ForeignKey(User, on_delete=models.CASCADE) I trying to delete using the ORM all the users without any Post, but failing. Tried to query all the Users and all the users with posts, and then to difference to get the Users_to_delete, but it raises 'NotSupportedError': Calling QuerySet.delete() after difference() is not supported. How can I delete all the users without any posts ? (Using the Django ORM) Any help will be appreciated ! -
Fetch calls to Django fail in Safari 11
I have a Django Rest Framework app that I am communicating with via the use-http module: const request = useFetch('', { headers: { 'Content-Type': 'application/json', 'X-CSRFToken': Cookies.get('csrftoken'), }, cachePolicy: 'no-cache', credentials: 'include', }) ... request.get('/api/users/status/') .then(res => console.log(res)) .catch(err => console.log(err)) This works perfectly, except in Safari 11 (and mobile Safari 11), where the result is a 403 forbidden error. I am using session authentication, and I have verified that the CSRF token is correct and being sent with the request. However, I did note that the Django sessionid cookie is never set after login. My front end is on the same domain as the back end, with the API accessible via /api/, so I don't believe I should be having CORS issues. I have tried changing the CSRF_COOKIE_SAMESITE and SESSION_COOKIE_SAMESITE Django settings. -
Handling relationships between fields
Here is my model:- class Form(models.Model): name = models.CharField(max_length=100) description = models.TextField() created_on = models.DateTimeField(auto_now_add=True) starts_on = models.DateTimeField() ends_on = models.DateTimeField() def __str__(self): return self.name I want to restrict created_on to be always less than equals to start_on, and similarily ends_on to be greater than equals to starts_on. What are the options available in Django to do this? -
How to sort posts by amount of comments
How to sort Posts by the number of comments and in the response to the GET request and in the response to get in the first place the id of the post with the most comments the answer for example: { post_id : '4', comments: '3' } { post_id:'6', comments:'2' } -
aggregate on many to many in django orm
i want to create a report for sum of duration that a adviser advise on this month. my model : class Adviser(models.AbstractBaseModel): user = models.OneToOneField('accounts.User', on_delete=models.PROTECT, related_name='adviser') patients = models.ManyToManyField('patient.Patient', through='adviser.AdviserPatient', related_name='advisers') class AdviserPatient(models.AbstractBaseModel): adviser = models.ForeignKey('adviser.Adviser', on_delete=models.PROTECT, related_name='adviser_patient') patient = models.ForeignKey('patient.Patient', on_delete=models.PROTECT, related_name='adviser_patient') duration = models.SmallIntegerField() assign_date = models.DateField(auto_now_add=True) release_date = models.DateField(null=True, blank=True) class Patient(models.AbstractBaseModel): user = models.OneToOneField('accounts.User', on_delete=models.PROTECT, related_name='patient') my query : ended_advise_this_mouth = Adviser.objects.annotate( total=Case(When( adviser_patient__release_date__gte=start_of_month(), adviser_patient__release_date__lte=end_of_month(), then=Sum('adviser_patient__duration')), default=Value(0), output_field=IntegerField())) but with this query i get duplicated adviser like that : <QuerySet [<Adviser: [1 None None]>, <Adviser: [1 None None]>, <Adviser: [1 None None]>, <Adviser: [1 None None]>, <Adviser: [1 None None]>, <Adviser: [1 None None]>, <Adviser: [2 vahid imanian]>]> as you see adviser 1 repeat 6 time with separate total . when i use method values('id') or use distinct() not effected in result . my db is mysql and cant use distinct('id'). i need a querysetfor pass serializer please help me to fix this query and is there any way to use django-rest-framework serializers for this queryset? -
Do I have to change a model in Django for type errors?
I have a model in Django which has a field that stores characters like this: class Something(models.Model): some = models.CharField(max_length = 64) I have now decided that I am going to store objects of the type 'bytes' in 'some' and was wondering whether or not I have to change the model type, and if so, to what? -
Django ManyToManyField reverse relationship issues
I have 3 models, Industry has a ManyToManyField to Client and Contact has a ForeignKey to Client. When I go to the django admin, Contact and Industry both display the correct widgets and allow for choosing the relationship and they seem to work. But if I try to access a Client I created, I get this error: TypeError at /admin/project/client/ __call__() missing 1 required keyword-only argument: 'manager' another perhaps error occurs when trying to create a Contact without setting a Client: NOT NULL constraint failed: project_contact.company_id what could be missing in the Client model setup that could be causing these problems? models.py class Client(models.Model): name = models.CharField(max_length=100) class Industry(models.Model): name = models.CharField(max_length=100) clients = models.ManyToManyField('Client', related_name='industries', blank=True) def get_clients(self): return ", ".join([c.clients for c in self.clients.all()]) class Contact(models.Model): name = models.CharField(max_length=100) clients = models.ForeignKey(Client, related_name='contacts', blank=True, on_delete=models.CASCADE) admin.py class ClientAdmin(admin.ModelAdmin): list_display = ['id', 'name', 'contacts', 'industries'] class IndustryAdmin(admin.ModelAdmin): list_display = ['id', 'name', 'get_clients'] class ContactAdmin(admin.ModelAdmin): list_display = ['id', 'name', 'company'] admin.site.register(Client, ClientAdmin) admin.site.register(Contact, ContactAdmin) admin.site.register(Industry, IndustryAdmin) -
Getting this error (Generic detail view QuizView must be called with either an object pk or a slug in the URLconf.)
I am stuck trying to figure out how to fix this error. I know what the error is referring to (path(quizzes)), but I don't understand how to fix it although I tried pk although i may not have done it right. Here is my url.py and models urlpatterns = [ path('JSUMA/', include('JSUMA.urls')), path('admin/', admin.site.urls), path("register/", v.register, name="register"), path('', include("django.contrib.auth.urls")), path("contact/", v.contactview, name="contact"), path("Quizzes/", v.QuizView.as_view(), name="quiz") ] models.py class User(models.Model): first_name = models.CharField(max_length=25) last_name = models.CharField(max_length=25) #password = models.CharField(max_length=25) email = models.EmailField(max_length=100) class Quiz(models.Model): name = models.CharField(max_length=200,primary_key=True) NOQ = models.IntegerField(default=1) class Meta: verbose_name = "Quiz" verbose_name_plural = "Quizzes" def __str__(self): return self.name #number Of Questions class Major(models.Model): major = models.CharField(max_length=200) majorData = models.IntegerField(default=0) answer = models.ManyToManyField('Answer') def __str__(self): return self.major class Question(models.Model): question_text = models.CharField(max_length=400) quiz = models.ForeignKey("Quiz", on_delete=models.CASCADE, null=True) def __str__(self): return self.question_text class Answer(models.Model): question = models.ForeignKey('Question', on_delete=models.CASCADE, null=True) answer_text = models.CharField(max_length=200) def __str__(self): return self.answer_text -
Controlling the styling of BootStrap form in Flask WTForms
I have a form where there are 14 questions, 4 option for each question, 1 correct answer, and a timer field that has to be rendered on the page something like this: Expected form format Help me in understanding and using WTFroms along with bootstrap to make my form look like this: Currently, this is how it looks: Current form format Code for forms.py: class XMLQuestionForm(FlaskForm): question = FieldList(StringField('Question', validators=[DataRequired(), Length(max=395)]), min_entries=14, max_entries=14 ) optionA = FieldList(StringField('Option A', validators=[DataRequired(), Length(max=85)]), min_entries=14, max_entries=14) optionB = FieldList(StringField('Option B', validators=[DataRequired(), Length(max=85)]), min_entries=14, max_entries=14) optionC = FieldList(StringField('Option C', validators=[DataRequired(), Length(max=85)]), min_entries=14, max_entries=14) optionD = FieldList(StringField('Option D', validators=[DataRequired(), Length(max=85)]), min_entries=14, max_entries=14) answer = FieldList(SelectField('Answer', validators=[DataRequired()], choices=[(None,'<Select an answer>'),('Option A','Option A'),('Option B','Option B'),('Option C','Option C'),('Option D','Option D')]), min_entries=14, max_entries=14) timer = FieldList(IntegerField('Timer', default=60), min_entries=14, max_entries=14) submit = SubmitField('Generate XML') Code for home.html {% extends "layout.html" %} {% block content %} <div class="content-section"> <form method="POST" action=""> {{ form.hidden_tag() }} <fieldset class="form-group"> <legend class="border-bottom mb-4">KBC Question XML Creator</legend> {% for n in range(14) %} <!-- Question --> {% if form.question[n].errors %} {{ form.question[n](class="form-control form-control-lg is-invalid") }} <div class="invalid-feedback"> {% for error in form.username[n].errors %} <span>{{ error }}</span> {% endfor %} </div> {% else %} {{ form.question[n].label }} {{ … -
Authorization header field absent in request.headers() and request.META when using Apache, Preflight CORS error when using custom header
I have my Django Rest Framework API's up and running on an AWS EC2 instance. I'm using Apache server and added an SSL certificate using Let's Encrypt to serve the API as HTTPS at Port 443. I'm using a custom token authentication (generating session token using my own random algorithm). This token is random and unique to each user (after the user is logged in), and hence I'm trying to pass it as a header in my POST request (for validation). But here comes the problem. On doing post request from Postman and also from my React frontend, the header is not getting received in both request.headers("Authorization") and request.META["HTTP_AUTHORIZATION"]. Strangely, the field is only absent (as checked from apache error log after printing both). Hence null is getting assigned to token. After a lot of research over the internet, I changed Authorization to Authorization2. That actually fixes the issue and works great but only while making a request through Postman. Whereas, on doing post request from react end, the browser console says: Access to fetch at 'https://www.myapi.live/api/project/add/8/' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field authorization2 is not allowed by Access-Control-Allow-Headers in preflight response. I tried … -
nginx: [emerg] "server_names_hash_bucket_size" directive is not allowed here in /etc/nginx/sites-enabled/django.conf:4 nginx: in AWS EC2
I am getting the above error while deploying my Django application to the AWS EC2 instance. server { listen 80; server_name ec2-34-220-17-196.us-west-2.compute.amazonaws.com; server_names_hash_bucket_size 64; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/AppName/app.sock; } } This is my django.config file in /etc/nginx/sites-available$ route. Please help me out I am stuck here for long while. -
i want to update and view user profile, upload profile also
my view class SignupView(APIView): permission_classes = (permissions.AllowAny, ) def post(self, request, format=None): data = self.request.data name = data['name'] email = data['email'] password = data['password'] password2 = data['password2'] if password == password2: if User.objects.filter(email=email).exists(): return Response({'error': 'Email already exists'}) else: if len(password) < 6: return Response({'error': 'Password must be at least 6 characters'}) else: user = User.objects.create_user(email=email, password=password, name=name) user.save() return Response({'success': 'User created successfully'}) else: return Response({'error': 'Passwords do not match'}) my model class UserAccountManager(BaseUserManager): def create_user(self, email, name, password=None): if not email: raise ValueError('Users must have an email address') email = self.normalize_email(email) user = self.model(email=email, name=name) user.set_password(password) user.save() return user def create_superuser(self, email, name, password): user = self.create_user(email, name, password) user.is_superuser = True user.is_staff = True user.save() return user class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] def get_full_name(self): return self.name def get_short_name(self): return self.name def __str__(self): return self.email i want to create user profile and upload profile also view that profile i want to create user profile and upload profile also view that profile i want to create user profile and upload profile also view that profilei want to create user … -
Django - how to call a parent function in a child model
I have a child model with a Foreignkey ("Objective"), that related to a parent model ("Project") in Django. So the "Project" has many "Objectives". My goal is to divide the amount of one particular objective to the total amount of the Project, computed by the function "total_budget". Hence, I am trying to call the function "total_budget" in the "Objective" model. Is it possible? Is that the best way to do it? Here is my models.py code: class Project(models.Model): model_name = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True, blank=True) current_savings = models.IntegerField() monthly_salary = models.IntegerField() monthly_savings = models.IntegerField() horizon = models.DateField(default='2025-12-31') def save(self, *args, **kwargs): self.slug = slugify(self.model_name) super(Project, self).save(*args, **kwargs) def total_budget(self): #define current date and horizon to compute the number of months until horizon curr_date = datetime.date.today() horizon = self.horizon dates = [curr_date.strftime('%Y-%m-%d'), horizon.strftime('%Y-%m-%d')] start, end = [datetime.datetime.strptime(_,'%Y-%m-%d') for _ in dates] re_mon = (end. year - start. year) * 12 + (end. month - start. month) #budget is equal to the monthly savings times remaining months, plus current savings budget = self.monthly_savings*re_mon + self.current_savings return budget class Objective(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name='objectives') title = models.CharField(max_length=100) amount = models.DecimalField(max_digits=8, decimal_places=0) expiration = models.DateField() isexpensed = models.BooleanField() investable = models.BooleanField() class … -
This backend doesn't support absolute paths
I´m trying to set a path for some json files I have to open with python open() method. Reading documentation I noticed that path method from class Storage in django.core.files.storage must be overrided but I don't know how to override it since I don't know how to store this path. My files are this way App --index_backend ----json -------some_json.json ----index.py --views.py manage.py I'm quite new on Django, so if you need to see some more code, please tell me to upload as much as needed. -
JSON data from django rest framework not being received
What I have been tying to do recently is to send the data from a website that I am creating using django to a mobile app using flutter the thing is that whenever I try to get the data from the rest framework it doesn't return anything in fact when I see the requested being made to the website no message is displayed that it has received the request I do get a message only if I load the page directly, the catch is if I get json data from others websites like randomuser.me/api/ I do get a response and all the data from it, do I have to set anything in special for the rest framework to accept GET requests in which are not directly made by a browser ? I will be providing the settings that I am using for the rest framework right bellow ! Settings.py REST_FRAMEWORK = { "DEFAULT_RENDERER_CLASSES": [ "rest_framework.renderers.JSONRenderer", # "rest_framework.renderers.BrowsableAPIRenderer", ], "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.SessionAuthentication", # Delete this "rest_framework_jwt.authentication.JSONWebTokenAuthentication" # "rest_framework.authentication.BasicAuthentication", ], "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.IsAuthenticated" # Default permission for all apis ], "DEFAULT_PARSER_CLASSES": [ "rest_framework.parsers.JSONParser", ], } As you can see the Is Authenticated is a default permission class but for the page that … -
Python: Checking between times, dates. Validating dates
I'm trying to create some kind of validation for dates. I have these kinds of dates for my API request. "date_from": "2020-11-20T20:11:00Z", "date_to": "2020-11-20T20:12:50Z" date.timestamp() = 1605903600.0 datetime.utcnow().timestamp() = 1605896932.580989 Let's say the current time is 2020-11-20 20:13:00, and I'm still able to create some objects by providing the older time (2020-11-20T20:11:00Z) than the current. I need to check if the date_from is not less than the current time, so I have tried to: def validate_date_from(self, date): if date.timestamp() <= datetime.utcnow().timestamp(): raise serializers.ValidationError("Meeting could not start earlier than the current time") return date But I'm still able to create the objects via API, so that means the validation method isn't working as it should. Secondly, I have this code snippet (below) it should check if the reservation is currently happening, so basically it checks between the start and the end date and if the current time is between the start and the end date, we can know that meeting is active, but unfortunately, it's not working as well. if parse(reservation['date_from']).timestamp() >= datetime.now().timestamp() <= parse(reservation['date_to']).timestamp(): raise serializers.ValidationError("Room is in-use") parse(reservation['date_from']).timestamp() = 1605903060.0 datetime.now().timestamp() = 1605896745.853667 parse(reservation['date_to']).timestamp() = 1605903170.0 -
Condition to check if the user is in the model and to block before re-enrolling
Hi I have a problem with writing a condition that checks if the logged in user is currently on the list of enrolled users and blocks him from re-enrolling, and if he is on the list, it unlocks my access to the tournament transition. this is my views.py file def groups(request, pk): tournament_groups = get_object_or_404(TournamentGroup, pk=pk) tournament_users = TournamentUsers.objects.filter(user_group=tournament_groups) judges = TournamentJudges.objects.filter(user_tournament=tournament_groups.tournament_name) tournament = Tournament.objects.get(tournament_name=tournament_groups.tournament_name) form = TournamentUsersForm() current_user = request.user.debatants if request.user.is_authenticated: form = TournamentUsersForm( initial={'user_tournament': tournament_groups.tournament_name, 'user_group': tournament_groups, 'user_full_name': current_user}) if request.method == "POST": form = TournamentUsersForm(request.POST) if form.is_valid(): form.save() form = TournamentUsersForm() context = {'tournament_groups': tournament_groups, 'tournament_users': tournament_users, 'form': form, 'judges': judges, "tournament": tournament, 'current_user': current_user,} return render(request, 'ksm_app2/groups.html', context) this is my models.py file class TournamentUsers(models.Model): user_full_name = models.ForeignKey(Debatants, on_delete=models.SET_NULL, null=True) user_tournament = models.ForeignKey(Tournament, on_delete=models.SET_NULL, null=True) user_group = models.ForeignKey(TournamentGroup, on_delete=models.SET_NULL, null=True) def __str__(self): return str(self.user_full_name.id) this is my template {% for tournament_user in tournament_users %} {% if current_user.id == tournament_user.user_full_name.id %} <h2>Jesteś już zapisany</h2> {% else %} <h2>Zapisz się jako uczestnik</h2> <form method="post" style="visibility: hidden"><br> <button type="submit" style="visibility: visible!important">Zapisz się</button> {% csrf_token %} <label for="name">Imię i nazwisko</label> {{ form.user_full_name }} <label for="tournament">Wybierz turniej</label> {{ form.user_tournament }} <br> <label for="tournament">Wybierz drużyne</label> {{ form.user_group }} <br> </form> {% … -
How correct use values for group by in Django
today I solve made one thing on ORM Django, simple thing, i have a table with date, url and amount of smth(it's not have sense), i need a GROUP BY, for group all url one type in one, and, after that, i have a result, exactly i have one url, all going good, but when i try yous MAX or MIN, i have same result in both situatin (with max and min), when i try use count i get 1, and it's very strainge. Code: url of query code -
Utilizing Django url resolver vs. re-inventing the request.path parsing wheel
Let's say I had the following array: sub_urls = [ '/', '/<uuid:id>', '/test', '/test/<uuid:id>' ] The URL stings are very similar to what you'd find in Django's urlpatterns my question: can django.url.resolve be used to find the pattern in the sub_urls array given a path string like /test/189e8140-e587-4d5d-ac5c-517fd55c67bc without me having to re-invent the wheel here?