Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Got Error while installing mysqlclient in django project on cPanel
Requirements.txt contains: asgiref==3.4.1 Django==3.2.9 django-isbn-field==0.5.3 mysql-connector-python mysqlclient phonenumberslite==8.12.42 Pillow==9.0.1 python-decouple==3.6 python-stdnum==1.17 pytz==2021.3 six==1.16.0 sqlparse==0.4.2 Got error: Error ERROR: Failed building wheel for mysqlclient ERROR: Command errored out with exit status 1: /home/bookbestie/virtualenv/bookbestie/3.8/bin/python3.8_bin -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-nk4wll31/mysqlclient_306f3e44780f440a9c0a625d98f95d89/setup.py'"'"'; __file__='"'"'/tmp/pip-install-nk4wll31/mysqlclient_306f3e44780f440a9c0a625d98f95d89/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-frd2zcuu/install-record.txt --single-version-externally-managed --compile --install-headers /home/bookbestie/virtualenv/bookbestie/3.8/include/site/python3.8/mysqlclient Check the logs for full command output. WARNING: You are using pip version 21.3.1; however, version 22.0.4 is available. You should consider upgrading via the '/home/bookbestie/virtualenv/bookbestie/3.8/bin/python3.8_bin -m pip install --upgrade pip' command. Please help!! what to do. I am beginner first time hosting. I got guide from you will be precious for me. I was browsed other questions posted but not worked. Please help. -
Django Pushing JSON formatted data to TimeLine Google Chart visual - converted date to New Date()
I've seen some posts about this but it's still unclear to me how to get this done. I have a Django application that queries a SQL database. I bring this data in and convert it from a pandas dataframe to a JSON format: tempdata = json.dumps(d, cls=DjangoJSONEncoder) return render(request, 'notes/gantt.html', {'data': tempdata}) JSON looks like this: [["id", "title", "created", "est_completion"], ["3", "Add new Security Group", "2022-04-25", "2022-05-05"]] I tried to pass this into the google chart visual but I'm getting an error: Invalid data table format: column #2 must be of type 'date,number,datetime'. Its my understanding the date format is specific to google charts and needs to be set to new Date(2016, 11, 31) My question is how can i do that? Is there a for loop I have to run? or is there an easier more straightforward way to do it? google.charts.load("current", {packages: ["timeline"]}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var container = document.getElementById("timeline"); var chart = new google.visualization.Timeline(container); var dataTable = google.visualization.arrayToDataTable({{ data|safe }}); var options = { timeline: {showRowLabels: false}, animation: { startup: true, duration: 1000, easing: "in" }, avoidOverlappingGridLines: true, backgroundColor: "#e8e7e7", }; chart.draw(dataTable, options); -
How to render user profile (actual image) instead of filename in a Django form which basically update user-account
I am following a Django course on youtube, and I need a small change in my Django form. The form looks like: html of the form field which I want to change: <div class="form-input"> <label for="id_Avatar">Avatar</label> Currently: <a href="/images/1044-3840x2160.jpg">1044-3840x2160.jpg</a> <br> Change: <input type="file" name="avatar" accept="image/*" id="id_avatar"> </div> So in Avatar Currently: <filename>, I want actual image to display here. So basically I want my template html like this: <div class="form-input"> <label for="id_Avatar">Avatar</label> Currently: <img src="/images/1044-3840x2160.jpg"> <br> Change: <input type="file" name="avatar" accept="image/*" id="id_avatar"> </div> which will display user profile image. I think maybe I need to change my forms.py to generate tag instead if tag but I don't know how to do this. models.py class UserModel(AbstractUser): name = models.CharField(max_length = 90) email = models.EmailField(unique = True) about = models.TextField(blank = True, null = True) avatar = models.ImageField(null=True, default="avatar.svg") USERNAME_FIELD = 'email' and forms.py is: class UserForm(forms.ModelForm): class Meta: model = UserModel fields = ['avatar', 'name', 'username', 'email', 'about'] and in views.py the update function is: def editUserProfile(request): user = request.user form = UserForm(instance=user) if request.method == 'POST': form = UserForm(request.POST, request.FILES, instance = user) if form.is_valid(): form.save() return redirect('chat:userProfileView', uname = user.username) context = { 'form' : form } return render(request, … -
How to show foreign key data values instead of urls in Django api?
I have the following codes in models.py class Tag(models.Model): name = models.CharField(max_length=40) def __str__(self): return self.name class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) likes = models.IntegerField() popularity = models.FloatField() reads = models.IntegerField() tags = models.ManyToManyField(Tag) class User(models.Model): name = models.CharField(max_length=40) def __str__(self): return self.name but in localhost:8000/posts, I found out something weird: those foreign keys are shown as the urls, for example { "url": "http://127.0.0.1:8000/posts/1/", "likes": 3, "popularity": 0.25, "reads": 59, "author": "http://127.0.0.1:8000/users/1/", "tags": [ "http://127.0.0.1:8000/tags/1/", "http://127.0.0.1:8000/tags/2/" ] } So in this case, how can I change the displayed api into something like "author":"Any Name" and "tags": ["tag1","tag2"] instead? -
socket.gethostbyname(host_name) working in terminal but not working in Django?
I am trying to find out my ip using socket library in my Django project using this script. import socket host_name = socket.gethostname() ip_address = socket.gethostbyname(host_name) I get this error: socket.gaierror: [Errno -2] Name or service not known Error is pointing to line ip_address = socket.gethostbyname(host_name). But, I do not get this error while running this same script in terminal. >>> import socket >>> hostname = socket.gethostname() >>> ip = socket.gethostbyname(hostname) >>> >>> ip '192.168.191.5' This is my /etc/hosts #127.0.0.1 localhost #127.0.1.1 softcell-Latitude-3510 # The following lines are desirable for IPv6 capable hosts #::1 ip6-localhost ip6-loopback #fe00::0 ip6-localnet #ff00::0 ip6-mcastprefix #ff02::1 ip6-allnodes #ff02::2 ip6-allrouters I have commented out everything because I want socket to return the System IP. Why is this not working in Django but giving correct output in Terminal? -
Python Import not working at the top of file but works inside function
I was using django and ran into the following problem just wondering why Python acts this way. I was importing a function and I had the import at the top of the file with my other imports and my tests keep failing but my tests passes after I move the import statement to inside the function I was working on. Has anyone encountered such problems ? -
Setting limit on models
How to set limits on models without using any package like django-limits, if the model limit is 4 then only 4 models could be created Models class Post(models.Model): #limit = 4 title = models.CharField(max_length=200, null=True, blank=True) -
The problem that javascript cannot be applied depending on whether the URL parameter is
There are a drop down list (select option) to select whether to is_recruiting, a radio option to select 'Total' or 'Period', and input tag of 'from_date' and 'to_date' to set the date when selecting 'Period'. When the radio option is centered and 'Total' is selected, the date input tag is prevented from being input, and the recruiting option can be selected. Conversely, if the 'Period' is selected, the recruiting option is blocked and the period(from_date & to_date) can be set. <form action="/chart" method="GET"> <select name="is_recruiting" id="is_recruiting" class="ml-4"> <option value="A" {% if is_recruiting == "A" %} selected {% endif %}>A</option> <option value="B" {% if is_recruiting == "B" %} selected {% endif %}>B</option> <option value="ALL" {% if is_recruiting == "ALL" %} selected {% endif %}>ALL</option> </select> <div class="radio" style="display: inline"> <label><input type="radio" name="optionRadios" value="total" {% if option_radio != 'period' %} checked {% endif %}/> Total </label> </div> <div class="radio" style="display: inline"> <label><input type="radio" name="optionRadios" value="period" {% if option_radio == 'period' %} checked {% endif %}/> Period : </label> <input autocomplete="off" class="datepicker" name="from_date" id="fromDate" value={{from_date|default_if_none:''}}> <label> ~ </label> <input autocomplete="off" class="datepicker" name="to_date" id="toDate" value={{to_date|default_if_none:''}}> </div> <button class="btn btn-primary btn-xs mb-1" type="submit">Submit</button> </form> <script> $('input[type=radio][name=optionRadios]').on('click',function () { var chkValue = $('input[type=radio][name=optionRadios]:checked').val(); var recruitingSelect = … -
How to shrink time-series data query in django?
I'm currently working a project on collecting gps time series data, and the interval is very short, every 10th of a second. When I query based on a time range, the query is significantly heavy and too large for making graphs. I've seen good solutions: Annotating queryset with modulus https://stackoverflow.com/a/56487889 or.. another approach using a third party postgresql extension https://stackoverflow.com/a/25212750/12913972 The problem with the first solution is that it's not compatible for all query sizes, for instance a query with very short or long interval. If I want to group incremental rows, considering drastic changes in lat/long coordinates, is there a known way or existing function to do this? Or do I have to create the logic from scratch based on my needs? I'm using django 4.*, postgresql if that helps. Any suggestions is appreciated. Thanks! -
Reverse for 'classroom' with arguments '('',)' not found. 1 pattern(s) tried: ['classroom/(?P<classroom_id>[0-9]+)/\\Z']
I got the error in my django project. Base on what i have searched, the problem seems related to url thingy but my url seems right. My view: def student(request, student_id): student = get_object_or_404(Student, pk=student_id) faculty = Faculty.objects.filter(student=student) course = Course.objects.all() classroom = Classroom.objects.all() return render(request, 'polls/student.html', {'student': student,'faculty': faculty, 'courses':course,'classrooms':classroom}) My templates: {% block body %} <h2>{{ student.fname }} {{ student.lname }}</h2> <h3>Faculty</h3> {% if faculties %} {% for faculty in faculties %} <p><a href="{% url 'faculty' faculty.id %}">{{ faculty.name }}</a></p> {% endfor %} {% else %} <p> </p> {% endif %} <h3>Course</h3> {% for course in courses %} <p><a href="{% url 'course' course.id %}">{{ course.name }}</a> </p> {% endfor %} <h3>Class</h3> {% if classrooms %} {% for class in classrooms %} <p><a href="{% url 'classroom' classroom.id %}">{{ class.name }}</a> </p> {% endfor %} {% else %} <p> </p> {% endif %} </p> {% endblock %} My url: urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name = 'index' ), path('classroom/<int:classroom_id>/', views.classroom, name='classroom'), path('student/<int:student_id>/', views.student, name='student'), path('teacher/<int:teacher_id>/', views.teacher, name='teacher'), path('faculty/<int:faculty_id>/', views.faculty, name='faculty'), path('course/<int:course_id>/', views.course, name='course'), path('create_class/', views.add_class,name = "create_class"), path('', include("django.contrib.auth.urls")), ] Can any django expert help me to see what i do wrong ? -
Django deserializing data with natural keys
I'm having some trouble loading a fixture generated using natural keys. My models are: class ChildNameManager(models.Manager): def get_by_natural_key(self, name): return self.get(name=name) class ChildName(models.Model): name = models.CharField(max_length=64, db_index=True, unique=True) objects = ChildNameManager() def __str__(self): return self.name def natural_key(self): return (self.name,) And class SpecialVideoManager(models.Manager): def get_by_natural_key(self, code): return self.get(code=code) class SpecialVideo(models.Model): code = models.CharField(max_length=32, unique=True, db_index=True) child_names = models.ManyToManyField(ChildName, related_name="special_videos") objects = SpecialVideoManager() def natural_key(self): return (self.code,) I generated a fixture with natural keys that looks like this: [ { "model": "pensum.specialvideo", "fields": { "code": "553076706", "child_names": ["amy"] } }, { "model": "pensum.specialvideo", "fields": { "code": "553072042", "child_names": ["alfred"] } }, { "model": "pensum.specialvideo", "fields": { "code": "553088795", "child_names": ["jhonatan", "jonatan", "jonathan", "yonatan"] } } ] The problem is, when I try to load the fixture it raises the following error: django.core.serializers.base.DeserializationError: Problem installing fixture 'test.json': ["'amy' value must be an integer."]: (testapp.specialvideo:pk=None) field_value was 'amy' -
Profile picture does not update after form submitted in django
I also created UserUpdateForm class which i did not include here and if i try to change my name and email through UserUpdateForm class it works but if try for profile picture it did not works views.py from django.shortcuts import render, redirect from .forms import ProfileUpdateForm def editprofile(request): if request.method == 'POST': p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid(): p_form.save() return redirect('profile') else: p_form = UserRegisterForm(instance=request.user.profile) context = { 'p_form': p_form, } return render(request, 'users/editprofile.html', context) forms.py from django import forms from .models import Profile class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] html template <form class="form" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form__group form__avatar"> <label for="avatar">Upload Avatar</label> <input class="form__hide" required type="file" name="avatar" id="avatar" accept="image/png, image/gif, image/jpeg, image/jpg"/> </div> </form> -
Images are not rendering on Django template from a multi-model view
Problem: I cannot get images to appear on my template plant_detail.html. I think I'm calling on variables incorrectly, but not sure what to change. Context: I created a model PlantImage, that allows me to associate multiple images within my model Plant. I then created a class-based view PlantDetailView to link the two models, PlantImage and Plant together. However, now when I try to display those images in the template plant_detail.html, nothing will appear. How can I get images to appear on my template? I tried reading through the Django documentation, reading articles, and watching youtube videos, but I'm not sure what I'm missing or need to edit. My files: plants/models.py class Plant(models.Model): name = models.CharField(max_length=120) slug = models.SlugField(null=False, unique=True) description = models.TextField() def __str__(self): return self.name def get_absolute_url(self): return reverse("plant_detail", kwargs={"slug": self.slug}) class PlantImage(models.Model): plant = models.ForeignKey(Plant, default=None, on_delete=models.CASCADE) images = models.ImageField(upload_to = 'images/') def __str__(self): return self.plant.name plants/views.py def plant_index(request): plant_objects = Plant.objects.all() context = {'plant_objects': plant_objects} return render(request, 'plants/plant_index.html', context) class PlantDetailView(DetailView): model = Plant template_name = 'plants/plant_detail.html' slug = 'slug' def get_context_data(self, **kwargs): context = super(PlantDetailView, self).get_context_data(**kwargs) context['plant_images'] = PlantImage.objects.all() return context plant_detail = PlantDetailView.as_view() plants/urls.py from django.urls import path from .views import plant_index, plant_detail app_name = … -
can't find where django endpoint redirects to
I am very new to django and I am porting over a flask webapp I made to django. The specific endpoint I am trying to find is the /redirect endpoint's code. The specific problem I am trying to find out where Microsoft/Azure places you once you completed the sign-in process. I want to find out where this endpoint's code is so I can force it to redirect to an endpoint called /closeauth. /closeauth is an html file I made that will do a try block to see if you are using outlook, if you are not using outlook, but are using the web, it will kick you out to the normal / home endpoint. However, if you are using outlook, it will send a message back to the parent webpage to let outlook know that authenciation is succesful, then the parent webpage will try to go to /. To understand what I mean, here is an example in flask with the app.config file and the redirect endpoint which is the exact code I am looking for django: app_config.py: import os REDIRECT_PATH = "/getAToken" app.py for flask example @app.route(app_config.REDIRECT_PATH) def authorized(): try: cache = _load_cache() result = _build_msal_app(cache=cache).acquire_token_by_auth_code_flow( session.get("flow", {}), request.args) … -
Creating Custom Join in Django
I am struggling to create the correct prefetch behavior in Django. Here is the outline of the problem: Each Account has DailyQuotes, updated daily at different times (think snapshot) Need to query all of those DailyQuotes, and only get the most recent quotes for each account Here are the models: class Account(models.Model): name = models.TextField(default="") ... class DailyQuotes(models.Model): account = models.ForeignKey(Account, related_name="quote", on_delete=models.CASCADE) date = models.DateField(default=None) ... Currently the query inside of my view for this looks like: acc_ids = [1,2,3] max_date = DailyQuotes.objects.aggregate(Max("date"))["date__max"] accounts = ( Account.objects.filter(id__in=acc_ids) .prefetch_related( Prefetch( "quote", queryset=DailyQuotes.objects.filter(date=date), ), ) ) # Feed into serializer, etc This works and generates 3 queries: 1 for the max date, 1 for accounts, and 1 for the quotes. The problem with this solution is that if one account has more up to date DailyQuotes, then the other accounts will return no quotes. So I need to get the latest DailyQuotes for each account based on the max date for that account, not all accounts. I have generated the SQL query that does what I want, but turning it into Django code has been giving me issues. I could execute the raw SQL but I would like to keep it … -
How to change HTMX behavior to replace the full web page if form is invalid
If this form submits as invalid, I want to override the htmx and do a HttpRedirectResponse that refreshes the full page instead of just changing the div, #superdiv, contents. <form id="create_form" action="." method="post" hx-post="." hx-target="#superdiv" hx swap="outerHTML"> {{ form }} <button id="button" type="submit">Create</button> </form> I have been attempting to do this in the def post of my views. if form.is_valid(): return self.form_valid(form) else: return HttpResponseRedirect(reverse_lazy("logs:manager_form")) Would this be achieved better using JavaScript? I am trying my best to sticking to learning only vanilla JavaScript for now. Thanks for any help. -
query database to search post in django application
I'm trying to add search bar in my application but I don't know how to query a database to gives the things that user's search for. I want when user search for a user in a post or category in a post of model to shows the result that user search for, like YouTube search and facebook search, How can i do this in django to give me what i want ? this is my model: class Photo(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.CharField(max_length=30,null=True, blank=False) image = CloudinaryField(blank=False, null=False) description = models.TextField(null=True) date_added = models.DateTimeField(auto_now_add=True) phone = models.CharField(max_length=12, null=False, blank=False) price = models.CharField(max_length=30,blank=False) location = models.CharField(max_length=20, blank=False) def __str__(self): return str(self.category) my dashboard: <div class="container"> <div class="row justify-content-center"> <form action="{% url 'search' %}" method="get"> <input class="form-control me-2" type="search" placeholder="Search" aria- label="Search"> <br> <button class="btn btn-outline-success" type="submit">Search</button> </form> </div> </div> <div class="container"> <div class="row justify-content-center"> {% for photo in photos reversed %} <div class="col-md-4"> <div class="card my-2"> <img class="image-thumbail" src="{{photo.image.url}}" alt="Card image cap"> <div class="card-body"> <h2 style="color: yellowgreen; font-family: Arial, Helvetica, sans-serif;"> {{photo.user.username.upper}} </h2> <br> <h3>{{photo.category}}</h3> <h4>{{photo.price}}</h4> </div> <a href="{% url 'Photo-view' photo.id %}" class="btn btn-warning btn-sm m-1">Buy Now</a> </div> </div> {% empty %} <h3>No Files...</h3> {% endfor %} </div> … -
Design question: Is there a Django specific way to select users to receive notifications when a form is submitted?
I have a Django app, and need to send email notifications to certain users at certain points in my processes without adding any external libraries. For example, if any user submits a particular form, I need to send a notification to a specific set of users. I'm thinking to use custom model permissions for each model that relates to a particular form. Then hypothetically add users to unique Authentication Groups that have those particular permissions. Then I would create a Notifier class with a notify_users_by_email method that could accept an authorization group and a reason type. Have each reason type be 1-to-1 with the permissions defined at the model level. Then we can just filter the group to the users in the group and send the email. I would also add a Notifications model, which could be used to record who sent the notifications, who was the intended recipient, send time and the notification reason (again related to permission). In general, is that an appropriate way of going about this, or is there a cleaner way to do this in Django? class Notifier: @classmethod def notify_group_by_email(cls, group_id: int, reason: str): users_in_group = Group.objects.get(id=group_id).user_set.all() for user in users_in_group: cls.notify_user_by_email(user_id=user.id, reason=reason) user … -
Django (Wagtail) template not recognizing page type for if condition
On my wagtail blog, I have a simple model that will be the index page listing different articles, defined in my models.py as: class ArticleIndex(Page): description = models.CharField(max_length=255, blank=True,) content_panels = Page.content_panels + [FieldPanel("description", classname="full")] I have some template tags setup to show categories and tags in the sidebar, which should only activate on the index page, not actual article pages. I have this setup thusly: {% if article_index %} {% categories_list %} {% tags_list %} {% endif %} If I remove the if condition, everything displays as I want, so I know it is not an issue with the template tags. I don't understand why {% if article_index %} is failing, as that's what the page type is. How can I print out what the actual page type is to see where the discrepancy is, or to see why the if condition is failing? -
Django download links only working in new tab
This is driving me crazy, I'm developing a django app and need to provide a download link to a file located in the media folder. If I type the url in a blank tab it works fine, the file is downloaded, but if I click on the link from the website nothing happens. I realize this might be because the url to the file doesn't have the same origin that the website and from what I understood the browser won't allow the download, is this correct? Is there any way around? url of the website (in development): http://localhost:8000/django_app/view_name url of the file: http://localhost:8000/django_app/media/file.ext I've tried the following html href: href="../media/file.ext" download target="_blank" And the following view: def download_file(request): fl_path = settings.MEDIA_ROOT + "\\filename.ext" filename = "file_name" mime_type, _ = mimetypes.guess_type(fl_path) response = HttpResponse(fl, content_type=mime_type) response['Content-Disposition'] = "attachment; filename=%s" % filename return response Nothing happens when I click on the link, no error generated. If I open the link in a new tab it downloads the file normally... Note that I need to be able to change the href link dynamically. Thanks! -
How to restrict access to a template to users based on their department_name
I have below model. Departments, users.. Users are assigned in a department. How can i restrict the access of template based on department_name of a user? For eg : User can view Application Template_1 if department_name == "Computer_Department". Here user belong to "computer" department. User can view Application Template_2 if department_name == "Electrical_Department". Here user belong to "electrical". ******My code are as below models.py class Departments(models.Model): id = models.AutoField(primary_key=True) department_name = models.CharField(max_length=255) # here department name can be computer, electrical etc created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() class Departments(models.Model): id = models.AutoField(primary_key=True) department_name = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager() UserViews.py def bi_powise(request): return render ( request, 'user_template/application_template/bi_powise.html', {}) urls.py path ( 'bi_powise_user', UserViews.bi_powise, name = 'bi_powise_user' ) sidebar_template.html {% url 'bi_powise_user' as bi_powise_user %} <a href="{{ bi_powise_user }}" class="nav-link {% if request.path == bi_powise_user %} active {% endif %}"> <i class="nav-icon fas fa-chalkboard"></i> <p> BI PO-Wise </p> </a> </li> -
Django: Horizontal scaling with a single database
I have a single django instance about to hit its limits in terms of throughput. Id like to make a second instance and start scaling horizontally. I understand when dealing with database read replicas there is some minimal django configuration necessary, but in the instance of only using a single database: is there anything I need to do, or anything I should be careful of when adding a second instance? For the record, I use render.com (it’s similar to heroku) and their scaling solution just gives us a slider and will automatically move an instance up or down. Is there any sort of configuration I need to do with django + gunicorn + uvicorn? It will automatically sit behind their load balancer as well. For reference my stack is: Django + DRF Postgres Redis for cache and broker Django-q for async Cloudflare -
Need to have the correct url path in Django
I am trying to get my django app to point to the correct url in my chatserver/urls.py file. I am getting this error when I start my django app: Using the URLconf defined in chatserver.urls, Django tried these URL patterns, in this order: admin/ join [name='join'] The empty path didn’t match any of these. This is my chatserver/urls.py file: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('chat.urls')), path('admin/', admin.site.urls), ] And this is my chat/urls.py file: from django.urls import path from . import views urlpatterns = [ path('join', views.init, name='join'), ] And here is my app project directory: [1] Can someone help me correct my error? -
How to update a couple element by one request? HTMX
I have a few dropdowns. First one is parent and the second one is child. I mean when I choose value in first dropdowns, the values in second one are getting updated. Also I have one div for result. So when I pick element from the first dropdown second dropdown and values from result div should be updated somehow by HTMX. Here is a primitive schema of code: <div> <div class="grid-container"> <div id="dropdonw-1"> <select> <option value="1" hx-post="/url" hx-swap="innerHTML" hx-target="#dropdonw-2" <---- How to specify a couple of targets? > VALUE </option> </select> </div> <div id="dropdonw-2"> <select></select> </div> </div> <div id="result-div"></div> </div> -
Django 404 error-page not found, how can I solve this problem?
My project is named main, and when I runserver I get this error.Anybody have any clue how to fix this error. Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/detail//3 Using the URLconf defined in movieReview.urls, Django tried these URL patterns, in this order: admin/ [name='home'] detail/<str:slug>/<int:id> [name='detail'] category [name='category'] celebrity [name='celebrity'] category/<str:slug>/<int:id> [name='category-movies'] celebrity/<str:slug>/<int:id> [name='celebrity-movies'] recent-released [name='recent-released'] upcoming [name='upcoming'] accounts/register [name='register'] accounts/profile [name='profile'] accounts/changepassword [name='changepassword'] my-reviews [name='my-reviews'] delete-review/<int:id> [name='delete-review'] ^media/(?P<path>.*)$ accounts/ The current path, detail//3, didn’t match any of these. My settings.py file looks like this... """ Django settings for movieReview project. Generated by 'django-admin startproject' using Django 3.1.2. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', …