Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Understanting Django inheritance templates
Im really lost about this, im trying to understand a django inheritance template about I have a layout with a navbar and html structure: todos/templates/todos/layout.html <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous" /> <title>Practice Django</title> </head> <body> <nav class="navbar navbar-dark bg-dark justify-content-between"> <div> <a class="navbar-brand" href="/">Django app</a> <a href="#" class="navbar-item mr-3">Page 1</a> <a href="#" class="navbar-item">Page 2</a> </div> <form action="" class="form-inline"> <input type="search" placeholder="Search Todo" aria-label="Search" class="form-control mr-sm-2" /> <button type="submit" class="btn btn-outline-success my-2 my-sm-0"> Search </button> </form> </nav> <div class="container"> {% block content %} {% endblock %} </div> </body> </html> then im trying to setup a index page with a grid, a column for show todos and the another one for create a new todo. todos/templates/todos/base.html {% block content %} <h1 class="text-center">Base Page</h1> <div class="row"> <div class="col"> {% block todolist %} {% include 'todos/todos_list.html' %} {% endblock %} </div> <div class="col"> {% block addtodo %} {% include 'todos/add_todo.html' %} {% endblock %} </div> </div> {% endblock %} todos/templates/todos/add_todo.html {% extends 'todos/base.html' %} {% block addtodo %} <h3 class="text-center">subpage addtodo</h3> {% endblock %} todos/templates/todos/todos_list.html {% extends 'todos/base.html' %} {% block todolist %} <h3 class="text-center">subpage todolist</h3> {% endblock %} For try to understand … -
Caching the result of a query to the database
When rendering a page, a heavy query to the database is performed. My task is to cache the queryset obtained in the query and use it later. If 5 minutes have passed since the last initialization of the cache during the next cache query, the old cache should be removed and new data should be written from the database. Now I have written the logic without taking into account the timing, and further I have a problem with understanding how to connect the timer. class BlacklistCache: def __init__(self): self._cache = {} @property def cache(self): return self._cache @cache.setter def cache(self, value): self._cache = value @cache.deleter def cache(self): del self._cache blacklist_cache = BlacklistCache() def check_blacklist_cache(item_type): if blacklist_cache.cache: return blacklist_cache.cache else: blacklist = BlacklistedItem.objects.filter(item_type=item_type).values_list('item_id', flat=True) blacklist_cache.cache = blacklist return blacklist_cache.cache Could you get me any advice, or maybe most efficient approach? -
Data rollbacking when using AJAX function in Django?
I have an application that displays data to the users. There is a secondary column where users can enter a correction. I created an AJAX function that saves the data entered and updates my database. The application was working fine. I started to do some testing and today I found out that when I enter a value in the editable columns, after like 10 minutes it is deleted. I did queries in my database. When I query the row where I edited the value, it is shown correctly in my SQL database, and after 10 minutes, it is reverted. I don't understand why this is happening, and I was almost certain that it wasn't happening before. This is how my html/js script looks like: <head> <link rel="stylesheet" type="text/css" href="{% static 'css/dashboardStyle.css' %}"> </head> <body> <br> <br> <br> <br> <h1 class='fade-in'>Hello, {{ name }}</h1> <br> <br> <br> <br> <table class="content-table"> <thead> <tr> <th>ID</th> <th>MonthlyAccess</th> <th>MonthlyAccess_E</th> <th>QTY</th> <th>QTY_E</th> <th>GrossProfit</th> <th>GrossProfit_E</th> <th>Source</th> <th>Comment</th> </tr> <tbody> {% for datadisplay in Fact_POSTransactions %} <tr> <td>{{datadisplay.id}}</td> <td>{{datadisplay.MonthlyAccess}}</td> <td class="editable" data-id="{{ datadisplay.id }}" data-type="MonthlyAccess_E">{{ datadisplay.MonthlyAccess_E }}</td> <td>{{datadisplay.QTY}}</td> <td class="editable" data-id="{{ datadisplay.id }}" data-type="QTY_E">{{ datadisplay.QTY_E }}</td> <td>{{datadisplay.GrossProfit}}</td> <td class="editable" data-id="{{ datadisplay.id }}" data-type="GrossProfit_E">{{ datadisplay.GrossProfit_E }}</td> <td class="editable" data-id="{{ … -
Django (containerized) cannot connect to MySQL (containerized) on local machine
I set up a MySQL database using the official image from DockerHub by the command on a virtual machine with CentOS 7.6 docker run -d -p 3306:3306 --name mysql -v /opt/mysql/mysql-data/:/var/lib/mysql -e MYSQL_DATABASE=myblog -e MYSQL_ROOT_PASSWORD=123456 mysql:5.7 Then I built and started a Django project in another container named myblog with the settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'myblog', 'USER': os.environ.get("MYSQL_USER", 'root'), 'PASSWORD': os.environ.get("MYSQL_PASSWD", '123456'), 'HOST': os.environ.get("MYSQL_HOST", '127.0.0.1'), 'PORT': os.environ.get("MYSQL_PORT", '3306') } } However, when I opened the interactive bash shell of the Django project and tried to makemigrations with the command python3 manage.py makemigrations, Django complains about the connection with the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 583, in connect **kwargs) File "/usr/lib64/python3.6/socket.py", line 724, in create_connection raise err File "/usr/lib64/python3.6/socket.py", line 713, in create_connection sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/usr/local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 227, in get_new_connection return Database.connect(**conn_params) File "/usr/local/lib/python3.6/site-packages/pymysql/__init__.py", line 94, in Connect return Connection(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 325, in __init__ self.connect() File "/usr/local/lib/python3.6/site-packages/pymysql/connections.py", line 630, in connect raise exc … -
how can i bind three ModelForm in django?
i want to make a report of a patient. every patient has many of vitals, each vital has different results_values. but i don't know how can i perform these steps and bind that forms in single view to achieve ? i also get patient and vitals data but i don't understand how can i put reportform in same view and submit report attribute? i want to render forms fields and data something like this. models.py class Patient(models.Model): name = models.CharField(max_length=100) vitals = models.ManyToManyField(Lesson) class Vital(models.Model): title = models.CharField(max_length=100) expected_values = models.CharField(max_length=10) class Report(models.Model): vital = models.ForeignKey(Vital, on_delete=models.CASCADE) result_values = models.CharField(max_length=10, blank=True) forms.py class PatientForm(forms.ModelForm): class Meta: model = Patient fields = ['name'] class VitalsForm(forms.ModelForm): class Meta: model = Vitals fields = [ 'title', 'expected_values' ] class ReportForm(forms.ModelForm): class Meta: model = Report fields = ['result_values'] views.py def book_update_form(request, pk): book = get_object_or_404(Book, pk=pk) b_form = BookForm(request.POST or None, instance=book) l_form = [LessonForm(request.POST or None, prefix=str( lessons.pk), instance=lessons) for lessons in book.lessons.all()] if request.POST and b_form.is_valid() and all([lf.is_valid() for lf in l_form]): b_form.save() for lf in l_form: lesson_form = lf.save() return redirect('dashboard') context = { 'book_update': b_form, 'lesson_form_list': l_form } return render(request, 'patient/report.html', context) -
is there way to add wysiwyg editor in django admin and automatically create url and html page?
is there way to add wysiwyg editor in django admin and automatically create url and html page ? i have blog and i want add new posts from admin panel and choose url for each post also i want the post must have an design then just pass data from wysiwyg editor to page and keep the design i have installed CKeditor and add it to model like this class Test(models.Model): name = models.CharField(max_length=50,default="") content = QuillField(default="") app_image = models.ImageField(upload_to='images/',null=True, blank=True) def get_image(self): if self.app_image and hasattr(self.app_image, 'url'): return self.app_image.url else: return '/path/to/default/image' def __str__(self): return self.name -
Generic detail view DetalleProyecto must be called with either an object pk or a slug in the URLconf
i am trying to build a view that shows me the detail of a record but i am having trouble adding a pk or slug, i am new to python. any help will be very appreciated thanks The error message it sends me is the following, NoReverseMatch at /buscar/ Reverse for 'detalle_obra' with arguments '('',)' not found. 1 pattern(s) tried: ['detalle/(?P[0-9]+)/$'] I also tried to solve it with get_absolute_url but it only returns the same screen #Models.py ` class Documento(models.Model): Num = models.AutoField(primary_key=True) doc = models.CharField(max_length=300, blank=True, null=True) Adjunto = models.FileField(upload_to='project', blank=True, null=True) LOPSRMEP = models.CharField(max_length=50, blank=True, null=True) Adjunto_lop = models.FileField(upload_to='project', blank=True, null=True) RLOPSRMEP = models.CharField(max_length=50,blank=True, null=True) Adjunto_rlo = models.FileField(upload_to='project', blank=True, null=True) etapa = models.ForeignKey(Etapa, on_delete=models.CASCADE) CeCo = models.ForeignKey(Obra, on_delete=models.CASCADE) creado = models.DateTimeField(auto_now_add=True) modificado = models.DateTimeField(blank=True) def __str__(self): return self.doc #urls.py from django.urls import path from .views import HomePageView, DetalleProyecto#, detalle from core import views app_name = 'libro' urlpatterns = [ path('', HomePageView.as_view(), name="home"), #path('catalogo/', CatalogoPageView.as_view(), name="catalogo"), path('busqueda/', views.busqueda, name="busqueda"), # path('documento/<slug>/', views.DetalleProyecto.as_view(), name='detalle_obra'), path('detalle/<int:pk>/', DetalleProyecto.as_view(), name='detalle_obra'), path('buscar/', views.buscar), ] #views.py def buscar(request): if request.GET["srch"]: ce=request.GET["srch"] et=request.GET["etapa"] res=Documento.objects.filter(CeCo__CeCo=ce, etapa=et).order_by('modificado') return render(request, "core/busqueda.html", {"res":res, "query":ce}) else: return render(request, "core/invalido.html") '''def detalle(request, slug): documento = Documento.objects.get(slug=slug) context = { 'documento': documento } … -
Django upgrade to version 2.2.16 adds Boto dependency
I upgraded my environment .yml file for my Django application from Django version 2.2.11 to 2.2.16. But this upgrade includes adding the boto dependency (2.49.0) to my environment file. I want to know if this dependency is necessary. If so -Is there any Django documentation that explains why? -
Element of class <myClass> is not JSON serializable in request.session
In my project i have this class: class priceManage(object): def __init__(self,uid): self.uid = uid def getRealPrice(self): tot_price = 0 plist = e_cart.objects.filter(e_uid_id = self.uid, e_ordnum__isnull = True).select_related() for x in plist: tot_price += x.e_prodid.getRealPrice()*x.e_qta return float(tot_price) but when i try to store my object reference in request.session: if not 'tot_cart' in request.session: request.session['tot_cart'] = priceManage(request.user.id) i get the error: Object of type priceManage is not JSON serializable How can i save my instance reference in a request.session dict for call methods in every part of my code? So many thanks in advance -
CSRF verification failed on safari browsers only
My form is referenced outside my site via iFrame, the {% csrf_token %} is set in the form, the nginx config allows for that wordpress site to use my form and after form submission it redirects to a thank you post thats also hosted by me, but for some reason when the person filling out the form uses safari browser its giving me a error 403 csrf verification failed, I've tried having them enable cookies on their safari browsers but apparently they are still receiving the error. The form code is too big to post here but here's the view that processes that form submission. def add_reg_cf_issuer_part1(request): is_private = request.POST.get('is_private', False) postIssuerCompanyName = request.POST.get('issuerCompanyName') try: newIssuer = Issuer.objects.get(issuerCompanyName=postIssuerCompanyName) except ObjectDoesNotExist: doesNotExist = True else: doesNotExist = False return redirect("/company-registered") postEmail = request.POST.get('issuerEmail') nothingstring = 'None' postFirstName = request.POST.get('issuerFirstName') postLastName = request.POST.get('issuerLastName') postIssuerTitle = request.POST.get('issuerTitle') postIssuerPhone = request.POST.get('issuerPhone') postIssuerCompanyName = request.POST.get('issuerCompanyName') postCompanyType = request.POST.get('companyType') postStateOfIncorporation = request.POST.get('StateOfIncorporation') postDBA = request.POST.get('DBA') postIssuerCountry = request.POST.get('issuerCountry') postIssuerState = request.POST.get('issuerState') postIssuerCity = request.POST.get('issuerCity') postIssuerAddress = (request.POST.get('q46_businessAddress') or nothingstring)+" "+(request.POST.get('q47_businessAddress47') or nothingstring) postIssuerZip = request.POST.get('issuerZip') postIssuerHomepage = request.POST.get('issuerHomepage') q1=(request.POST.get('q1') or nothingstring) q2=(request.POST.get('q27_haveYou') or nothingstring)+" "+(request.POST.get('q2') or nothingstring) q3=(request.POST.get('q28_areYou') or nothingstring)+" "+(request.POST.get('q3') or nothingstring) q4=(request.POST.get('q30_haveYou30') or nothingstring)+" … -
Django TemplateSyntaxError :- How access Dictionary values for iteration?
I have one list and dictionary. Where list values are keys of dictionary. Want to display this data on html page like there will be 3 tables first is Per page B&W print, second "Per page front and back B&W print" and third Per page Color print as in tableTitle list. now in table data will come from respective key of complext_dict. so final output should like this:- table 1:- Per page B&W print and table rows are 2 first abcd.pdf and second abc,pdf. table 2:-Per page front and back B&W print and table rows are zero table 3:-Per page Color print and table row is one rp.pdf tableTitle = ["Per page B&W print", "Per page front and back B&W print", "Per page Color print",] complex_dict = {'Per page B&W print': ['abcd.pdf', 'abc.pdf'], 'Per page front and back B&W print': [], 'Per page Color print': ['Rp.pdf']} Here is the HTML template {% for title in tableTitle %} <div class="card"> <div class="card-body"> <p>{{title}}</p> <table class="table table-striped table-responsive"> <thead> <tr> <th scope="col">#</th> <th scope="col">Documet Name</th> <th scope="col">Action</th> </tr> </thead> <tbody> {% for file in complexDict.title%} <tr> <td>{{forloop.counter}}</td> <td>{{file}}</td> <td>Action</td> </tr> {% endfor %} </tbody> </table> </div> </div> ** app/views.py ** def userDashboard(request): … -
Filtered consultation in django
Good morning, I want to make a post consultation by profile type but the relation of post is with profile and profile if you have a profile type. post_suggest_type_profile = Post.objects.all().filter() model profile class Profile(AppModel): """Profile Model. model used to store those created by users. """ user = models.OneToOneField( "users.User", related_name='profile', on_delete=models.CASCADE, blank = True, null = True, ) profile_type = models.ForeignKey( "users.ProfileType", related_name='profiles', on_delete=models.CASCADE, blank = True, null = True, ) model Post class Post(AppModel): """Post Model. model used for storing users' posts. """ class Meta: ordering = ['-created'] profile = models.ForeignKey( "users.Profile", related_name="posts", on_delete=models.CASCADE, blank = True, null = True, ) -
django webapplication which should support windows and should handle multiple request
suggest me some server for Django web application which should support windows and should handle multiple request. currently I'm using wsgi,it handling only single request. I need to replace the server which should handle multiple request at a time. -
Custom Upload Handlers in Django
I'm trying to create my own custom upload handlers on Django with the goal of being able to upload sub-directories. I ccouldn't find any resouce to build my own upload handlers so I saw Django Upload Handler on Github I basically copy and paste it in the begining to check all works fine and then make my changes, but I'm missing something, because it doesn't return the files to the request, so I'm currently lost, I think maybe that Django uploads handlers isn't what I think it is and needs some changes in order to work, but I neither know what changes, because the handler doesn't return any NotImplementedError. Any suggestion will be much appreciated. -
django(python), invalid literal for int() with base 10: '' Problems arise
class DoctorList(models.Model): d_code = models.AutoField(primary_key=True) name = models.CharField(max_length=300) position = models.CharField(max_length=200) code = models.ForeignKey(HospitalList, on_delete=models.CASCADE, db_column="code") def __str__(self): return str(self.d_code) def increment_helpdesk_number(): last_helpdesk = DoctorList.objects.all().order_by('d_code').last() help_id = last_helpdesk.help_num help_int = help_id[13:17] new_help_int = int(help_int) + 1 new_help_id = 'd_' + str(new_help_int).zfill(4) return new_help_id help_num = models.CharField(max_length=17, unique=True, default=increment_helpdesk_number, editable=False) error code: invalid literal for int() with base 10: '' Request Method: POST Request URL: http://127.0.0.1:8000/api/doctor/ Django Version: 3.1 Exception Type: ValueError Exception Value: invalid literal for int() with base 10: '' Exception Location: D:\test\Backserver\test\src\com\doctor\models.py, line 22, in increment_helpdesk_number I want to create an autofield called d_0001, d_0002 d_0003... To do that, I referred to this site. Reference link But ValueError: invalid literal for int() with base 10: '' I get an error. How can I fix it? -
Is Django a backend or full stack framework [closed]
First of all, I'm an Android Developer, I want to learn how to make a restful APIs for my apps on my own, I want to go with Django to accomplish that. Currently, I'm going through the official tutorials and I'm doing very well, but I have questions about it I couldn't find useful answers on the web First: is Django a full stack or backend? can someone use Django for backed stuff and the front end developer work on the front end? Do I need to know about HTML, CCS, and javascript to be a backend developer? how much I need to know about Django to start building APIs. if you notice any misconceptions on my question please let me know, I'm new on web stuff. -
How to create a cart with Django rest framework?
I'm coding a REST API with Django REST framework I want to create a cart for a coffee shop with Django rest but I don't know how to create views and serializers.py for my project . I created my models and the cart class but I can't write views.py and Serializers.py and urls.py please help me . this is my model and cart class: #models.py from django.db import models from coffishop import settings class Food(models.Model): name = models.CharField(max_length=100) price = models.PositiveIntegerField() type = models.CharField(max_length=50) info = models.TextField() image = models.ImageField(upload_to='images/') def __str__(self): return self.name class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='orders') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) class Meta: ordering = ('-created',) def __str__(self): return f'{self.user} - {str(self.id)}' def get_total_price(self): total = sum(item.get_cost() for item in self.items.all()) class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='items') product = models.ForeignKey(Food, on_delete=models.CASCADE, related_name='order_items') price = models.IntegerField() quantity = models.PositiveSmallIntegerField(default=1) def __str__(self): return str(self.id) def get_cost(self): return self.price * self.quantity #cart class from menu.models import Food CART_SESSION_ID = 'cart' class Cart: def __init__(self, request): self.session = request.session cart = self.session.get(CART_SESSION_ID) if not cart: cart = self.session[CART_SESSION_ID] = {} self.cart = cart def __iter__(self): food_ids = self.cart.keys() foods = Food.objects.filter(id__in=food_ids) cart = self.cart.copy() … -
How can I make my text appear below the navbar?
I'm currently coding my first website and I'm experiencing a problem I don't know how to solve. I have a home page with a navbar, and when I put text in the page, it appears cut because the text starts behind the navbar. How can I make the text appear below the navbar? Here's the code. {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset= "UTF-8"> <title>DNA TRANSLATOR</title> <meta charset= "UTF-8"/> <meta name= "viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href= '{% static "css/style.css" %}'> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script> <style> body { background-attachment: fixed; background-color: rosybrown; } </style> </head> <body> <nav class="navbar fixed-top navbar-expand-lg navbar-light" style='background-color: snow;'> <div class = 'container'> <a class="navbar-brand" href="#">DNA Translator</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarTogglerDemo01"> <ul class="navbar-nav mx-auto"> <li class="nav-item active"> <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="">Translator</a> </li> <li class="nav-item"> <a class="nav-link" href="#" >Process</a> </li> </ul> </div> </div> </nav> <div class = "container"> {% block content%} {% endblock content%} </div> </body> </html> -
Django Rest Framework — no module named rest_framework. Rest_framework is installed and venv is active
I clone repository from github on my second computer, runserver does works but when typing python manage.py makemigrations Bash notice about 'no module name rest_framework' This situation is a second time. Lately I install again rest_framework but then I had install other modules. Finally I create new project but now I want resolve this problem. Screenshot is below with my venv and packages enter image description here -
How to store a large, very frequently accessed list on a server using Django?
So I'm creating a video streaming application using Django. I'm using Cassandra as my database to hold all user content, and video content. Eventually once I'm finished, the app is going to run in the Amazon cloud. Each video held in the database has about 10 (give or take) columns in it, ranging from large text files to small floats. In my app, I have a function that goes through every video entry in the database and saves each one as a dictionary (matching column names to column values as key names and values), and then creates a large list of all of the dictionaries. The database is constantly changing (every time any user watches something it changes), so the function has to run every time the page loads in order to have the most up-to-date video files. This is leading to a clear issue, in that if the list becomes very large - say 100,000+ videos - then the program is having to search through and modify 100,000+ items in a list every time the page loads. My question is, how do I go about having a list of videos on the server that is constantly being updated and … -
How to use in built Auth model in django to manage login for 4000-5000 users belongs to different Company
I am new to Django and i am working on one requirement where i have multiple company for example A,B,C,D and each Company will have 1000 Users. I have used Django inbuilt Auth Module for authentication purpose and created one model as shown below. class ShiftChange(models.Model): ldap_id = models.CharField(max_length=64) Vendor_Company = models.CharField(max_length=64,choices=VENDOR_CHOICES,default='genesys') EmailID = models.EmailField(max_length=64,unique=True) Shift_timing = models.CharField(max_length=64,choices=SHIFT_CHOICES,default='General_Shift') Reason = models.TextField(max_length=256) # updated_time = models.DateTimeField(auto_now=True) Below are the things which i have created. For login i'm using django inbuilt User model and i am using email id to filter result as shown below in my view so in this when user is login based on his email id data getting filter and he Can see only his data. def retrieve_view(request): # alluser = ShiftChange.objects.all() alluser = ShiftChange.objects.filter(EmailID=request.user.email) # alluser = ShiftChange.objects.filter(ShiftChange.ldap_id == request.user.username) return render(request, 'apple/shift2.html', {'alluser': alluser}) Task: Instead of asking all 4000 user to login by Creating account i want if this can be possible by creating some group from django admin where i Can add all user belonging to one Company and create only one login access and share it with respective POC of Company A(Company A person should not see data of Company B,C,D). 2.other way … -
How can I get URL of model being serialized in Django REST Framework?
I am trying to create an API using Django REST Framework that looks like this: [ "expression": { "expression": e, "url": e_url }, "definition": d ] I am having problems retrieving the url field inside the expression object. I am trying to use HyperlinkedRelatedField but could not make it work. I want to point out that url is NOT a field in my Expression model. class ExpressionSerializer(serializers.ModelSerializer): url = serializers.HyperlinkedRelatedField( view_name="dictionary:expression", lookup_field="slug", read_only=True, many=False, ) class Meta: model = Expression fields = ["url", "expression"] class DefinitionSerializer(serializers.ModelSerializer): expression = ExpressionSerializer(many=False) class Meta: model = Definition fields = ["expression", "definition"] How can I retrieve the URL for expression? -
How can I test registering jira issue in Django
I'm trying to test function that connects to Jira and creates Jira issue My services.py def get_jira_client(): global jira_client if jira_client is None: jira_client = JIRA(server=JIRA_URL, auth=(jira_user, jira_password)) return jira_client def register_jira_issue(ticket_id): jira = get_jira_client() ticket = Ticket.objects.prefetch_related(Prefetch('attachments', to_attr='ticket_attachments'), Prefetch('tags', to_attr='ticket_tags')).filter(id=ticket_id).first() new_issue = add_issue(jira, ticket, ticket.owner) set_tags(new_issue, *ticket.ticket_tags) add_attachments(ticket.ticket_attachments, new_issue) def add_issue(jira, ticket, owner): issue_dict = { 'project': {'key': project_key}, 'summary': ticket.title, 'description': format_text_for_jira(ticket.description), 'issuetype': {'name': issuetype_name}, cf_username: str(owner.username), cf_hd_grant_id: ticket.grant_id, cf_user_email: str(owner.email), cf_user_fullname: f"{owner.first_name} {owner.last_name}" } new_issue = jira.create_issue(issue_dict) ticket.key = new_issue ticket.save() logger.info(f'User {ticket.owner} added issue ') return new_issue def set_tags(jira_issue, tags): tags_dict = Tags.objects.filter(id=tags.id).values()[0] chosen_tags = [key for key, _ in tags_dict.items() if _ is True] if tags_dict['cluster_calculations'] or tags_dict['cluster_installation']: chosen_tags.append(tags_dict['cluster']) jira_issue.update(fields={"labels": chosen_tags}) logger.info(f'User set tags {chosen_tags} to issue {jira_issue}') def add_attachments(files, jira_issue): jira = get_jira_client() for file in files: jira.add_attachment(issue=jira_issue, attachment=file.file) logger.info(f'User added attachment {file} to issue {jira_issue}.') function register jira issue is asynchronously called in views.py and it uses these functions: add_issue - registers issue in jira set_tags - sets labels for issue add_attachments - adds attachment to issue Does anyone know a way to test ticket registration in jira? I've tried requests_mock but it didn't work for me. I also saw some exapmples of … -
How do I revert an unfinished makemigration after adding a non-nullable field(Foreign) and filling it
I made the mistake of adding a non-nullablle field and filling it with 1. contest = models.ForeignKey(Contest, on_delete=models.CASCADE) (Contest is empty, new table) >>> python manage.py makemigrations contests You are trying to add a non-nullable field 'contest' to contestentry without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option: 1 Please enter the default value now, as valid Python The datetime and django.utils.timezone modules are available, so you can do e.g. timezone.now Type 'exit' to exit this prompt >>> 1 When migrating it gave an error because the table of the model is empty. >>> python manage.py migrate contests psycopg2.errors.ForeignKeyViolation: insert or update on table "contests_contestentry" violates foreign key constraint "contests_contestentr_contest_id_7f53b874_fk_contests_" DETAIL: Key (contest_id)=(1) is not present in table "contests_contest". I removed the field and tried to migrate back but it didn't work then I tried to revert the migrations but it gave the following error: >>> python manage.py migrate contests 0007_remove_contestentry_nvotes Operations to perform: Target specific migration: … -
I want to change django's AutoField value
mycode.py class playerList(models.Model): d_code = models.AutoField(primary_key=True) name = models.CharField(max_length=300) position = models.CharField(max_length=200) def __str__(self): return str(self.d_code) Currently, the value of d_code is created as 1,2,3,4... What I want is to stretch like d_0001, d_0002, d_0003... How can I make it like this? Is that difficult? Please let me know