Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Remove data from postgres using html.Button
I created a generatable charts that saved in postgresql. And I added some buttons like a delete button for every charts. It look like this I use for loop to create the charts and append it. How can I use the delete button? I tried to create another callback, if I click the other delete button it's printing "None" but, if I click the last one it's printing "1". Is there another solution? If I clicked the delete button, get the value of dcc.input which is the ID from the postgresql and then call the charts model ChartsModels().objects.get(id=value of dccinput).delete() I'm open with any suggestion to improve my work. app.layout = html.Div(id='graphs', children=[ ]) @app.callback(Output('graphs', 'children'), Input('graphs', 'children')) def update_extend_traces_traceselect(child): app.layout = html.Div(id='graphs', children=[ ]) @app.callback(Output('graphs', 'children'), Input('graphs', 'children')) def update_extend_traces_traceselect(child): i = 0 for b in barData: fig = go.Figure() fig.add_trace( go.Bar( x=[d['value'] for d in y][0], y=newdatetime, name=barname[i], marker_color=barcolor[i], orientation=orientation[i], marker_line_color=markerlinecolor[i], marker_line_width=float(markerlinewidth[i]) )) else: fig = go.Figure() fig.add_trace( go.Bar( y=[d['value'] for d in y][0], x=newdatetime, name=barname[i], marker_color=barcolor[i], orientation=orientation[i], marker_line_color=markerlinecolor[i], marker_line_width=float(markerlinewidth[i]) )) fig.update_layout( # barmode=barmode[i], xaxis_title=xtitle[i], yaxis_title=ytitle[i], title=title[i], showlegend=ast.literal_eval(showlegend[i]), xaxis_showgrid=ast.literal_eval(showgrid[i]), yaxis_showgrid=ast.literal_eval(showgrid[i]), xaxis_showticklabels=ast.literal_eval(showticklabels[i]), yaxis_showticklabels=ast.literal_eval(showticklabels[i]) ) child.append(html.Div(id="div-id", children=[dcc.Input( id="charts-id", type="text", value=chart_ID[i] ), html.Button('EDIT', id='edit-chart', style={'margin': '5px'}), html.Button('Delete', id='delete-chart', n_clicks=0, style={'margin': '5px'}), … -
django forms don't show clear image button
I have a Django form modalform. There is an image field in it. The issue is that when the user clicks on the clear image, the image is removed from the models, but when the html file tries to retrieve the image, an error message appears The 'image' attribute has no file associated with it. So I'm planning to remove the clear button from django forms or is there any other best practises? -
I keep getting this Syntax Error running python manage.py runserver
I am using Django with Twitter API to make a Twitter app. I am running it using python3.7 and pip 22.0.4 in a python venv. I get this error when trying to run python manage.py runserver Traceback (most recent call last): File "/usr/local/Cellar/python@3.7/3.7.14/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/usr/local/Cellar/python@3.7/3.7.14/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/arthuruwalaka/Documents/TwitterProject/TwitterApp/app/backend/twitter_env/lib/python3.7/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/arthuruwalaka/Documents/TwitterProject/TwitterApp/app/backend/twitter_env/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/Users/arthuruwalaka/Documents/TwitterProject/TwitterApp/app/backend/twitter_env/lib/python3.7/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Users/arthuruwalaka/Documents/TwitterProject/TwitterApp/app/backend/twitter_env/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "/Users/arthuruwalaka/Documents/TwitterProject/TwitterApp/app/backend/twitter_env/lib/python3.7/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/arthuruwalaka/Documents/TwitterProject/TwitterApp/app/backend/twitter_env/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/arthuruwalaka/Documents/TwitterProject/TwitterApp/app/backend/twitter_env/lib/python3.7/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/Users/arthuruwalaka/Documents/TwitterProject/TwitterApp/app/backend/twitter_env/lib/python3.7/site-packages/django/apps/config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Cellar/python@3.7/3.7.14/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 724, in exec_module File "<frozen importlib._bootstrap_external>", line 860, in get_code File "<frozen importlib._bootstrap_external>", line 791, in source_to_code File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/arthuruwalaka/Documents/TwitterProject/TwitterApp/app/backend/twitter_env/lib/python3.7/site-packages/oauth_tokens/models.py", line 160 except (TokenRequestDenied, AccountLocked, LoginPasswordError, WrongAuthorizationResponseUrl), e: ^ SyntaxError: invalid syntax The only additions … -
I'm trying to create a login page in Django with remember me functionality and session management
after the cookie used to save the password has expired the signin functionality stops working can someone help me figureout the problem. If the run the code without the the cookie having an expiry time it works properly but not with.... i have showed the views.py file from django.http import HttpResponse from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth from accounts.models import userData from django.contrib import messages from django.db import connection # Create your views here. def signUp(request): if request.method == 'POST': if request.POST.get('username') and request.POST.get('passwd'): saverecord = userData() saverecord.username = request.POST['username'] saverecord.passwd = request.POST['passwd'] saverecord.save() messages.success(request, 'User Created......!') return redirect('signIn') else: return render(request, 'SignUp.html') def signIn(request): if request.COOKIES.get('cid'): return render(request, 'signIn.html', {'cookie1': request.COOKIES['cid'],'cookie2': request.COOKIES['cid2']}) # if request.COOKIES.get('cid'): # return render(request, 'signIn.html', {'cookie1': request.COOKIES['cid']}) # if request.COOKIES.get('cid2'): # return render(request, 'signIn.html', {'cookie2': request.COOKIES['cid2']}) if request.method == 'POST': if userData.objects.filter(username=request.POST.get('username'), passwd=request.POST.get('passwd')): request.session['uid'] = request.POST.get('username') # messages.success(request, "Login Successful...") if request.POST.get("chk"): response = HttpResponse("User Credentials") response.set_cookie('cid', request.POST['username']) response.set_cookie('cid2', request.POST['passwd']) # response.set_cookie('cid2', request.POST['passwd'], max_age=180) return response return redirect('index') else: messages.success(request, "Invalid User....") return render(request, 'SignIn.html') else: return render(request, 'SignIn.html') def index(request): if request.session.has_key('uid'): return render(request, 'index.html') else: return redirect('signIn') def signOut(request): del request.session['uid'] return render(request, 'signIn.html') -
Netsuite Customer statements
I am looking to send a customer statement from Netsuite to multiple email addresses that I have stored in a custom field in the customer record. Right now it will only send to the primary email on the customer record which can only be 1 email. Is there a way to send to multiple emails when generating the statement for a customer from the statements page? If not, is there a way around this? Thanks. -
Add custom field to admin fields
models.py class Video(models.Model ): embedded_code = models.TextField(blank=False, null=False, default='') This field represents youtube's embedded code. In the form for editing an instance I'd like to have a link to a detail view where I would like to show the video. In other words, I don't want to shoow the video in the admin site, I'd like just to create a link. And it is not about list_display. For that purpose in the model I could organise something like that: def preview(self): href = reverse('vocabulary-videos:detail', kwargs={'pk': self.id}) a = "<a href='{}'>Preview</a>".format(href) return mark_safe(a) Is it possible to show this link in the edit form without substituting the template? -
How to make DRF ordering and filtering work with custom query_params that generated by bootstrap-table extension
I have working version without api, filling table with loop in templates. Works as i need, but because there is thousands rows of data, page loading 5-20 seconds. So i want use server side pagination. Problem is - bootstrap-table script generates url like this for example: /api/parcels/?search=&sort=Size&order=desc&offset=0&limit=25&multiSort[0][sortName]=Price&multiSort[0][sortOrder]=asc&multiSort[1][sortName]=Region&multiSort[1][sortOrder]=asc bootstrap-table.js can sort by single column, also have extension for multiple column sort, and own pagination. Probably best way is to rewrite JS more into format of DRF. But i want do it opposite way, at least to get more experience with DRF. So, i know DRF have own ordering accodring docs: http://example.com/api/users?ordering=account,username ordering_fields = ['account', 'username'] and with ORDERING_PARAM you can change name for query param. But format offered by bootstrap-table.js not fits at all. So question is - is there a way to change DRF ordering according to my needs and which is better way? Just in case, my view and serializer so far. class ParcelViewSet(generics.ListAPIView): serializer_class = ParcelSerializer def get_queryset(self): queryset = Parcels.objects.all() return queryset def list(self, request, *args, **kwargs): queryset = self.get_queryset() serializer = self.get_serializer(queryset, many=True) response_data = { "total": len(serializer.data), "totalNotFiltered": len(serializer.data), 'rows': serializer.data } return Response(response_data) class ParcelSerializer(serializers.ModelSerializer): class Meta: model = Parcels fields = '__all__' -
Django Timer issue
I'm writing a Chess App with Django and Django Channels. The problem I have ran into is this: During the game, each time a player makes a move, the opponent's timer starts to count down. I've managed to achieve this using tasks. The issue is that each time the loop decrements the timer and broadcasts both timers to the clients, it calls the database and saves the current timer value to the model. That happens every second, and I've come to realize that it is a bad practice (saving to the database every second), and it's been causing me some bugs. My question is, what is the correct approach here? I want to keep track of the timers on the backend's side, so for example when it hits zero, I can stop the game, or when a player disconnects, the timer will keep on counting down. async def timer_handler(self, event): moving_color = event['text'] username = self.scope['user'].username consumer_color = self.game_obj.get_color(username) if consumer_color == moving_color: if self.timer_task != None: asyncio.Task.cancel(self.timer_task) self.timer_task = None elif consumer_color == self.opposite_color(moving_color): if self.timer_task == None: self.timer_task = asyncio.create_task(self.timer_countdown(self.opposite_color(moving_color))) else: try: raise Exception("Scheduled a timer task for a timer that's already running") finally: print('self.timer_task:', self.timer_task) async def … -
Pagination django listview
I have to do pagination by 3 items per page,i have this code.When i clicked on the next button, link is changing, but on the page,its not.I tried a few examples from stackoverflow but it doesnt usefull views.py class ShowPost(ListView): model = Posts template_name = 'posts/allposts.html' paginate_by = 3 page_kwarg = 'posts' urls.py urlpatterns = [ path("addpost/", AddPost.as_view(), name='post'), path("all_posts/", ShowPost.as_view(), name='show_post') ] allposts.html <!DOCTYPE html> {% load thumbnail %} <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <ul> {% for object in object_list %} <li>Owner: {{ object.owner }}</li> <li>Phone: {{ object.phone_number }}</li> <li>Title: {{ object.title }}</li> <li>Text: {{ object.text }}</li> <li>Type: {{ object.type }}</li> <li>Price: {{ object.price }}</li> <li>Date: {{ object.created }}</li> <p> {% if object.image %} <img src="{% thumbnail object.image 200x200 crop %}" alt="" /> {% endif %} </p> <hr/> <!-- If object_list is empty --> {% empty %} <li>No objects yet.</li> {% endfor %} <br> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }} <ul style="margin-left: 10px;" class="pagination"> {% if page_obj.has_previous %} <li><a href="?page1">&laquo; first</a></li> <li><a href="?page={{ page.obj.previous_page_number }}">previous</a></li> {% endif %} {% if page_obj.has_next %} <li><a href="?page={{ page_obj.next_page_number }}">next</a></li> <li><a href="?page={{ page_obj.paginator.num_pages }}">last</a></li> {% endif %} </ul> </ul> </body> </html> -
Defining choices outside of model producess fields.E005 error [duplicate]
I have the following code in my models.py: from django.db import models from django.utils.translation import gettext_lazy as _ class Sport(models.IntegerChoices): SWIMMING = 0, _("Swimming") HIKING = 1, _("Hiking") RUNNING = 2, _("Running") class Manufacturer(models.Model): uuid = models.UUIDField(default=uuid4, editable=False) name = models.CharField( max_length=255, help_text="Manufacturer name as displayed on their website", ) url = models.URLField(blank=True) sport = models.PositiveSmallIntegerField(choices=Sport) class OrganisationClass(models.Model): uuid = models.UUIDField(default=uuid4, editable=False) class_name = models.CharField(max_length=64, blank=False) description = models.CharField( max_length=255, blank=False, ) sport = models.PositiveSmallIntegerField(choices=Sport) which produces the FAIClass.sport: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. when I run manage.py check and I don't understand why. I got the idea to do it based on this answer, I'd really appreciate if someone could help. -
django: contol access to pages by many to many relation
I have a problem for block access to not authorized user in specific pages. List of that users is stored in Many to Many model in Project object. Below is models.py class Project(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name="projects_as_owner", null=True) project_managers = models.ManyToManyField(User, related_name="projects_as_pm", blank=True) name = models.CharField(max_length=200) description = models.TextField(blank=True) date_of_insert = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Milestone(models.Model): project_fk = models.ForeignKey(Project, related_name="milestones", on_delete=models.CASCADE) name = models.CharField(max_length=200) description = models.TextField(blank=True) date_of_insert = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name And views.py with class I have problem class NewMilestone(LoginRequiredMixin, generic.CreateView): model = Milestone fields = ['name', 'description'] lookup_url_kwarg = 'p_id' template_name = 'main/new_milestone.html' # ... two functions, that work good, not important here ... def get_queryset(self): qs = super(NewMilestone, self).get_queryset() project = Project.objects.get(id=self.kwargs['p_id']) if(qs.filter(project_fk__owner=self.request.user).exists() or User.objects.filter(id=self.request.user.id).filter(projects_as_pm__id=project.id).exists()): return qs else: return Http404("You are not authenticated to this action") Objective here is here to allow authenticated users (owner and project manager/s) to enter this view and for anybody else show info about declined access. Problem is that, that worked well on checking ONLY ownership. When I added that part about project manager(after 'or') program allows any user to access this view with link. I tried many configuration for that second 'if' statement every single one … -
Django, Docker, Nginx, cant find static file
I just cant wrap my head around how to properly write a nginx.conf file. My nginx container in docker keeps giving me error 2022/10/03 12:33:28 [error] 31#31: *1 open() "/usr/src/app/staticblog/style.css" failed (2: No such file or directory), client: 172.18.0.1, server: , request: "GET /static/blog/style.css HTTP/1.1", host: "localhost:1337", referrer: "http://localhost:1337/profile/login" nginx.conf file upstream blog { server back:8000; } server { listen 80; location /{ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://blog; } location /static/ { alias /usr/src/app/static; } location /media/ { alias /usr/src/app/media; } } I feel like im just writing conf file wrong, but I cant wrap my head around directories in docker and how to properly manage them UPDATE: as @HemalPatel mentioned, I messed some slashes. Now I think I might as well got confused with setting.py file xD STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR / "blog/static/", ] STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') Im so sorry its such a dumb question -
Customize the display to reset password
I would like to customize the view on the password reset process on django, not using the default view, myproject/urls.py from django.contrib.auth import views as auth_view urlpatterns = [ ....... path('', include('django.contrib.auth.urls')), path('reset-password/',auth_view.PasswordResetView.as_view(template_name='account/ password_reset.html'),name=' reset_password'), path('password_reset/done/',auth_view.PasswordResetDoneView.as_view(template_name='account/ password_reset_done.html'),name='password_reset_done'), path('reset/<uidb64>/<token>',auth_view.PasswordResetConfirmView.as_view( template_name='account/password_reset_form.html'),name='passwor_reset_confirm'), path('reset/done/',auth_view.PasswordResetCompleteView.as_view(template_name='account/ password_reset_complete.html'),name='password_reset_complete'), ] password_reset.html {% extends 'layout/base.html' %} {% block content %} <div class="row"> <div class="col s4 offset-s4"> <h5>To reset your password please enter your email</h5> <form method="POST"> {% csrf_token %} {{form}} <button class="btn waves-effect waves-light" type="submit">send </button> </form> </div> </div> {% endblock content %} password_reset_done.html {% extends 'layout/base.html' %} {% block content %} <h2>password reset</h2> <p>We have emailed you a reset link,If you do not receive a message, check your Spam</p> {% endblock content %} password_reset_form.html {% extends 'layout/base.html' %} {% block content %} <div class="row"> <div class="col s4 offset-s4"> <h5>Please enter your new password</h5> <form method="POST"> {% csrf_token %} {{form}} <button class="btn waves-effect waves-light" type="submit">Change </button> </form> </div> </div> {% endblock content %} password_reset_complete.html {% extends 'layout/base.html' %} {% block content %} <p>Your password has been changed. You can go ahead and log in now. <br> <a href="{% url 'account:login' %}">Login</a></p> {% endblock content %} Despite this I still have the default display -
Could not parse the remainder: '()' from 'forloop.counter|add:page_obj.start_index()'
I am trying to use a value 'start_index' from paginator's 'get_page()' object. This is required so my for loop can display id of an element according to the amount of previus elements in earlier pages. When i try to add this value to the forloop counter inside a template i get next error: my view: def openAllOrders(request): orders = cache_getFilteredOrders(request) orders_per_page = 10 paginator = Paginator(orders, orders_per_page) page_number = int(request.GET.get('page', 1)) page_obj = paginator.get_page(page_number) orders_before = (page_number-1) * orders_per_page page_orders = page_obj.object_list tbody_html = getOrdersTable(request, page_orders, orders_before) context = dict(tbody=tbody_html, page_obj=page_obj, type=request.GET.get('type'), date_start=request.GET.get('date_start'), date_end=request.GET.get('date_end'), orders_amount=len(orders),) return render(request, "order.html", context) page_obj.start_index() value in debugger: what am i doing wrong, and how should i add this value to forloop counter correctly? Thanks in advance! -
Share Custom User model between two Django projects (same db)
i have two Django project, sharing the same DB (postgres) The first one is an onboarding project for the users where i store the user data. The second one is the project where all the entities related to the user are. For example project one has only Users, project two has Cars and those two models are going to be related. I want to get the users from the first project and "use" them in the second one. I read some articles on how to do this, it seems that i should recreate the User model on project 2 and fake the migrations but i don't really like this way. I'm new to Django can you please help me understanding the best practice to achieve this? -
change "Delete" label beside can_delete checkbox in inlineformset_factory in django
I have two django models: Customer and Agent. Agent has foreign key to Customer (each customer can have lots of agents). I have this CBV: class CustmerAgentsEditView (SingleObjectMixin, FormView): model = models.Agent template_name = 'customer_agents_edit.html' def get(self, request, *args, **kwargs): self.object = self.get_object(queryset=models.Customer.objects.all()) # object.fields[].label='حذف' return super().get(request, *args, **kwargs) def post(self, request, *args, **kwargs): self.object = self.get_object(queryset=models.Customer.objects.all()) return super().post(request, *args, **kwargs) def get_form(self, form_class=None): return CustomerAgentsFormset(**self.get_form_kwargs(), instance=self.object) def form_valid(self, form): form.save() return HttpResponseRedirect(self.get_success_url()) everything works well. the output have "Delete" checkbox which lets to remove an agent related to customer. label beside this Delete checkbox is Delete. I just want to change it to "REMOVE!!!". also in my forms.py I have just this code: CustomerAgentsFormset = inlineformset_factory(Customer, Agent, fields=('name', 'email', 'phone', 'mobile', 'role', 'customer'),extra= 2, can_delete=True) how can I do??? thanks for your answers. this is what I mean: enter image description here -
How to use Anaconda packages with AWS EB Django app
I am trying to deploy a django application with AWS Elastic Beanstalk, however it is not clear to me, how to use the installed Anaconda packages. I have successfully installed my conda packages using the .config within .ebextensions, however I don't know how to serve them to my django app. I've tried adding them to a .pth file, but still got no module error. files: "/var/app/venv/*/lib/python3.7/site-packages/conda.pth": mode: "000644" owner: root group: root content: | /miniconda3/lib/python3.7/site-packages If you have any link where I can read about, would be appreciated. Thank you -
Django-taggit: how to retrieve all tags filtered by a certain type of posts
I'm building a blog, and I have two status for a post, Published and a Draft. I wanto to display all tags of all published posts using Django-taggit. here's how a get all tags for all kind of posts, Published and Draft in my view: object_list = Post.published.all() tags = Tag.objects.filter() And I want to get only tags for published posts I got stuck, help! -
How can I prepopulate this field in my models? Django
I want that when I try to create a new account, the site_name field is prepopulated with the site that has it for instance, an account under reddit should have a site_name prepopulated with reddit.com already, instead of having to pick from the list of sites here is my class view for account creating an account: class AccountCreateView(LoginRequiredMixin, CreateView): model = Account template_name = "account_new.html" fields = ( "site_name", "username", "password", ) the rest of my views: class HomePageView(ListView): model = Site template_name = "home.html" def get_queryset(self): try: return Site.objects.filter(author=self.request.user) except: return HttpResponse("Login please!") class SiteDetailView(LoginRequiredMixin, UserPassesTestMixin, DetailView): model = Site template_name = "site_detail.html" def test_func(self): obj = self.get_object() return obj.author == self.request.user class SiteDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Site template_name = "site_delete.html" success_url = reverse_lazy("home") def test_func(self): obj = self.get_object() return obj.author == self.request.user class SiteEditView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Site template_name = "site_edit.html" fields = ("siteName",) def test_func(self): obj = self.get_object() return obj.author == self.request.user class AccountDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Account template_name = "account_delete.html" slug_field = "slug_field" slug_url_kwarg = "slug_field" success_url = reverse_lazy("home") class AccountEditView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Account template_name = "account_edit.html" fields = ( "username", "password", ) slug_field = "slug_field" slug_url_kwarg = "slug_field" class SiteCreateView(LoginRequiredMixin, … -
django get an unexpected keyword argument 'slug'
I get error but I can't understand how to fix it: (MainPage.get() got an unexpected keyword argument 'slug') This is my model: class Book(models.Model): title = models.CharField(max_length=256) price = models.IntegerField() category = models.ForeignKey('Category', on_delete=models.PROTECT) created_date = models.DateField(auto_now_add=True) description = models.TextField(blank=True, null=True) count = models.IntegerField(default=0) author = models.ForeignKey('Author', on_delete=models.PROTECT) class Category(models.Model): name = models.CharField(max_length=256) slug = models.SlugField(blank=True, unique=True, allow_unicode=True) created_date = models.DateField(auto_now_add=True) This is my view: class MainPage(View): def get(self, request): books = models.Book.objects.all() return render(request, 'core/index.html', {'books': books}) class CategoryPage(View): def get(self, request): categories = models.Category.objects.all() return render(request, 'core/category.html', {'categories': categories}) This is my urls: urlpatterns = [ path('', views.MainPage.as_view(), name='MainPage'), path('category/', views.CategoryPage.as_view(), name='Category'), path('category/<slug:slug>/', views.MainPage.as_view(), name='BookList')] -
javascript query for 3 dependent cascading drop down for django
I want to design three dependent drop-down menus in Django using javascript. I can design for two variables. Can anyone help me with three variables? Here I am writing code for two variables. $(document).ready(function(){ var $d = $("#d"); var $E = $("#E"); var $options = $E.find('option'); $d.on('change',function(){ $.html($options.filter('[value="'+ this.value +'"]')); }).trigger('change'); }); -
wait for an asyn_task to complete or complete it in background
I have some functions in my Django application, that takes lot of time (scraping using proxies), it takes sometimes more than 30sec and is killed by gunicorn and AWS server due to timeout. and I don't want to increase the timeout value. A solution that came to my mind is to run these functions as a async_task using django-q module. Is it possible to do the following: when a view calls the long function, Run the function in async way if it returns a result in a pre-defined amount of time return the result to user. If not, return an incomplete result and continue the function in the background (The function changes a model in the database) no need to notify the user of changes. -
Using Values after Cast and Replace in Django ORM
Dummy data: field_1 price lot 1 1,333.00 lot 1 348.39 lot 2 98.00 The objective is to add the values of price Since price are strings representing numbers, Cast and Replace are used to remove the thousand comma separator and perform the sum. If I want to make the total sum, it works without any problem: total_price = ( myModel.objects.filter(status='Active', project_id=pid) .annotate( cleaned_total=Replace('price', Value(','), Value('')) ) .annotate(float_total=Cast('cleaned_total', FloatField())) .aggregate(Sum('float_total')) ) total_price output: {'float_total__sum': 1779.39} The problem is that I would like to group the sum, and for that I use .values('field_1') and I would like the result to be something like this: <QuerySet [{'field_1': 'lot 1', 'float_total__sum': 1681.39}, {'field_1': 'lot 2', 'float_total__sum': 98.0}] What I've tried: total_price_grouped = ( myModel.objects.filter(status='Active', project_id=pid) .values('field_1') .annotate( cleaned_total=Replace('price', Value(','), Value('')) ) .annotate(float_total=Cast('cleaned_total', FloatField())) .aggregate(Sum('float_total')) ) But unfortunately that gives me the following result: {'float_total__sum': 1779.39} If I don't use Cast and Replace, the sum is grouped correctly as desired but those values with thousand comma separator are not added correctly: total_price_grouped = myModel.objects.filter(status='Active', project_id=pid).values('field_1').annotate(sum=Sum('price')) How could I do the sum by combining values, replace and cast? -
Django add every user in foreign key model with default values
I have created a Django model with a foreign key from user, I want that all created user before be created in that table with a default value: Models.py from django.contrib.auth.models import User class UserProfiles(models.Model): myuser = models.OneToOneField(User, on_delete=models.CASCADE) userstatus = models.CharField(default='active', max_length=20) Can you help me that I can migrate this table and be created to all users who are registered before? -
Custom url doesn't work in Django for views
I have the following setup in proj.urls.py : urlpatterns = [ path('', admin.site.urls), path('api/v1/prealert/', include('prealert.urls')), ] Then in my app prealert, this is my setup for URLs (prealert.urls.py) , I have : app_name = 'prealert' urlpatterns = [ path('search_holding_certificate/', views.search_housing_certificate_view, name='search-hc') ] This is my view : @csrf_protect def search_housing_certificate_view(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = HousingCertificateSearchForm(request.POST) # check whether it's valid: if form.is_valid(): lot = ManagementByLot.objects.all() customer = form['customer'].value() product = form['product'].value() ware = form['ware'].value() season = form['season'].value() entity = form['entity'].value() url = f"{reverse('admin:prealert_managementbylot_changelist')}?customer={customer}&product={product}" return HttpResponseRedirect(url) # if a GET (or any other method) we'll create a blank form else: form = HousingCertificateSearchForm() return render( request, 'admin/search_housing_certificate.html', {'form': form} ) When I access the view via this URL it doesn't work: http://127.0.0.1:8000/api/v1/prealert/search_holding_certificate/ unless I add on the default Django URL the word admin that's when it works: urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/prealert/', include('prealert.urls')), ] What causes this? Am using Django 4.0.3