Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I include all my html files in my base.html file in django?
I have a couple of html files in my django project including a base.html file, navbar.html, footer.html, etc. I have included the navbar and footer files in the base file and extended the base file to a home.html file which happens to be my main page. I recently created a courses.html file and would like this page to also be in the main page. I understand I can include it like I did with navbar and footer, but that would mean the courses.html file will be shown everywhere the base file has been extended to, and I don't want this. How can I do this? -
Installing python from source in virtual environment (Ubuntu)
I have a Django project that I want to integrate with Apache. Django development was done with Python3.10 (which is installed in the virtual environment). OS is Ubuntu. I now learned that mod_wsgi and Python3.10 don't play well together (issue link from mod_wsgi project). Sounds like Python 3.10.2 will fix it, but it's not yet available on deadsnakes (which is how I installed it in the virtual environment). I think I have 3 options Try to downgrade to Python 3.8 (I've not done it before and I am worried I'll break other dependencies) Wait for compiled 3.10.2 to be available (not sure how long it takes - can't afford to miss my deadlines) Compile Python from source My question is about 3. I compiled it for the OS, but don't know how to install it within the virtual environment (I tried to look at the make file, but couldn't figure it out). I can use some help on how to install Python3.10.2 within the virtual environment. Or I'll take any advice on how I can move forward (could be a short term solution that would work in production - followed by a longer term solution eventually). -
How can I use my own styling and html code on django forms?
I am quite new to django, and I've been struggling with the concept of form styling in django. I do not want to use any other styling aside my own styling for the forms. How do I do this? By the way, this is my code below. <form id="contact" action="" method="post"> <div class="row"> <div class="col-md-6"> <fieldset> <input name="name" type="text" class="form-control" id="name" placeholder="Your Name" required=""> </fieldset> </div> <div class="col-md-6"> <fieldset> <input name="email" type="text" class="form-control" id="email" placeholder="Your Email" required=""> </fieldset> </div> <div class="col-md-12"> <fieldset> <textarea name="message" rows="6" class="form-control" id="message" placeholder="Your message..." required=""></textarea> </fieldset> </div> <div class="col-md-12"> <fieldset> <button type="submit" id="form-submit" class="button">Send Message Now</button> </fieldset> </div> </div> </form> -
Accessing Database from other location
For my job interview, I got assignment to create CRUD with Django and Postgresql. I created database locally and finished my assignment. Now I have to upload my code to github. The problem is, they asked for some exampled for CRUD. Developer that is reviewing my code obviously can't access my local DB. What can I do to solve this issue? Do I have to upload my DB to cloud (if so what is the best way to do that)? Or is there any other way to resolve this? Thanks in advance -
I need your help about my website structure which written with Django
I need your help about my website structure which written with Django. My website has a posting part. When I am in main page, I want to go post page if only you are authenticated. Thats works now but when I write post part as url https://starofgeeks.com/post it can go directly to the post part without authentication. Can you recommend any structure for this situtation. Main page is starofgeeks -
How to test update form in django
I have a issue in my django project. I have a custom user model and I created update form and register form with ModelForm class for the user model. I wrote a unit test with TestCase class for to test the form but I'm getting __init__() got an unexpected keyword argument 'instance' error message. I couldn't find any solution for the issue. Can anyone help me solve the issue? Form: class UserUpdateForm(forms.ModelForm): class Meta: model = User fields = ('email', 'username', 'first_name', 'last_name') username = forms.CharField( widget=forms.TextInput( attrs={ } ) ) email = forms.EmailField( widget=forms.EmailInput( attrs={ } ) ) first_name = forms.CharField( widget=forms.TextInput( attrs={ } ) ) last_name = forms.CharField( widget=forms.TextInput( attrs={ } ) ) def clean_username(self): username = self.cleaned_data.get('username').lower() try: user = User.objects.exclude(pk=self.instance.pk).get(username=username) except User.DoesNotExist: return username else: raise forms.ValidationError(f"Sorry but {username} was taken already") def clean_email(self): email = self.cleaned_data.get('email').lower() try: user = User.objects.exclude() except User.DoesNotExist: return email else: raise forms.ValidationError(f"Sorry but {email} was taken already") def clean_first_name(self): first_name = self.cleaned_data.get('first_name') first_name = normalize_name(first_name) return first_name def clean_last_name(self): last_name = self.cleaned_data.get('last_name') last_name = normalize_name(last_name) return last_name My unit test: def updateUser(self): user = UserRegisterForm(data) if user.is_valid(): user = user.save() print(user.username) username = 'user1' email = 'user1@gmail.com' first_name = 'user' … -
Using Google Maps API in Django
New to Django. I've been making a web application using Django to show nearby restaurants when the user enters the address. I have all the necessary Google Maps API keys but don't know how to apply them to my code. Can someone help me with this? -
Postgre+Docker+Django OperationalError
I've got an issue with connecting PostgreSQL with Django using Docker. Error: web_1 | django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres" If I don't use Docker (just runserver command in prompt) it looks as it should, no errors. In another project Docker works correctly with this config. My docker-compose.yml: version: '3.8' services: web: build: . command: python bookstore/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db links: - db:db db: image: postgres:14 environment: - POSTGRES_USER= postgres - POSTGRES_PASSWORD= postgres - POSTGRES_DB= postgres My settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432 } } -
python django flexible access control system
I have a need for a flexible system of rights, that is, there is some object and only some users have access to it, they may also have different levels of rights in this object, This is a Backend, that is, a request comes from an authorized user and the server responds with all the objects that this user has access to, there were attempts with Django Rest Framework, but it is very difficult to understand and I did not find examples with Django Access, it is not mandatory to use Django, you can do anything that can solve this problem (Python only) Please tell me which way to look and figure it out! -
Deleting object from the url
I am trying to override delete action in my CategoryViewSet, the build in delete action taked the id of the category DELETE ..category/1/, but I want it to delete by the slug argument DELETE ..category/movie/. I can not figure out how can I withdraw slug field from the url (*args) models.py class Category(models.Model): name = models.CharField( max_length=255, verbose_name='Category Name' ) slug = models.SlugField( unique=True, verbose_name='Slug Name', max_length=50 ) serializers.py class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id', 'name', 'slug') views.py class CategoryViewSet(viewsets.ModelViewSet): queryset = Category.objects.all() serializer_class = CategorySerializer def destroy(self, request, *args, **kwargs): try: slug = args[0] delete_category = Category.objects.filter(slug=slug) self.perform_destroy(delete_category) except Http404: pass return Response(status=status.HTTP_204_NO_CONTENT) urls.py router_v1.register( r'categories', CategoryViewSet ) urlpatterns = [ path('', include(router_v1.urls)) ] -
how to show manytomany field data in json format - django
I'm trying to show manytomany data in json format(without using serializer), here is my models.py class CustomerInvoice(models.Model): customer = models.CharField(max_length=50) items_model = models.ManyToManyField(Item,through='InvoiceItem') created_at = models.DateTimeField(auto_now_add=True) class InvoiceItem(models.Model): item = models.ForeignKey(Item,on_delete=models.CASCADE) invoice = models.ForeignKey(CustomerInvoice,on_delete=models.CASCADE,related_name='invoice') quantity = models.IntegerField() price = models.DecimalField(max_digits=20,decimal_places=2) is it possible to make a look up base on many to many data? something like this : Q(items_model__icontains=query_search) ,and also how to return the M2M data into a json format using values() and json.dumps please? this returns the ID Values('items_model') and this dont work Values('items_model__all') and here is my views.py def invoices_all_lists(request): if request.is_ajax(): query_search = request.GET.get('filter') if query_search: all_item_qs = CustomerInvoice.objects.all() a = [] for i in all_item_qs.items_model.all(): a.append(i.item.name) invoices = CustomerInvoice.objects.annotate( total=Sum((F('invoice__quantity') * F('invoice__price')),output_field=DecimalField(decimal_places=2,max_digits=20)) ).filter( Q(id__icontains=query_search) | Q(seller__username__icontains=query_search) | Q(customer__icontains=query_search)).values( 'id','seller__username','customer','total','created_at','items_model').order_by('-id') else: all_item_qs = CustomerInvoice.objects.all() a = [] for data in all_item_qs: for i in data.items_model.all(): a.append(i.item.name) invoices = CustomerInvoice.objects.annotate( total=Sum((F('invoice__quantity') * F('invoice__price')) ,output_field=DecimalField(decimal_places=2,max_digits=20)) ).values( 'id','seller__username','customer','total','created_at','items_model').order_by('-id') start_from = 0 if request.GET.get('start'): start_from = int(request.GET.get('start')) limit = 10 if request.GET.get('limit'): limit = int(request.GET.get('limit')) data_lists = [] for index,value in enumerate(invoices[start_from:start_from+limit],start_from): value['counter'] = index+1 data_lists.append(value) data = { 'objects':data_lists, 'length':invoices.count(), } return HttpResponse(json.dumps(data, indent=4, sort_keys=True, default=str),'application/json') else: return redirect('invoiceapp:list-all-invoice') can i add this part of the code into the … -
Display items grouped in month together using django regroup
I have a model with following fields examname | month a1 Jan a2 Jan a3 Jan b1 Feb b2 March b3 March I want to display exams in each month grouped in months example Jan : a1 a2 a3 Feb : b1 March: b2 b3 I am using the following queryset def getallexams(request): exams = exam.objects.annotate(month_total=Count('month')).order_by('month') print(exams) context={ "exams" : exams, } return render(request, 'exams/index.html',context) Below is the code I am using to render the template: {% regroup exams by month as month_list %} <div class="accordion" > {% for month in month_list %} {{month.grouper }} # I am not sure how to loop through this month to display each exam {% endfor %} -
django channels realtime total notification
I need realtime total number of notification using django channels. signals.py @receiver(post_save, sender=Notification) def create_notification(sender, instance, created, **kwargs): if created: channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'realtime_order', { 'type': 'notification_count', 'text': Notification.objects.all().count() } ) consumers.py class NotificationConsumer(WebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(args, kwargs) self.room_group_name = None def connect(self): self.room_group_name = f'realtime_order' self.accept() # join the room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name, ) def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name, ) def receive(self, text_data=None, bytes_data=None): async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'notification_count', 'message': Notification.objects.all().count(), } ) def notification_count(self, event): self.send(text_data=json.dumps(event)) Dont know is it the correct procedure. And code is not working. -
DJANGO cant navigate to page using a hyperlink but typing page address works fine
doing a simple django project with 2 apps one for blogs and the other is for users both work fine but i cant navigate using the hyperlink in this page <p> <a href="{% url 'learning_logs:home' %}">Home</a> <a href="{% url 'learning_logs:topics' %}">Topics</a> {% if user.is_authenticated %} Hello, {{ user.username }}. <a href="{% url 'users:logout' %}">logout</a> {% else %} <a href="{% url 'users:login' }">login</a> {% endif %} urls.py in users from django.urls import URLPattern, path from django.contrib.auth.views import LoginView from . import views app_name = 'users' urlpatterns = [ path('login/', LoginView.as_view(template_name='login.html'), name='login'), path('logout/', views.logout_view, name='logout'), ] main urls of project from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('learning_logs.urls', namespace='learning_logs')), path('users/', include('users.urls', namespace='users')), ] error message Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/%7B%25%20url%20'users:login'%20%7D Using the URLconf defined in learning_log.urls, Django tried these URL patterns, in this order: admin/ [name='home'] topics [name='topics'] topics/<topic_id> [name='topic'] new_topic [name='new_topic'] new_entry/<topic_id> [name='new_entry'] edit_entry/<entry_id> [name='edit_entry'] users/ The current path, {% url 'users:login' }, didn’t match any of these. it shows the page if i type /users/login/ in the address bar -
Django: how to get the value inside a querydict?
I have the following querydict: <QueryDict: {'data_dict[user_id]': ['5'], 'data_dict[location]': ['Library'], 'data_dict[item_sold]': ['book']}> I want to get the value by using the key: i.e (x = data_dict.get('user_id') How can I do that? everytime I try to access the querydict it throws errors. -
Update many objects in one query DRF
I need to bulk update ("is_read" = True) Message instanses by given list of ids in one request with this code: {"ids": [11, 4, 7]} Model: class Message(models.Model): text = models.TextField(max_length=500, verbose_name=_("Text")) sender = models.ForeignKey( to=User, on_delete=models.CASCADE, related_name="sender_message", verbose_name=_("User"), ) thread = models.ForeignKey( to="Thread", on_delete=models.CASCADE, related_name="thread_message", verbose_name=_("Thread"), ) created_at = models.DateTimeField(auto_now_add=True, verbose_name=_("Created")) updated_at = models.DateTimeField(auto_now=True, verbose_name=_("Updated")) is_read = models.BooleanField(default=False, verbose_name=_("Is read")) I have this serializer: class MessageIsReadSerializer(serializers.ModelSerializer): class Meta: model = Message fields = ("id", "text", "sender", "is_read") And method in views.py: class MessageIsRead(APIView): permission_classes = (AllowAny,) queryset = Message.objects.all() def put(self, request, *args, **kwargs): id_list = request.data['ids'] instances = [] for item in id_list: obj = self.queryset.filter(id=item) obj.is_read = True instances.append(obj) serializer = MessageIsReadSerializer(instances, many=True) return Response(serializer.data) urls.py urlpatterns = [ path("messages-read/", MessageIsRead.as_view()), ] But as a result of running this query I get an error: AttributeError at /messages-read/ Got AttributeError when attempting to get a value for field `text` on serializer `MessageIsReadSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance. Original exception text was: 'QuerySet' object has no attribute 'text'. What is wrong? -
DRF reverse action url from viewset
I have an issue reversing the URL of ViewSet actions in the DRF my codes are below, I try some methods to reverse URLs but also you can see it's not working for me view.py class Device_API(ViewSet): def list(self, request) -> Response: ... def update(self, request, pk) -> Response: ... def create(self, request) -> Union[Response, Http404]: ... def destroy(self, request, pk) -> Union[Response, None]: ... @ action( detail=False, methods=["GET"], url_path=r"filter/(?P<type>\w+)", url_name="filter_type", ) def filter(self, request, type) -> Union[Response, Http404]: ... @ action(detail=True, methods=["GET"], url_name="data") def data(self, request, pk) -> Union[Response, Http404]: ... urls.py from rest_framework.routers import DefaultRouter, SimpleRouter from .views import Device_API Router = DefaultRouter() app_name = "api" Router.register("device", Device_API, basename="Device") urlpatterns = Router.urls and I try to reverse the URL like below but I get an error view = Device_API() view.basename = "Device" view.request = None url = view.reverse_action('filter') or url = reverse('Device-filter') Error django.urls.exceptions.NoReverseMatch: Reverse for 'Device-filter' not found. 'Device-filter' is not a valid view function or pattern name. I and also tried this url = reverse('api:Device-filter') Error Traceback (most recent call last): File "/home/nova/Documents/projects/webserver/ENV/lib/python3.8/site-packages/django/urls/base.py", line 71, in reverse extra, resolver = resolver.namespace_dict[ns] KeyError: 'api' During handling of the above exception, another exception occurred: Traceback (most recent call … -
Django pass Varibals brack the url
Hi there I'm following a youtube tutorial of Django 3.0 to learn but I'm using Django 4.0 something and in this particular code I'm getting an error the code in getting the error on urlpatterns = [ path('update_order<str:pk>', views.updateorder, name ='updateorder'), ]` the code doesn't give me an error urlpatterns = [ path('update_order', views.updateorder, name ='updateorder'),] so if I try to pass any veribals its give me error of "NoReverseMatch at / Reverse for 'updateorder' with no arguments not found. 1 pattern(s) tried: ['update_order/(?P<pk>[^/]+)\\Z']" my views def updateorder(request,pk): form = OrderForm() context = {"form":form} return render(request, 'order_form.html', context) if you need any other information please ask in the comment. Thanks in advance -
Get user input values in a Mathquill environment with a Form
I just started using Mathquill in my Django app. I want to get a user input value from Django.views.py. Until now, I don't have a way to get these input values. E.g in the code below, how do I place the Mathquill expression inside a form such that when a user clicks submit, I get the values of x and y from my views.py <span id="fill-in-the-blank"> \sqrt{ \MathQuillMathField{x}^2 + \MathQuillMathField{y}^2 }</span> <input type="submit"/> <script> var fillInTheBlank = MQ.StaticMath(document.getElementById('fill-in-the-blank')); fillInTheBlank.innerFields[0].latex() // => 'x' fillInTheBlank.innerFields[1].latex() // => 'y' val = $(document.getElementById("fill-in-the-blank")); </script> -
Third Party AP in DRF
Im trying consulting http://ip-api.com/json/ with parameter QUERY,like localhost:8000/api?24.48.0.1 but only received ''"query": [ "This field is required."'' views.py: @api_view() def my_view(request): input = MyInputSerializer(data=request.GET) input.is_valid(True) tp_api = "http://ip-api.com/json{}".format(input.data['query']) response_data = requests.get(tp_api).json() my_serializer = MyOutputSerializer(data=response_data, many=True) my_serializer.is_valid(True) return Response(data=my_serializer.data) Serializers.py class MyInputSerializer(serializers.Serializer): query = serializers.CharField() class MyOutputSerializer(serializers.Serializer): query = serializers.CharField() country = serializers.CharField() Urls.py from django.urls import path from . import views urlpatterns = [ path('api',views.my_view), ] -
Django "o termo '/usr/bin/env python' não é reconhecido como nome de cmdlet..." manage.py [closed]
Estou aprendendo Django e, quando tento rodar o arquivo manage.py, esse erro aparece: /usr/bin/python : O termo '/usr/bin/python' não é reconhecido como nome de cmdlet, função, arquivo de script ou programa operável. Verifique a grafia do nome ou, se um caminho tiver sido incluído, veja se o caminho está correto e tente novamente. No linha:1 caractere:1 /usr/bin/python "c:\Users\mathr\Desktop\Coding Projects\Django\hello_ ... + CategoryInfo : ObjectNotFound: (/usr/bin/python:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException Estou usando uma virtualenv e não mexi em nada no código original do arquivo, apenas dei runserver no terminal. Alguém sabe o que fazer? -
Django MySQL - Setting an index on a Textfield
I have a database of articles that I want to search through. I had been using normal Django ORM to search, which was getting way to slow and then I got to know a little about Indexes in Django. I'm using MySQL and I now know that with MYSQL I cannot put an index field into a TextField as described here in this stack question which I was facing. However in my case I can't change this to CharField. I was reading through the MyQSL Docs which stated MySQL cannot index LONGTEXT columns specified without a prefix length on the key part, and prefix lengths are not permitted in functional key parts. Hence I was of the understanding that since TextField in Django is LONGTEXT for MYSQL, I came across this Django-MySQL package here and thought that using this if I could change the LONGTEXT to a MEDIUMTEXT using this package, this might get resolved. So my updated model I did this class MyModel(Model): ........ document = SizedTextField(size_class=3) However, I still see the same error while applying python manage.py makemigrations django.db.utils.OperationalError: (1170, "BLOB/TEXT column 'document' used in key specification without a key length") How can I go about resolving this? -
How do you pass data into a Django form?
I'm using Django 4.0 and I'm trying to create a web app where the user selects a choice from a dropdown Django form. However, the choices will vary depending on the question and I want the form to be able to adapt to this. This is what I have in forms.py: class QuestionAnswerForm(forms.Form): def __init__(self, q_id, *args, **kwargs): self.q_id = q_id super(QuestionAnswerForm, self).__init__(*args, **kwargs) q_id = self.q_id # this line throws an error question = Question.objects.get(pk=q_id) choice = forms.ChoiceField(choices=get_choices(question)) However, I get the error: name 'self' not defined. I just want to know an easy way to pass the question id to the form so that the get_choices function can then return the choices that need to be displayed on the form. In views.py, the start of my view for the question sets the form in this way: def question_detail_view(request, q_id): print(f"Question id is {q_id}") form = QuestionAnswerForm(request.POST or None, q_id=q_id) -
django admin page disable def response_change
I would like to replace function of save button in admin page. Default is update, but I would like to insert new value to db. models.py class user_with_full_info(models.Model): user = models.ForeignKey(user, on_delete=CASCADE) branch = models.ForeignKey(branch, on_delete=CASCADE) team = models.ForeignKey(team, on_delete=CASCADE) position = models.ForeignKey(position, on_delete=CASCADE) date = models.DateTimeField(default=now) add_button.html {% extends 'admin/change_form.html' %} {% block submit_buttons_bottom %} <!-- hide default save button --> <!-- {{ block.super }} --> <div class="submit-row"> <input type="submit" value="Save" name="_change_position"> </div> {% endblock %} admin.py class UserFullInfoAdmin(admin.ModelAdmin): list_display = ('get_salary_number', 'user', 'branch', 'team', 'position', 'get_active') change_form_template = "information/user_button.html" def response_change(self, request, obj): if "_change_position" in request.POST: user_with_full_info.objects.create( user = user.objects.get(id = request.POST['user']), branch = branch.objects.get(id = request.POST['branch']), team = team.objects.get(id = request.POST['team']), position = position.objects.get(id = request.POST['position']) ) return HttpResponseRedirect(".") return super().response_change(request, obj) This code is working fine with insert new value, BUT it's always update the selected value too. How can I disable IS_POPUP_VAR in response_change function to not update selected value. -
Using OAuth in an Android app with custom
I am developing an Android app with a REST API. The REST API needs authentication for security. I would like to use Google's OAuth2 provider since I the client will be on Android. I don't want to store passwords myself. I'm trying to understand how the flow should work at a conceptual level. Authenticate to OAuth2 services describes how to get an OAuth token in the Android app. But then what? Do I need a route that accepts this token? I am implementing the API with Django and Django Rest Framework. I found python-social-auth to implement OAuth flows for the API. It works great when I test manually in a browser going to http://localhost:8000/social/login/google-oauth2/. When I request that URL with a HTTP client, it returns HTML for a Google login page. In the Android app, should I load that in a WebView? And then what? That doesn't seem quite right to me since I'd rather use the Android OAuth API that I linked earlier. What am I missing here and how do I solve this?