Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Performance of a Query in Django
I want to know some information about this particular query: case_insensitive_username = User.objects.filter(email__iexact=username).first() is there a way to know how many queries it executes on the background? How can I test the performance of this query? I mean, execution time, memory. Thanks in advance. -
Remove sqlite3 table from django project
when I try to make migrations I am getting the following error: django.db.utils.OperationalError: table "main_todolist" already exists This tablet is throwing an error and I dont want to use the table anyways, I am trying to get delete it or at least stop the error. Any suggestions? The more simple the solution the better, I am new to this. Ive seen that I may need to access the dbshell however I also get the error " You appear not to have the 'sqlite3' program installed or on your path". Ive tried appending \sqlite3 to the end of my path but to be honest I am not really sure how to append the path. Any help would be great, thank you. -
Django ORM . How to make right query to get all posts for Follow model
I have this Following-Follower model: class Follow(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='follower') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='following') created = models.DateTimeField(auto_now_add=True, db_index=True) class Meta: unique_together = ['user', 'author'] ordering = ('-created',) def __str__(self): return f'{self.user} follows {self.author}' and I'm getting posts in view like this: user_list = request.user.tracking.all() post_list = Post.objects.filter(author__in=user_list).order_by('-pub_date') Do you know a better way how to do it? (In one-line and less number of requests to database ) Thank you a lot! -
How to add notifications in django admin backend with audio
I found this blog that addresses the task I want to accomplish which is; being able to get real time notifications in django admin (backend alerts) every time a new order in placed on an ecommerce website. However the blog is dated 2014 and the swamp django repository referenced hasn't been maintained atleast for 4 years ago. Would you recommend I go ahead and deploy using this library because I believe alot has changed since then and I don't want to get into loops of fixing errors which have no updated and maintained documentation. Or do you know of any other library that I could use instead to do such a task. The ultimate objective here would be to even have an audio sound/notification play everytime a new order is placed or cart has been emptied. Thanks. -
How to add data to specific user and show in specific page?
I want to add data according to user specific logged in. I am stucked in how to do that this is my code below. views.py [My actual code to add data] def addintro(request): form = AboutForm() if request.method == 'POST': form = AboutForm(request.POST,request.FILES) if form.is_valid(): form.save() return redirect('addintro') total=About.objects.all() context = { 'form':form, 'total':total, } return render(request, 'Backend/aboutme/Intro/add-intro.html', context) I tried this method and it is working But I want to pass my form in this code.Can I pass my form in this code? def addintro(request): if request.method == "POST": data = request.POST['data'] new = About(description=data, author=request.user) new.save() return render(request, 'Backend/aboutme/Intro/add-intro.html') else: return render(request, 'Backend/aboutme/Intro/add-intro.html') forms.py class AboutForm(forms.ModelForm): class Meta: model = About widgets = { 'description': SummernoteWidget(attrs={'summernote': {'width': '100%', 'height': '400px'}}), } fields = '__all__' models.py class About(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE,null=True,blank=True,related_name='+') description=models.TextField("Write About You",null=True,blank=True) image=models.ImageField(null=True,blank=True) -
Can't make migrations of my django deployment app
My app is deployed with gunicorn+nginx and it worked fine before I started to make migrations today. Now the app is running (by the way, I don't know why it's working) but i can't go to the Admin page, I get an error after login (I made DEBUG=True to understand what's happening): ProgrammingError at /admin/login/ relation "auth_user" does not exist LINE 1: ...user"."is_active", "auth_user"."date_joined" FROM "auth_user... What I did before this: After a couple of failed migration attempts, I dropped my database and created it again with the same name. Then rm -rf <app>/migrations/ Then I try: python3 manage.py migrate --fake get this: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... FAKED Applying auth.0001_initial... FAKED Applying admin.0001_initial... FAKED Applying admin.0002_logentry_remove_auto_add... FAKED Applying admin.0003_logentry_add_action_flag_choices... FAKED Applying contenttypes.0002_remove_content_type_name... FAKED Applying auth.0002_alter_permission_name_max_length... FAKED Applying auth.0003_alter_user_email_max_length... FAKED Applying auth.0004_alter_user_username_opts... FAKED Applying auth.0005_alter_user_last_login_null... FAKED Applying auth.0006_require_contenttypes_0002... FAKED Applying auth.0007_alter_validators_add_error_messages... FAKED Applying auth.0008_alter_user_username_max_length... FAKED Applying auth.0009_alter_user_last_name_max_length... FAKED Applying auth.0010_alter_group_name_max_length... FAKED Applying auth.0011_update_proxy_permissions... FAKED Applying sessions.0001_initial... FAKED python3 manage.py makemigrations myapp Migrations for 'myapp': myapp/migrations/0001_initial.py - Create model table1 - Create model table2 - Create model table3 - Create model table4 python3 manage.py migrate --fake-initial Operations to perform: Apply all migrations: … -
How to retrieve the Django model (Database table) data to inline Javascript in template file?
There are tags (string names ) available in Tag model associated with database table. I need to bring them into javascript code in my html page.I am using some snippet code from Django documentation https://docs.djangoproject.com/en/3.0/topics/serialization/ from taggit.models import Tag from django.core import serializers def myView(request): js_data = serializers.serialize('xml', Tag.objects.all()) return render(request,'qanda/askyourquestion.html',{'tags':js_data}) Please let me know your inputs. I can't find any solution to this on latest Django version. I am currently using django 3.X. -
Django map image not found or not show
I am making Django project where i have use map widgets for the location and field id PointField but the map image not show model.py name = models.CharField(max_length=200, serialize=True) Shop_category = models.CharField(max_length=200, null=True, choices=CATEGORY) address = models.CharField(max_length=200, null=True) Shop_location = models.PointField() form.py class shopform(forms.ModelForm): class Meta: model = Shop fields = '__all__' widgets = { 'Shop_location': GooglePointFieldWidget, }**views.py** def shopview(request): context = {} form = shopform(request.POST or None) if form.is_valid(): form.save() context['form'] = form return render(request, "forms.html", context) form.html <!DOCTYPE html> {% csrf_token %} {{form.media}} {{form.as_p}} <button type="submit" value="Submit">Submit</button> -
how to join tables in Django ORM
I am trying to join 3 tables of postgresql in the form of queryset using django orm. The tables are defined as follows class a(models.Model): a_id = models.AutoField(primary_key=True) a_f = models.IntegerField() a_p = models.IntegerField() a_ms = models.ForeignKey(ms, on_delete=models.CASCADE, default=None, null=True) class Meta: db_table = 'a' class ms(models.Model): ms_id = models.AutoField(primary_key=True) ms_year = models.IntegerField() ms_month = models.IntegerField() ms_isconfirmed = models.BooleanField(default=False) ms_user_id = models.IntegerField() ms_st = models.ForeignKey(st, on_delete=models.CASCADE, default=None, null=True) class Meta: db_table = 'ms' class st(models.Model): st_id = models.AutoField(primary_key=True) st_name = models.CharField(max_length=100) class Meta: db_table = 'st' now I want to get st_name,ms_year,a_f for my requirement. I can able to write individual queries but couldn't able to join all of them to get into one table or one queryset. b = ms.objects.all().values('ms_id', 'ms_year') \ .filter(ms_id__in=st.objects.all().values('st_id')).filter(ms_year=2020) c = a.objects.all().values('a_f').\ filter(a_ms_id__in=ms.objects.all().values('ms_id')) I defined tables in models.py and wrote queries in views.py. Can someone guide me how to do this join operation in django orm? -
passing variable through urls but returned NoneType django
hey guys i am trying to make a website with Django that intergrate with mikrotik api but i kind of confused right now cus it seems that when i try to pass the variable (the api) through the url it returned a none type variable can anyone give me explanation and help me why it return that? (and sorry English with my poor English) here is my url urlpatterns = [ path("dashboard/<api>",views.dashboard,name="dashboard"), path("mikrotiklogin",views.mikrotikapi,name="mikrotik"), ] here is my view def api(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] iprouter = request.POST['iprouter'] try: con = routeros_api.RouterOsApiPool(host=iprouter,username=username,password=password,plaintext_login=True) api = con.get_api() return redirect("dashboard/{}".format(api)) except: messages.info(request,"gak bisa login mas") return redirect("mikrotiklogin") else: return render(request,"loginmikro.html") def dashboard(request,api): resource = request.POST.get("api") print(type(resource)) resource_log = resource.get_resource("log") content_log = resource_log.get() resource_user = resource.get_resource("/ip/hotspot/user") content_user = resource_user.get() all_user = len(content_user) total_user = 0 if all_user <= 0: total_user = 0 else: total_user = all_user resource_active_user = resource.get_resource("/ip/hotspot/active") content_user_active = resource_active_user.get() all_user_active = len(content_user_active) total_user_active = 0 if all_user_active <= 0: all_user_active = 0 else: total_user_active = all_user_active return render(request,"dashboard.html",{"content_log":content_log, "content_user_active":total_user_active ,"content_user":total_user}) here's is the error 'NoneType' object has no attribute 'get_resource' Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute 'get_resource' Python Version: 3.7.4 -
Can I deploy the Django Rest Framework project on Firebase?
We are developing an application using Vue.js and Django. The essence of the application: accept user requests from the form, send them for approval to the backend and send an answer to the frontend. On the localhost everything is already organized and working. Now our frontend is on firebase and I want to deploy my backend part somewhere. So, can I use firebase for deploying my part? Вecause I met different ambiguous answers to this question -
Integrating existing Typescript project to Django
I'm in the process of building an application for simple 3D modeling. I would like integrate https://github.com/furnishup/blueprint3d to Django backend on a crud based way. User could create an 3D model etc. Here's an overview of the tree from the existing Django project. └── src ├── architectural │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── db.sqlite3 ├── manage.py ├── memberships │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py └── spaces ├── admin.py ├── apps.py ├── __init__.py ├── migrations │ ├── 0001_initial.py │ ├── __init__.py ├── models.py ├── templates │ └── spaces │ └── space_list.html ├── tests.py ├── urls.py └── views.py Spaces app contains the models for the Space and Property as follows: class Space(models.Model): slug = models.SlugField() title = models.CharField(max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('spaces:detail', kwargs={'slug': self.slug}) class Property(models.Model): slug = models.SlugField() space = models.ForeignKey(Space, on_delete=models.SET_NULL, null=True) thumbnail = models.ImageField() def __str__(self): return self.title Now my question is relatively vague, but I would like to know how would one go about integrating these two. … -
formset with django-reversion data lost
How to store formset value in reversion log. class Foo(models.Model): name= models.CharField(max_length=100, null=True, blank=True) data= models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.name class Bar(models.Model): name= models.CharField(max_length=100, null=True, blank=True) def __str__(self): return self.name table like: name: ______________ add bar: name: _______________ +- name: _______________ +- -
Django not recognizing I have objects in my Model
Having a Model in file MyApp/models/Artwork.py: class Artwork(models.Model): class Meta: verbose_name = _('Artwork') verbose_name_plural = _('Artworks') def __init__(self, *args, **kwargs): super(Artwork, self).__init__(*args, **kwargs) objects = ArtworkManager() And an action in file: MyApp/functions/actions.py from MyApp.models import Artwork import pprint; def lock_artwork(request, id): pprint.pprint(Artwork) try: art = Artwork.objects.get(pk=id) except ObjectDoesNotExist: raise Http404() I get the curious error of not having the attribute objects in my model, which is there. Stacktrace: web_1 | <module 'MyApp.models.Artwork' from '/app/MyApp/models/Artwork.py'> web_1 | Internal Server Error: /en/artwork/lock/2/ web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner web_1 | response = get_response(request) web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response web_1 | response = self.process_exception_by_middleware(e, request) web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response web_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs) web_1 | File "/app/MyApp/functions/actions.py", line 72, in lock_artwork web_1 | art = Artwork.objects.get(pk=id) web_1 | AttributeError: module 'MyApp.models.Artwork' has no attribute 'objects' Something obvious I'm missing? -
How to send pop up message from an app in django to account app in the same django project
I have a django project file. The project contains 2 apps, first app is Account App for staffs or users and the second app is Web-Visitor App. When the Web-Visitor visitor the website, they get to fill a form that contains their details and email or username of one of the staffs/users. Then they submit the form. When they click submit button,a pop up comes up on the web-visitor device showing ("Please wait for response from user") and another pop up comes up on the user's device (if online). The pop up on the user's device shows 3 buttons. The user clicks one of the buttons on the pop up, when the user clicks the button, a message is sent to the web-visitor's pop up, showing some String as message like "The user(name) accept ur request. After this, the details is recorded in database. -
How to use a javascript variable inside django template {%url ...%} when calling an ajax call?
I'm trying to make an ajax call in the django template, but the url parameters are a lot and changing so I put them in an array inside the view.py and I sent it in the return render and when I want to get the url I just put {% url 'detail' first.0 %} or {% url 'detail' first.1 %}. and the problem is I have a button to get the next url and I tried javascript like this var i = 0 {% url 'detail' first."+i+" %} and then i++ but I get TemplateSyntaxError at /Could not parse the remainder: '"+i+"' from 'first."+i+"'. I read that django render the template before javascript is started but I just want to call an ajax call when the button is clicked like this: var request = new XMLHttpRequest(); request.open('GET', "{% url 'detail' first."+i+" %}", true) THANKS A LOT -
Django: how to get parameters value passed in url?
I have a path: path('update/<int:pk>/<int:projet>', UtilisateurUpdateView.as_view(), name='update', ), I want to be able to get value of parameters 'projet' in my UtilisateurUpdateView but don't know how for example, if my url is http://127.0.0.1:8000/project/update/1/8 I would like to be able to recovered 8 corresponding to parameters 'projet' -
Django's displayed datetime is incorrect
models.py from django.db import models # Create your models here. class Topic(models.Model): """A topic the user is learning about.""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Returns a string representation of the model.""" return self.text class Entry(models.Model): """Something specific learned about a topic.""" topic = models.ForeignKey(Topic, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): """Return a string representation of the model.""" if len(self.text) > 50: return f"{self.text[:50]}..." else: return self.text template value {{ entry.date_added|date:'M d, Y g:i' }} In a template, if I display the date_added variable, it seems that the time is 8 hours behind from my computer's time. I tried to change the timezone in settings, but I was met with ValueError: Incorrect timezone setting -
DRF render Django View as response ajax response
Currently working on a project and I'm not sure on how to do what I'm trying to do. I have a 2 django apps: frontend and api. Frontend has views that render an html template with react Api just operates with api requests What I'm trying to do is to do: From a react page located in frontend I send a post request to the api, the data received gets processed and after the output is ready I would like to redirect to a view in frontend app with the output obtained Do you have any idea on how to do it? I've had a look at the DRF documentation and something similar are the DRF renderers, but I don't know how to apply them -
creating dynamic if condition python
I am getting 3 parameters in get request like this first = request.GET.get('first',0) second = request.GET.get('second',0) third = request.GET.get('third' , 0) I just want to include those parameters in If loop who have value greater then 0. like if first and second have value 2,3 respectively my loop will be like if(first and second) ...... -
Django login - do not go register new user
I am using the django default views and url settings for login, logout, password reset and so on - mostly works. However when the user enters invalid login credentials I get a backtrace which starts like this: TemplateDoesNotExist at /accounts/login/ registration/login.html ... My interpretation of this is that the login view wants to redirect me to a user registration page, but I would rather return back to my login page and display an error message. How can I achieve that? -
Validate image resolution in Wagtail before uploading
I am currently creating a page in Wagtail that will allow the client to create a new service that has a title, body and a image. What I am asking is, how would one add a validator onto the image before it uploads to check if the image is bigger than a specific size. So instead of the client being able to upload or select a small image into a header, I can restrict it so the minimum resoltion for that image needs to be 500x500 for example. I have scratched around and havent been able to find anything of that sorts. I found 1 piece of code Here but when I try use that in my code it gives me a error: Field 'id' expected a number but got <Image: industrial.jpg> Here is my page model: class WhatWeDoPage(Page): """ The "What We Do" Page or the Services page. This will be the page where we showing the services GR-Gear is doing. """ template = 'home/services.html' services = StreamField([ ('services', blocks.StructBlock([ ('title', blocks.CharBlock()), ('body', blocks.RichTextBlock()), ('image', ImageChooserBlock(required=False, validators=[ImageValidator(width=500, height=500)])) ], icone='user')) ], blank=True) content_panels = [ FieldPanel('title', classname="full title"), StreamFieldPanel('services'), ] Any help or assistance would be gladly appreciative -
Django Images Not Showing On Production without refreshing server
Hey guys so I made a website for myself using Django and when you want to deploy it, as you know there are some thing you have to do for static file so here is my settings.py STATIC_URL = '/staticfiles/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'staticfiles/uploads')] MEDIA_URL = '/staticfiles/uploads/' MEDIA_ROOT = os.path.join(BASE_DIR, 'staticfiles/uploads') I have no issues with css js etc. The problem is if I upload a picture it saves it to staticfiles/uploads as it should but it doesn't show it right after I upload it, if I stop the server and re-run it then it shows the image. Is there any who could help me with that problem, what's the problem in the first place ? -
Django thread not closing db connections properly
I am trying to multiple threads in my django application, but unfortunately the number of connections to Database are exceeding the limit. The code I have used to close db connections in my application are not working properly, here it is def worker(q): while True: id = q.get() load_data(id) for conn in connections.all(): conn.close() q.task_done() q = Queue() -
Django Redirect to Original Page After Login
so I have a 'Books' webpage where you have the option to log in. After logging in, I'd like the user to be redirected to that 'Books' webpage again instead of the homepage. This is what my login function in views.py looks like: def loginPage(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') # check if user is authenticated user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.info(request, 'Username OR password is incorrect') response = {} return render(request, 'login.html', response) And this what the login button on my Books template looks like: <div class="alert alert-secondary" role="alert"> <h5 class="display-5">Are you not signed in?</h5> <a href="{% url 'login' %}"><button href="{% url 'login' %}" class="btn btn-large waves-effect waves-light grey darken-4">Login</button></a> </div> And this is what the form for the login looks like: <div class="d-flex justify-content-center form_container"> <form method="POST" action=""> --> {% csrf_token %} <div class="input-group mb-3"> <div class="input-group-append"> <span class="input-group-text"><i class="fas fa-user"></i></span> </div> <input type="text" name="username" placeholder="Username..." class="form-control"> </div> <div class="input-group mb-2"> <div class="input-group-append"> <span class="input-group-text"><i class="fas fa-key"></i></span> </div> <input type="password" name="password" placeholder="Password..." class="form-control"> </div> <div class="d-flex justify-content-center mt-3 login_container"> <input class="btn login_btn" type="submit" value="Login"> </div> </form> </div> I've been looking at articles about …