Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Login page in python django
Hi i'm just trying to create my login page but i have an error. i want to import the Login View and use the username and password from the admin that i created. i tried this code but i have an error. urls.py from django.contrib import admin from django.urls import path from gomo_websys.views import login_page, home_page from django.contrib.auth.views import LoginView urlpatterns = [ path('' , LoginView, {'template_name': 'login/Login.html'}), path('home/' , home_page, name='home_page'), Login.html {% extends 'base.html' %} {% block head %} <title>Login</title> {% endblock %} {% block body %} <h1>Welcome</h1> <p> You can log in here! </p> <h2>Login</h2> <form method="post"> {% crsf_token %} {{ form.as_p }} </form> {% endblock %} views.py from django.http import HttpResponse from django.shortcuts import render def login_page(request): return render(request, "login/Login.html") i have an error result. -
Django has multiple databases and each database has its own group of applications
I have a group of Django applications need to be placed in its own Postgres database instance Let say I have app1, app2, app3, app4, app5, app6. And I have multiple database instances for them DATABASES = { "default": env.db("DATABASE_URL", default="postgres://postgres:postgres@localhost:5432/th_life"), "analytic": env.db("ANALYTIC_URL", default="postgres://postgres:postgres@localhost:5432/th_life_analytic"), "product": env.db("PRODUCT_URL", default="postgres://postgres:postgres@localhost:5432/th_life_product"), "customer": env.db("CUSTOMER_URL", default="postgres://postgres:postgres@localhost:5432/th_life_customer"), } For sake of simplicity I will give an short example default and customer I need app1, app2, and app3 go to customer database instance class DBRouter(object): def __init__(self): print(f"Customize router") super().__init__() def db_for_read(self, model, **hints): # customer information if model._meta.app_label in ['app1', 'app2', 'app3']: return 'customer' return None def db_for_write(self, model, **hints): if model._meta.app_label in ['app1', 'app2', 'app3']: return 'customer' return None def allow_relation(self, obj1, obj2, **hints): return None def allow_migrate(self, db, app_label, model_name=None, **hints): return True After I tried migrate app1. It is not apply schema to the target database. It goes to default database instance Question: What is the correct way to group my applications to particular database instance? References: I had tried some of them and many of them are outdated or no answers Official docs multiple databases and multiple models in django Django Database router based on user selection django database routing with transactions Dynamic … -
django restframework how to get the filtered queryset
This is an example code. In the real environment there are a lot of query params. views.py class EavValueViewSet(PandasMixin, viewsets.ModelViewSet): serializer_class = serializers.EavValueSerializer queryset = models.EavValue.objects.all() pagination_class = None filter_backends = (filters.DjangoFilterBackend, OrderingFilter, SearchFilter,) search_fields = ('value',) filter_class = EavValueFilter ordering_fields = ('timestamp',) ordering = ('-timestamp',) I searched the value , url is http://localhost:8000/api/eav_value/?search=test , and I want to something then return another Response. How to get the filtered queryset. -
How to Display subcategory under Category in Django?
I have some issue with displaying subcategory under Category in Django, I have already Displayed category but I am unable to display Subcategory under Category, Please Help me to display these Subcategory under category. Here is my Models.py File class WebCategory(models.Model): name = models.CharField(max_length=50, unique=True, verbose_name='Category name') slug = models.SlugField(verbose_name='Slug') title = models.CharField(max_length=165, null=True) metadesc = models.TextField(max_length=165, null=True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = 'WebCategory' def save(self, *args, **kwargs): self.slug = slugify(self.name) super(WebCategory, self).save(*args, **kwargs) def __str__(self): return self.name class WebSubCategory(models.Model): category = models.ForeignKey('WebCategory', related_name='subcategory', on_delete=models.CASCADE, blank=True, null=True, verbose_name='Select category') name = models.CharField(max_length=50) slug = models.SlugField(unique=True, null=True) title = models.CharField(max_length=100, null=True) metadesc = models.TextField(max_length=165, null=True) description = RichTextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = 'WebSubCategory' def __str__(self): return self.name Here is my views.py file def home(request): context = RequestContext(request) category_list = WebCategory.objects.order_by('-created_at')[:5] subcategory_list = WebSubCategory.objects.order_by('-created_at')[:5] context_dict = {'webcat': category_list, 'websubcat':category_list} return render_to_response('home.html', context_dict, context) And here is my header.html file, where i want to diplay category and subcategory <ul class="nav nav-pills" id="mainNav"> {%if webcat %} {% for category in webcat %} <li class="dropdown dropdown-mega"> <a class="dropdown-item dropdown-toggle" href="JavaScript:void()"> {{category.name}} </a> {% if websubcat.webcat %} <ul class="dropdown-menu"> <li> <div class="dropdown-mega-content"> … -
How to not accept one email address for multiple registration accounts in django?
I made a registration page in django but the problem is that it should not accept one email address for multiple accounts. How to resolve this issue? If you need code then let me know. -
How do I implement a toaster message on success function of ajax in django?
I am working on a problem where I have to delete entries from the list. I need tp display a toaster message when item is deleted and I want to remove the deleted element without refreshing? How am I supposed to do it? I have tried a lot of links on the web but none of them worked for me. views.py def centre_delete(request): if request.is_ajax(): id = request.POST.get('id') Centre.objects.get(pk=id).delete() message = "Deleted Successfully" else: message = "Not Ajax" return HttpResponse(message) centre_list.html <script type="text/javascript"> $(document).ready(function() { $(".del").click(function(){ swal(Delete centre?); $.ajax({ type: "POST", url: "/NewApp/centredelete/", data: { 'id': $('#cendel').val() }, success: function () { #what should go here? } }); return false; }); }); </script> <body> {% for c in centres %} <tr> <td>{{ c.name }}</td> <td>{{ c.address }}</td> <td>{{ c.contact }}</td> <td>{{ c.phone }}</td> <td> <a href="{% url 'NewApp:centreupdate' slug=c.slug %} " style="color:black; margin-left:8px"><span class="glyphicon glyphicon-edit"></span></a> <input type="hidden" id="cendel" value="{{ c.id }}"> <a class="btn btn-primary del" type="button" id="del">Delete</a></td> </tr> {% endfor %} </body> -
Extra fields in UserAdmin for AbstractUser
I am not able to add custom fields defined in MyCustomUser to add form in admin. I can only add user with 2 basic fields - username and password. How can I extend the form with extra_field? from django.contrib.auth.models import AbstractUser class MyCustomUser(AbstractUser): extra_field = models.CharField(max_length=10) admin.site.register(MyCustomUser, UserAdmin) I have already tried other stack overflow suggestions but they are overdated or simply does not work for me. -
How to import an excel file using Django without admin access?
I am building a web page using Django. I have many users login. I need to provide an option for all users to import excel files from the web page that inturn will hit my database. I think Using Django-import-export we can upload files through admin access only. But I need to provide the same option for users. How can I achieve this? Thanks -
Python Email lib message_from_bytes function error
I'm trying to get emails from my gmail account using python. but whenever I call the email.message_from_bytes. an error is generated. I searched but I couldn't find the answer please check it. import imaplib , email, os def reademail(): con = imaplib.IMAP4_SSL("imap.gmail.com") username = 'xyz@gmail.com' password = 'xyz' con.login(username, password) def get_body(msg): if msg.is_multipart(): return get_body(msg.get_payload(0)) else: return msg.get_payload(None, True) con.select('INBOX') result, data = con.fetch(b'340', '(RFC822)') raw = email.message_from_bytes(data[0][1]) # print data print (get_body(raw)) print reademail() error Traceback (most recent call last): File "pyt.py", line 25, in <module> print reademail() File "pyt.py", line 18, in reademail raw = email.message_from_bytes(data[0][1]) AttributeError: 'module' object has no attribute 'message_from_bytes' -
how to send two parameters in url on django template language?
approve Like the above code, I am trying to send two model id but I don't know the right structure for it. and above code wouldn't work. path('start/', views.start, name="start"), def start(request,post_id): and also if i get two parenthesis, how should i modify the above url and view code? -
How to populate some form fields according to the value selected from a combo box (select box)
I have a form with "Reference Number" as a select box. I also have several text boxes in read only mode, which needs to be populated (from the database) according to the selected "reference number" I also have several other text boxes to input new details to go with the selected reference number, so that by clicking a "submit" button, I need to be able to save (edit existing record in the table) those new data values. How can I achieve this task? Fairly new to web form and also new to python and django, so haven't done much, i have the interface created, models already created. -
how to show the div when clicked on the link and how to get value from input?
i have a django template that uses for loop to print comments i want to show the input field and a button when the edit link is clicked how do i do that. and also when the edit button is pressed i wanna get the value from that specific input field. how do i do that? {% for comment in comments %} <div class="comment mdl-color-text--grey-700"> <header class="comment__header"> <img src="images/co1.jpg" class="comment__avatar"> <div class="comment__author"> <strong>{{comment.User_name}}</strong> <span>{{comment.date}}</span> </div> </header> <div class="comment__text"> {{comment.text}} </div> <!-- FAB button , class "mdl-button--fab"--> <a href="javascript:delete_comment('{{comment.text}}','{{comment.blogslug}}')"> <button class="mdl-button mdl-js-button mdl-button--fab"> <i class="material-icons">delete</i> </button> </a> <!--when this link is clicked bellow edit_comment div should appear --> <a href=""> <button class="mdl-button mdl-js-button mdl-button--fab"> <i class="material-icons">edit</i> </button> </a> <!-- and also when i click the edit button how can i get value from the input --> <div id="edit_comment" style="visibility: hidden;"> <input type="text" name="edit_comment"> <button>edit</button> </div> </div> {% endfor %} so the problem is there are going to many other comments of this type because they are printed using a loop. -
django how to get return value as a model's value in another model
i want to transfer the return value as another model's value in a database. Do i need to put it in a view or it can be done inside model's def function? def total_keluar(self): keluar = self.stok_keluar keluar.total=Gudangatas.objects.aggregate(Sum('stok_keluar')) keluar.total.save() return keluar.total i tried this code but not working column=model(keluar.total) -
I can't get my files to save to my database and then be able to be dispalyed in my basic django api
I'm building a basic http api from scratch in django and I can't get my files that are created with my POST method to save to my database and then be able to be called up and displayed with file/file_id in Postman. THIS IS MY VIEWS.PY def file(request): if request.method == "GET": print("a GET request is being made to this route") all_names = list(File.objects.values('name')) for file in all_names: print(file) return JsonResponse(dict(files=all_names)) elif request.method == "POST": print("******", request.META) files = resquest.File["filename"] name = request.META["HTTP_NAME"] newFile = File( name = name, uploader = request.META["HTTP_UPLOADER"], content = files.read(), size = 10 ) newFile.save() return JsonResponse({"file_id": name}, safe=False) TypeError: Object of type 'QuerySet' is not JSON serializable -
How to print an error when getting a wrong format input (datetime format) in a submit form in Django?
I'm building an application streaming object detection on web browser, the data (datetime, object info, etc.) is saved in mysql database, the app has a web page for filtering the data based on datetime, now it only works when the format is proper datetime format (e.g. 2019-07-24 12:00:00), if it's incorrect (e.g. 2019-07-123), web browser will return an error page. search.html <input id="from_date" type="text" name="from_date" placeholder="From Date..." > <input id="to_date" type="text" name="to_date" placeholder="To Date..." > views.py def search(request): if request.method == 'GET': from_date = request.GET.get('from_date') to_date = request.GET.get('to_date') "code to detect if from_date and to_date are incorrect formats???" I want to know how can I detect that case then print an error in my web template. -
Is there a parameter to change the order of reactions for an activity with stream?
For a certain activity id (postid) I have an API endpoint that will return the list of reactions (comments) for that activity. It appears to me that the way in which the reactions are returned from stream is that the newest is at the top? I want the newest at the bottom like how facebook is. As far as what I've seen or tried I just see what the documentation has: https://getstream.io/docs/python/#reactions_retrieve-reactions I do see that it seems to support pagination which I also need so that's great. class ListCommentsForPost(ListAPIView): permission_classes = (IsAuthenticated,) def get(self, request, postid, *args, **kwargs): response = stream_client.reactions.filter( activity_id=postid, kind="comment", ) serializer = CommentSerializerStream(response['results'], many=True) return Response(serializer.data) Ultimately, I just expect to be able to change the order of how reactions are returned chronologically. When stepping the code I do see it is indeed an OrderedDict so maybe the answer is to just try to manually reorder it? Should probably still be a query parameter though. -
Optimize Django for loops with filter inside the loop
If i have model like this class User(models.Model): name = models.CharField(max_length=255) organization = models.ForeignKey( "organization.Organization", on_delete=models.CASCADE ) school = models.ForeignKey( school, on_delete=models.CASCADE,) And then I receive and input of list of lists of user ID. Like this: list_of_lists_of_user_id = [ [11,21,23] , [12, 324] , [909,2,12,444,242] , ....... ] I want to return the same kind of list but not with just ID, instead I want the other value like "name" and "school" too. So I want to return the list of queryset of User's name and School I would have to loop through like this: return_list_of_query_set = [] for group in list_of_lists_of_user_id: query_set = User.values("name","school").filter( id__in=group ) return_list_of_query_set.append(query_set) How would I optimize this for loop and don't make 1000s queries -
How to setup django rest framework to only allow user that creates an object to GET,PUT,DELETE
I'm setting up a Django REST API that involves families, parents, and children. I want to setup permissions so that Admins can send a GET request to the /api/parents/ endpoint and see a list of all Parents, but User's GET requests only return the list of Parent objects that they created, or "own". I'm building an app with a React.js frontend and a Django REST backend. When a User Signs Up, they are issued a JSON Web Token using the open source simplejwt package that django has. The application involves parents and children in families. When the User tries to create a Parent object, they need to be able to retrieve the unique hyperlinked URL to their personally created Parent object in order to create a linked Child object for their children and associate it only to their Parent object. Right now, when I make a POST request to the endpoint for the Parent router, Anyone can create a Parent object as long as they are logged in. Only GET requests from admins succeed(with the attached JWT as a Bearer in Authorization in the request). Admin GET requests succeed with a list of all Parent objects in the database. If … -
AWS Elastic Beanstalk Django configuration file exception
I'm trying to deploy a sample Django (Python 3.6) application to AWS Elastic Beanstalk via the eb CLI tool. I followed this tutorial and all is going good until I get to the YAML Django configuration file. I'm using Sublime 3 for editing, at first I thought it had some problem with the encoding and/or tabs but then I tried with vim, copy-pasting the exact code from the tutorial and got the same error every time. My project structure is / /project /project/wsgi.py ... $ cat .ebextensions/django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: project/wsgi.py When I run eb deploy I get the next error: ERROR: InvalidParameterValueError - The configuration file .ebextensions/django.config in application version 2.0.0 contains invalid YAML or JSON. YAML exception: Invalid Yaml: while scanning for the next token found character '\t' that cannot start any token in "<reader>", line 2, column 1: aws:elasticbeanstalk:container: ... ^ , JSON exception: Invalid JSON: Unexpected character (o) at position 0.. Update the configuration file. -
Cleaning up code to show/hide Django objects in template with JavaScript
I have a Django template that lists blog categories and tags in a sidebar and want to limit the results to only show 5 categories and tags by default. I also want to add functionality that toggles (shows/hides) the full list of categories and tags when the user clicks a link at the bottom of the category/tag lists on the sidebar. So far, the code is working. It only shows 5 categories/tags by default and when you hit 'more', it expands to the full list. Then clicking 'hide' will then revert back to hiding the extra elements and only show 5. It also changes the show/hide text to reflect that. However, there is a lot of repeated code and I want to clean it up so I'm only using 1 function and event listener for this. Javascript // Expand sidebar categories and tags let categoryLinks = document.querySelectorAll('.sidebar-categories .sidebar-item-link'); let tagLinks = document.querySelectorAll('.sidebar-tags .sidebar-item-link'); let sidebarMore = document.querySelectorAll('.sidebar-more'); let catMore = sidebarMore[0]; let tagMore = sidebarMore[1]; function truncateCatLinks(links) { for (let i = 0; i < links.length; i++) { if (i > 4) { if (links[i].style.display === 'none') { links[i].style.display = 'block'; catMore.textContent = 'Less...'; } else { links[i].style.display = 'none'; … -
Django's REST framework custom exception handling simply doesn't work
July 2019 - Using latest Django/DRF: in myproj/my_api_app/public_views.py I have: def custom_exception_handler(exc, context): # Call REST framework's default exception handler first, # to get the standard error response. response = exception_handler(exc, context) # Now add the HTTP status code to the response. if response is not None: response.data['status_code'] = response.status_code return response in myproj/myproj/settings.py I have: (Yes, two times myproj/myproj) REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ], 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.ScopedRateThrottle', ), 'DEFAULT_THROTTLE_RATES': { 'public_get': '30/minute', 'user_get': '60/minute' }, 'EXCEPTION_HANDLER': 'myproj.my_api_app.public_views.custom_exception_handler' } I try to hit a non-existing endpoint on purpose and I am still getting the default 404 message (DEBUG=False in settings). I have tried every permutation of the "Path" for the EXCEPTION_HANDLER. Nothing works. The EXCEPTION_HANDLER is ignored. What am I doing wrong? -
Using APIs within Django and how to display the data
I am trying to test how to display API information within a view on my Django project. I know you may have to add some installed APIs into the settings INSTALLED APPS block. This api is a simple geo one. I am new to Django and new to using APIs within it. I have managed to get my app the way I need it using Youtube videos. But now I am on my own. I have many different view classes to display differents of my app. The view below is the view Id like to place the data on. is this how I would potentially do it? Then call { country } within the HTHL to display it? class PostDetailView(DetailView): model = Post template_name = 'clients/post_detail.html' def api_test(request): # This is where the APIs are going to go. response = requests.get( 'http://api.ipstack.com/134.201.250.155?access_key=c30ffa84341bb5b9cb4b3794357d0dfa') geodata = response.json() return render(request, 'clients/post_detail.html', { 'ip': geodata['ip'], 'country': geodata['country_name'] }) I am currently getting no errors within my app, but the country element isnt displaying. -
Django model wont migrate using a OneToOne field
When I try to run migrate my new models using python manage.py migrate, I get this error: AssertionError: OneToOneField(<class 'migratefire.models.Server_DefaultChannel'>) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self' This is how my models.py structure looks (I made sure to declare the inherited models first): class Server_DefaultChannel(): channel_id = models.BigIntegerField(default=0) name = models.CharField(default='undefined', max_length=32) channel_type = models.IntegerField(default='-1') class Server_Inviter(models.Model): avatar = models.CharField(default='undefined', max_length=64) discriminator = models.IntegerField(default=0) inviter_id = models.BigIntegerField(default=0) username = models.CharField(default='undefined', max_length=32) class Server_Guild(models.Model): features = ArrayField(models.CharField(default = 'undefined', max_length = 64)) icon = models.CharField(default = 'undefined', max_length = 64) guild_id = models.BigIntegerField(default=0) name = models.CharField(default = 'undefined', max_length = 128) splash = models.CharField(default = 'undefined', max_length = 64) description = models.CharField(default = 'undefined', max_length = 256) vanity_url = models.CharField(default = 'undefined', max_length = 128) class Discord_Server(models.Model): approximate_member_count = models.IntegerField(default=-1) approximate_presence_count = models.IntegerField(default=-1) server_defaultchannel = models.OneToOneField(Server_DefaultChannel, on_delete=models.PROTECT, null=True) code = models.CharField(max_length=32) server_guild = models.OneToOneField('migratefire.Server_Guild', on_delete=models.PROTECT, null=True) server_inviter = models.OneToOneField('migratefire.Server_Inviter', on_delete=models.PROTECT, null=True) server_tags = ArrayField(models.CharField(default='none', max_length=16)) last_checked = models.DateTimeField(default=0)` I've tried putting the app name in the meta field for each class, I've tried using strings instead and got this error: ERRORS: migratefire.Discord_Server.server_defaultchannel: (fields.E300) Field defines a relation with model 'migratefire.Server_DefaultChannel', … -
DurationField or Timedelta
im having a problem trying to set a duration in my to-do tasks. i've tried with DurationField and some people told me to try the timedelta in your forms.py but im not quite shure how to pass the difference like (6days) from my two model DateField (start and end). Models.py from django.db import models from datetime import datetime, timedelta class To_do (models.Model): task = models.CharField(max_length=150) topic = models.CharField(max_length=150) how = models.TextField(max_length=600) start = models.DateField(default=datetime.today) end = models.DateField(blank=False) duration = models.DurationField(default=timedelta) i'd like to display the difference for the user and after set an alarm for less than 3 days etc. Thanks for your attention. -
Django-allauth - adding additional fields using AbstractUser
I am trying to add additional fields ('test') using AbstractUser. I creates a simple user model. class CustomUser(AbstractUser): test = models.CharField(max_length=100) def __str__(self): return self.email Next i create form: class SimpleSignupForm(SignupForm): first_name = forms.CharField(max_length=30, label='First Name') last_name = forms.CharField(max_length=30, label='Last Name') test = forms.CharField(max_length=100, label='test') def signup(self, request, user): user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.test = self.cleaned_data['test'] user.save() return user Everything is saved outside of my test field. How to save the easiest data from the test field from my forms in my model CustomUser. Why it does not work in my example. Any help will be appreciated.