Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django reverse admin disable delete for inline
This is my ModelAdmin class ComputerAdmin(ReverseModelAdmin): list_display = ('employee', 'ip', 'mac', 'name', 'hardware') list_filter = ('employee__branch', ) inline_type = 'tabular' inline_reverse = ['hardware', ] show_full_result_count = False This is how it shows when adding a new computer As you can see I don't want to have delete column and delete icon, because I have a foreign key so only one element is allowed. How can I do that ? Does django-reverse-admin have anything like has_delete_permisison for inlines only and not the whole ModelAdmin ? I have already searched in documentation with no results, which is why I am posting here. Thanks -
How to find duplicate and deactivate duplicates for user attributes
Suppose we have a model in django defined as follows: class DateClass: user_id = models.IntegerField(...) sp_date = models.DateField(...) is_active = models.BooleanField(...) ... I follow insert policy here, i.e, for a specific user there will be only one specific active date. That means, there will be only one active row for user=1 at date table for sp_date values 27/10/2021, 28/10/2021 and so one. There shouldn't be two active rows for 27/10/2021 for user=1, but for other users have there rows for 27/10/2021. Whenever a date has to be updated, I deactivate (is_active=False) the previous row and add a new row for specific date. I want to find duplicate active dates for each users in one single query, and then deactivate (set is_active=False) all the duplicate values except the last row (The row which was last inserted). Two rows will be duplicate if the values of user_id and sp_date are equal and both have is_active=True. I know how to find duplicates for a specific column which is fairly easy. But I can't think of something which can do the above task elegantly. I can only think of following approach: for user in users: dates = DateClass(user_id=user.id, is_active=True) for date in dates: days … -
In Django, remove options in a choice-field dropdown based on the valuse selcted in other field in a model
I'm new to Django and any help is appreciated, How can I restrict the choice option in one field based on a previous field. For example, if I select 'dog' for animal, I want to remove 'chocolate' from the FOOD_CHOICE. Thank you!!! ANIMAL_CHOICE = ( ('a','cat'), ('b','dog'), ('c','fish'), ) FOOD_CHOICE = ( ('a', 'chocolate'), ('b', 'kittySnack'), ('c', 'steak'), ) class Animal(models.Model): animal = models.CharField(max_length=1, choices= ANIMAL_CHOICE) food = models.CharField(max_length=1, choices= FOOD_CHOICE) -
Flatpicker defaultHours and defaultMinute not working
I am trying to change the default time when a date is selected in Flatpicker, but every time I select a date, the time is always 12:00 or another value if the time was already there when retrieved by Django. I cannot find a way to set the current time upon selection of the date. $('.datepicker').flatpickr({ dateFormat: "d-m-Y H:i:S", enableTime: true, // enableSeconds: true, allowInput: true, time_24hr: true, minuteIncrement: 1, defaultHour: new Date().getHours(), defaultMinute: new Date().getMinutes(), }); -
How to add username and password for xml format with python
def test(login,password): data="""<?xml version="1.0"?> <soap-env> <soap-env:Body> <Auth> <Login>login</Login><password>password</password> </Auth> <Ping> </Ping> </soap-env:Body> </soap-env:Envelope>""" return data i can't add login and password when i use '+login+' and i can't do format string like this " " -
I have a problem with class-based views create a view
I need help or guidance on where to find a solution. The following code does not run properly and returns an error. class TaskCreate(CreateView): model = Task fields = '__all__' success_url = reverse_lazy('tasklist') template_name = 'create.html' class_form = 'create' The create.html file is in the main templates folder where the static folder is. The code will work when I change the name from create.html to task_form.html and move it to the application folder.But I don't want to do this Question. What do I have to do for the above code to work for me? Thank you for every reply. -
Fullcalendar error rendering Unexpected token
Going through a new django 3 project, newbie on that, so sorry me if my code is not so clean. The problem is when i try to render calendar... without events it loads nicely, but when loading'em it stops rendering the whole calendar. Console throes an Uncaught SyntaxError: Unexpected token '{', but i can´t find the problem, neither is a comma into my loop. Any help welcome. My calendar script: <script> document.addEventListener('DOMContentLoaded',function(){ var cUI= document.getElementById('calendar'); var c= new FullCalendar.Calendar(cUI,{ themeSystem: 'bootstrap', headerToolbar:{ left:'prev,next today', center:'title', right:'', }, events:{ {% for v in vacation %} { title:"{{ v.reason }}: {{ v.starth }}-{{ v.endh }}", start: "{{ v.start | date:'Y-m-d' }}", end: "{{ v.end | date:'Y-m-d' }}", }, {% endfor %} }, }); c.render(); c.setOption('locale','es'); }); </script> Thank you -
django ORM aggregate for count
**i want to get count of scheduled test ride and completed test ride of user** obj= TestRide.objects.filter(feature=feature_obj).aggregate( scheduled_count=( Count('status', filter=Q(status='Scheduled')) ), completed_count=( Count('status', filter=Q(status='Completed')) ), ) i am getting same count value in scheduled_count and completed_count i think my filter is not working can anyone help me out thanks -
Bulk user import in Django
I like to bulk import users to my original User model. I don't use AbstractUser or AbstractBaseUser and I don't like to because my site is working and I don't want to abuse my schema. I'am using the original User model where I add the users (no user registration allowed) and I store the extra filed in my Profile model with a OneToOne relation. I'm not so experienced so I tried to use code snippets that I found but I am still not able to achieve my goal. If I try to use import-export module in my admin panel it works with other models but not with the User model. Tablib or other solutions would be also interesting to me. models.py (I'm using the original User model that sends a signal to Profile model when a user is created) class Profile(models.Model): def __str__(self): return str(self.user) user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) date = models.DateField(auto_now_add=True, auto_now=False, blank=True) projekt = models.ForeignKey(Projekt, on_delete=models.CASCADE, default=1) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() forms.py class RegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email', 'last_name', 'first_name', 'password1', 'password2'] admin.py from django.contrib.auth.models import … -
How to make multiple tables inside one Model in Django?
I have made a model class for Stocks database which has Date Open High Low and Close fields in Django. I uploaded one CSV file into that which is working fine. But now I want to upload multiple stock files data into this same model. How to do it ? -
How can set withdrawal limit? Django, Python
i have a project where users deposit, play game, and withdraw. I want to set withdraw limit for specific user groups. this is my User Model: class User(AbstractBaseUser, PermissionsMixin): class PlatformStatus(models.TextChoices): NOT_REQUESTED = 'not requested' REQUESTED = 'requested' PENDING = 'pending' CREATED = 'created' class Status(models.TextChoices): PENDING = 'pending' ACTIVE = 'active' DEACTIVATED = 'deactivated' BLACK_LIST = 'blacklist' class UserRole(models.TextChoices): REGULAR = 'regular' SILVER = 'silver' GOLD = 'gold' PLATINUM = 'platinum' VIP = 'vip' class ReadStatus(models.TextChoices): READ = 'read' UNREAD = 'unread' ACTIVE = 'active' """" Custom user model that uses email instead of username """ id = models.AutoField(primary_key=True, editable=False) email = models.EmailField(max_length=255, unique=True) username = models.CharField(max_length=255, unique=True, null=True, blank=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) status = models.CharField(max_length=250, choices=Status.choices, default="pending") role = models.CharField(max_length=250, choices=UserRole.choices, default='regular') created_at = models.DateTimeField(auto_now_add=True, null=True) first_name = models.CharField(max_length=150, unique=False, null=True) last_name = models.CharField(max_length=150, unique=False, null=True) phone = models.CharField(max_length=20, unique=True, null=True, blank=False) user_ip = models.CharField(max_length=120, null=True, blank=False) is_phone_verified = models.BooleanField(default=False) is_id_verified = models.BooleanField(default=False) id_number = models.CharField(max_length=250, unique=True, null=True) id_issued_state = models.CharField(max_length=250, null=True) id_self = CompressedImageField(upload_to="user-id/self/", null=True, default=None, max_length=500, quality=50, validators=[validate_file]) id_front = CompressedImageField(upload_to="user-id/front/", null=True, default=None, max_length=500, quality=50, validators=[validate_file]) id_back = CompressedImageField(upload_to="user-id/back/", null=True, default=None, max_length=500, quality=50, validators=[validate_file]) btc_address = models.CharField(max_length=500, unique=True, null=True, blank=True) referral_code = models.CharField(max_length=10, … -
Django not saving the data to database
I have a very basic knowledge of Django and having come across a problem, it has rendered me totally confused. I am trying to construct a 3D plotter. Everything is rendering properly but when I click Submit, it never saves to the database except the specified default value that I have provided. My models.py from django.db import models class Value(models.Model): eq_input = models.CharField(max_length=20, default='x**2 + y**2') color = models.CharField(max_length=20, default='Magma') My forms.py from django import forms from .models import Value class ViewForm(forms.ModelForm): Equation = forms.CharField(max_length=20, label='Equation') Color = forms.CharField(max_length=20,label='Color') class Meta: model = Value fields = { 'Equation', 'Color' } My views.py from django.shortcuts import render from django.http import HttpResponse from .models import Value from .forms import ViewForm def home_view(request): if request.method == "POST": form = ViewForm(request.POST) if form.is_valid(): form.save() else: form = ViewForm() context = { 'form': form } return render(request, "home.html", context) My home.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>3D Graph Plotter</title> </head> <body> <center><h1>This is a 3D plotter</h1></center> <center> <form action="." method="POST">{% csrf_token %} {{ form.as_p }} <input type="submit" name="Save" /> </form> </center> </body> </html> and my urls.py from django.contrib import admin from django.urls import path, include from equation.views import eq, home_view urlpatterns = [ path('admin/', … -
How to get distinct data in Django views queryset?
I have the following records in table I want to get all sender_id where receiver_id is 15 and all receiver_id where sender_id is 15. How can I define queryset. I have tried following class ContactListAPI(GenericAPIView, ListModelMixin ): def get_queryset(self): return Messages.objects.filter(Q(sender=15) | Q(receiver=15)) serializer_class = ContactsSerializer permission_classes = (AllowAny,) def get(self, request , *args, **kwargs): return self.list(request, *args, **kwargs) but this is giving me all the records but I want Distinct values only. simply I want to get all the receiver id's where sender is 15 and all sender ids where receiver is 15. here my expected output is 11,17. tell me how can I get these by defining query set. -
Toggle Switch Not working in all rows in Django
I am intending to implement activating and deactivating a user by changing the value of is_active in the database which is a boolean to True or false depending on the the status of the Toggle switch.I have implemented this but the problem is that the toggle switch only works in on raw only the rest doesnt work looped output from database <main class="page-content"> <div class="path"> <h5>Administration <i class="fa fa-chevron-right"></i> Users <i class="fa fa-chevron-right"></i> All user</h5> </div> {% for message in messages %} {% if 'success' in message.tags %} <script> swal("Success", "{{ message }}", "success"); </script> {% elif 'error' in message.tags %} <script> swal("Error!", "{{ message }}", "error"); </script> {% endif %} {% endfor %} <hr/> <div class="container-fluid pl-0 pr-2"> <table id="myTable" class="table table-bordered table-hover table-sm"> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Email</th> <th>Role</th> <th>Status</th> <th>Action</th> </tr> </thead> <tbody> {% if all_users %} {% for user in all_users %} <tr> <td>{{ user.first_name }}</td> <td>{{ user.last_name }}</td> <td>{{ user.email }}</td> <td>{{ user.role }}</td> <td>{% if user.is_active %} <i class="fas fa-check-circle" style="color:green"></i> {% else %} <i class="fas fa-times-circle" style="color: red;"></i> {% endif %} </td> <td><a href="{% url 'admin:edit_user' user.id %}" ><i class="fas fa-edit" style="color:limegreen ;"></i></a>&nbsp;<input type="checkbox" name="is_active" data-toggle="toggle" id="statuschange" data-on="Activate" checked data-off="Deactivate" data-size="xs" … -
Data format for text/plain requests in DRF API
Building an API to be used by A9G for communication. As a result, text/plain is desired. The API currently works well with application/json and other Content-Type, however, I am finding it hard getting the correct format for posting text/plain data. Tried: meter_id=OND123 timestamp=2019-08-24T14:15:22Z current=45.6 voltage=240.0 frequency=50 power_factor=0.6 energy=78 and different variations of it but I always get: { "non_field_errors": [ "Invalid data. Expected a dictionary, but got bytes." ] } My plaintext parser is: class PlainTextParser(parsers.BaseParser): """ Plain text parser. """ media_type = "text/plain" def parse(self, stream, media_type=None, parser_context=None): """ Simply return a string representing the body of the request. """ return stream.read() And only those fields are required. Can anyone help me out with the correct data format for this? -
In SQLAlchemy, Which is better to fetch the data in descending order or reverse list the fetched data?
I have to fetch data in descending order. So what would be faster? fetch the data in descending order or reverse() the list of fetched data. Note: I have been using SQLAlchemy in Flask framework. My application has to fetch hundreds of data from MySQL. -
Streaming opencv frame with django frame is not working on all
I'm trying to stream OpenCV frames to web browser like is described in answer here: How to stream opencv frame with django frame in realtime?. I don't know why in Firefox is all working all the time, but when I tried Safari the stream is sometimes not working. Exist any universal solution of this problem for Firefox, Safari, Chrome and so on. Thanks. -
Getting Next/Prev item from database Django
I have read Getting next and previous objects in Django and How to access the next and the previous elements in a Django template forloop?, but I am still confused how to get the next item. I have tried these suggestions, and I've read the documentation. I can't find any youtube videos really. Can someone explain it to me? -
error occur while run url.py in django in pycharm
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. why this error occured .how can I solve this error. please give me an answer -
Django linking files together
I'm trying to build a PWA inside a Django project. Myfolderstructur inside the pwa app: pwa->static->pwa->serviceworker.js and pwa->templates->indexPWA.html How can i load the indexPWA.html in the serviceworker.js? var filesToCache = ["indexPWA.html",... gives the error: ` /static/pwa/indexPWA.html HTTP/1.1" 404` If i copy another indexPWA.html inside the static folder, the error is removed, but my PWA is not installable and 2 identical files in one project it's not the way it should be. In the indexPWA.html i load the serviceworker.js like: if ("serviceWorker" in navigator) { navigator.serviceWorker.register("{% static 'pwa/serviceworker.js' %}"); } -
updating django python code to latest lts
I have been trying to update my django python code from django version 1.9 and python version 2.7 to the django version 3.2.8 and the python3.8. but while updating I'm stuck with the below error (SA_python3.9_env) E:\SA_py_3.9\sa>python manage.py runserver sys.argv:- ['manage.py', 'runserver'] sys.argv:- ['manage.py', 'runserver'] Watching for file changes with StatReloader Performing system checks... Traceback (most recent call last): File "E:\SA_py_3.9\SA_python3.9_env\lib\site-packages\django\template\utils.py", line 66, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Exception in thread Traceback (most recent call last): django-main-thread File "E:\SA_py_3.9\SA_python3.9_env\lib\site-packages\django\template\backends\django.py", line 121, in get_package_libraries : Traceback (most recent call last): module = import_module(entry[1]) File "E:\SA_py_3.9\SA_python3.9_env\lib\site-packages\django\template\utils.py", line 66, in __getitem__ File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) return self._engines[alias] File "<frozen importlib._bootstrap>", line 1030, in _gcd_import KeyError File "<frozen importlib._bootstrap>", line 1007, in _find_and_load : 'django' During handling of the above exception, another exception occurred: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked Traceback (most recent call last): File "E:\SA_py_3.9\SA_python3.9_env\lib\site-packages\django\template\backends\django.py", line 121, in get_package_libraries File "<frozen importlib._bootstrap>", line 680, in _load_unlocked module = import_module(entry[1]) File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed return _bootstrap._gcd_import(name[level:], package, level) File "<frozen … -
Nav Bar Toggle Button - Won't dropdown
I have a Django homepage that has a Bootstrap navbar, and when resized I have it show a toggle button. My issue is that when this toggle button comes into effect, I cannot dropdown the navbar items? I am unsure how I can fix this. Snip of what these look like (for an idea): https://imgur.com/a/PyiUs38 Pastebin: https://pastebin.com/QqPiyVxf <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <!--LOGO--> <a class="navbar-brand" style="pointer-events: none"> <!-- Unclickable --> <img src="http://www.w3.org/2000/svg" width="30" height="30" alt=""> </a> <!--MAIN NAV--> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo02" aria-controls="navbarTogglerDemo02" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse justify-content-md-center" id="navbarTogglerDemo02"> {% with request.resolver_match.url_name as url_name %} <ul class="navbar-nav"> <li class="nav-item {% if url_name == 'home' %}active{% endif %}"> <a class="nav-link" href="{% url 'home' %}">Home</a> </li> <li class="nav-item {% if url_name == 'about' %}active{% endif %}"> <a class="nav-link" href="{% url 'about' %}">About</a> </li> <li class="nav-item {% if url_name == 'projects' %}active{% endif %}"> <a class="nav-link" href="{% url 'projects' %}">Projects</a> </li> <li class="nav-item {% if url_name == 'uses' %}active{% endif %}"> <a class="nav-link" href="{% url 'uses' %}">Uses</a> </li> <li class="nav-item {% if url_name == 'contact' %}active{% endif %}"> <a class="nav-link" href="{% url 'contact' %}">Contact</a> </li> </ul> {% endwith %} </div> <!--SOCIALS--> <!-- Twitter --> <a class="btn btn-primary" … -
django model form set initial
I have a list of comments stored in database, schema: models.py class Comment(models.Model): content = models.CharField(max_length=255) query set In [1]: from comments.models import Comment In [2]: Comment.objects.all() Out[2]: <QuerySet [<Comment: Comment object (1)>, <Comment: Comment object (2)>]> In [3]: Comment.objects.all()[0] Out[3]: <Comment: Comment object (1)> In [4]: Comment.objects.all()[0].content Out[4]: 'first comment' I want to use a CommentListUpdateView, to allow user to update many comments at the same page individually (each comment has a form and a update button) therefore, I in views.py # Create your views here. def commentListUpdateView(request): forms = [] for comment in Comment.objects.all(): form = CommentUpdateForm(request.POST, instance=comment, initial={'content': comment.content}) # form = CommentUpdateForm(request.POST, instance=comment) # form.fields['content'].initial = comment.content forms.append(form) return render(request, 'comments/comment_list_update.html', {'forms': forms}) forms.py class CommentUpdateForm(forms.ModelForm): class Meta: model = Comment fields = ['content'] template {% for form in forms %} <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form }} <button type="submit">Update</button> </form> {% endfor %} However, I can always get the value from backend, but the value is always missing in the frontend. the html I got as result: <form method="POST" enctype="multipart/form-data"> <input type="hidden" name="csrfmiddlewaretoken" value="zQtpR8P4K8A1a7i1ELI9kJg1YRo0Y7d02hpSWqY5VPX2j48x1j4UHubWmosaGk4Q"> <label for="id_content">Content:</label> <ul class="errorlist"> <li>This field is required.</li> </ul><input type="text" name="content" maxlength="255" required="" id="id_content"> <button type="submit">Update</button> </form> I have … -
How to get Google-Calendar events using access token
I have built a django app, which it includes google Oauth2.0 login. I want to get google calendar events of every users when they login with Oauth2.0 and I wrote the following code. I saved the access token into UserAuth table and fetched it, then used it to get google calendar. def get_events_server(request): user = User.objects.get(username=request.user) creds = UserAuth.objects.get(user=user).google_id_token credentials = AccessTokenCredentials(creds, "") http = httplib2.Http() http = credentials.authorize(http) service = build('calendar', 'v3', http=http) return service When I run the code, the following error has happened. HttpError at /calendar/ <HttpError 403 when requesting https://www.googleapis.com/calendar/v3/calendars/primary/events?timeMin=2021-10-28T04%3A33%3A08.956703Z&timeMax=2021-11-04T04%3A33%3A08.956712Z&singleEvents=true&timeZone=GMT%2B9%3A00&orderBy=startTime&alt=json returned "Request had insufficient authentication scopes.". Details: "[{'message': 'Insufficient Permission', 'domain': 'global', 'reason': 'insufficientPermissions'}]"> Is there a solution to skip this issue? -
Making use of the token generated upon log in
I have coded the API to work with my web and also generate token upon login/register from the Postman request by using knox for the token. Now I want to make use of this token that is linked to the account that is logged in to get the username so I can know which account who make the request. But I am not sure on how to use this token. Can anyone provide me with some advise on how to do this as I am quite new on this. Just learned how to generated this token yesterday. Thanks ! views.py @api_view(['POST']) @authentication_classes([TokenAuthentication]) @permission_classes([IsAuthenticated]) def create_job(request): job = Job() jobserializer = JobSerializers(job, data = request.data) if jobserializer.is_valid(): operation = jobserializer.save() data = {} if operation: data["Success"] = "Successfully created" return Response(data) return Response(jobserializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class JobSerializers(serializers.ModelSerializer): class Meta: model = Job fields = ['combinedparameters', 'servicedate'] models.py class Job(models.Model): owner = models.CharField(max_length = 150) datetime = models.DateTimeField(default=timezone.now) combinedparameters = models.CharField(max_length = 1000) servicedate = models.CharField(max_length=10) def __str__(self): return self.servicedate In the web browser, I get the user by request.user but I am not sure on how to make use of this token to get the user in API.