Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pagination from django_tables2 not rendering
I am relatively new in Django and could not find any answer here on why my table from django_tables2 is not rendering nice pagination buttons. Here follows the codes: models.py class IDOC(models.Model): on_delete=models.SET_NULL, null=True) sample_id = models.CharField(max_length=200) lon = models.FloatField(null=True, blank=True) lat = models.FloatField(null=True, blank=True) dp_position = models.IntegerField(null=True, blank=True, verbose_name='DP Position [-]') def __str__(self): return self.sample_id tables.py class IDOCTable(tables.Table): sediment_depth_m = NumberColumn() wl_m = NumberColumn() H_m = NumberColumn() idoc_mgl = NumberColumn() temp_c = NumberColumn() idoc_sat = NumberColumn() class Meta: model = IDOC template_name = "django_tables2/bootstrap-responsive.html" views.py def view(): idoc_objects = IDOC.objects.all() idoc_show = flutb.IDOCTable(idoc_objects) context = { 'idoc_table': idoc_show, } return render(request, 'flussdata/query.html', context) flussdata/query.html {% extends 'base.html' %} {% load django_tables2 %} {% block content %} <div class="row"> <div class="col-md"> <div class="row"> <div class="card card-body"> <h3>Intragravel Dissolved Oxygen Content</h3> {% render_table idoc_table %} </div> </div> </div> </div> Then, my tables is rendered like this: Instead of the way it should, which I believe is like this: -
Simple JWT Usage
I have my Django backend authentication working (tested using curl and postman) but something eludes me. When sending test requests, the docs show username and password data being sent: curl \ -X POST \ -H "Content-Type: application/json" \ -d '{"username": "davidattenborough", "password": "boatymcboatface"}' \ http://localhost:8000/api/token/ but, if I try to send email and password instead, the response says that the username is a required field. Where and how can I change that behavior? Thanks! -
Can two models reference each other by ForeignKey?
I have two models class Customer(models.Model): name = models.CharField(max_length=255, unique=True) default_contact = models.ForeignKey("CustomerContact", verbose_name="...", related_name="default_contacts", null=True, on_delete=models.SET_NULL) etc. And class CustomerContact(models.Model): customer = models.ForeignKey(Customer, related_name='contacts') user = models.OneToOneField(User, related_name='user_contacts', on_delete=models.SET_NULL) address = models.ForeignKey(CustomerAddress, ....) In this example Customer points to CustomerContact. At the same time CustomerContact points to Customer. My coworker says that pointing Customer points to CustomerContact violates the OneToMany nature of ForeignKey. What am I doing wrong? -
Search and page functionality disappearing for any additional data tables on webpage
Strange issue, but for some reason whenever I add any additional data tables to my site on the same page, the additional tables populate just fine but are missing the search and page functionality. I am using datatables.net for it. What could be the reason for this? I see in the example on https://datatables.net/examples/basic_init/multiple_tables.html that it should work just fine.enter image description here {% block css %} <!-- Custom styles for this page --> <link href="{% static 'vendor/datatables/dataTables.bootstrap4.min.css' %}" rel="stylesheet"> {% endblock %} <div class="row"> <div class="container-fluid"> <div class="card shadow mb-4"> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary">Data Table 1</h6> </div> <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered" id="dataTable" width="100%"> DATA IS HERE ON MY MACHINE </table> </div> </div> </div> </div> </div> <div class="row"> <div class="container-fluid"> <div class="card shadow mb-4"> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary">Data Table 2</h6> </div> <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered" id="dataTable" width="100%"> DATA IS HERE ON MY MACHINE </table> </div> </div> </div> </div> </div> {% endblock %} {% block js_body %} {% include 'theme/components/charts_scripts.html' %} <script src="{% static 'vendor/datatables/jquery.dataTables.min.js' %}"></script> <script src="{% static 'vendor/datatables/dataTables.bootstrap4.min.js' %}"></script> <script src="{% static 'js/demo/datatables-demo.js' %}"></script> {% endblock %} -
Model object not creating from inside except block or right before raising exception
Something very strange is happening in my Django app. When I try to run the following code Model.objects.create(**obj) before raising an exception OR run the same code inside an except block, the code runs without any issue, but I cannot see the object in the database. Running the Model.objects.all() also doesn't return anything. This is the complete code: def has_permission(self, request, view): try: serializer = VerifyOTPRequestSerializer(data=request.data) serializer.is_valid(raise_exception=True) otp = request.data.pop("otp") flow = request.data.pop("flow") primary_phone = request.data.get("contact_detail", {}).get( "primary_phone", "" ) if OTPFailedAttempts.objects.filter(phone=primary_phone).count() > 0: raise Exception("otpAttemptError") return helpers.OTPHelper.verify_otp(primary_phone, otp, flow) except Exception as permission_error: OTPFailedAttempts.objects.create(**{"phone": primary_phone, 'email': email}) return False Is there a particular reason why Django doesn't allow object creation of objects around exceptions or am I doing something wrong? -
How Do I Detect And Properly Display Events On Calendar That Overlaps Months in Python?
I used a tutorial I found online to create an event calendar in Python. I've tried to improve it to schedule events that may have a start and end time range that overlap months. Meaning it may start in June and end in July. I've got it partially figured out...I can display the events based on the start day being lte day in the Python HTMLCalendar module. I can't figure out how to pick up the remaining day for July 1. June displays perfectly. Thanks in advance for any thoughts. Here's my code... HTMLCALENDAR Utility.. class Calendar(HTMLCalendar): def __init__(self, year=None, month=None, dropdown=None): self.dropdown = dropdown self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, requests): requests_per_day = requests.filter(start_time__day__lte=day,start_time__month=self.month) d = '' for request in requests_per_day: d += f'<li> {request.get_html_url} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek, requests): week = '' for d, weekday in theweek: week += self.formatday(d, requests) return f'<tr> {week} </tr>' # formats a month as a table # filter events by year and month def formatmonth(self, withyear=True): # … -
How Do I Detect And Properly Display Events On Calendar That Overlaps Months in Python?
I used a tutorial I found online to create an event calendar in Python. I've tried to improve it to schedule events that may have a start and end time range that overlap months. Meaning it may start in June and end in July. I've got it partially figured out...I can display the events based on the start day being lte day in the Python HTMLCalendar module. I can't figure out how to pick up the remaining day for July 1. June displays perfectly. Thanks in advance for any thoughts. Here's my code... HTMLCALENDAR Utility.. class Calendar(HTMLCalendar): def __init__(self, year=None, month=None, dropdown=None): self.dropdown = dropdown self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, requests): requests_per_day = requests.filter(start_time__day__lte=day,start_time__month=self.month) d = '' for request in requests_per_day: d += f'<li> {request.get_html_url} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek, requests): week = '' for d, weekday in theweek: week += self.formatday(d, requests) return f'<tr> {week} </tr>' # formats a month as a table # filter events by year and month def formatmonth(self, withyear=True): # … -
How to print out request.body data in django?
Just working through the Django tutorials and playing around with stuff. Was going through the HttpResponse and HttpRequest docs and I'm just trying to print out data to see how things work. However, when I try to print to console the request.body I get nothing back. def detail(request, question_id): current_question_selected = Question.objects.get(pk=question_id) choices_for_question = current_question_selected.choice_set.all() context = {"choices_for_question":choices_for_question, "current_question_selected":current_question_selected} #print(request.META["REMOTE_USER"]) print(request.body) return render(request, 'polls/detailtext.html', context) This is what gets pritned to the screen, the letter 'b' with an empty string [28/Jun/2022 10:59:56] "GET /polls/1/ HTTP/1.1" 200 456 b'' Not sure what i'm missing -
Sending mail now for testing after disabling the less secure app setting in gmail
I was trying to send mail to test one of my Django Rest Framework projects. I know I have to turn on the "Less Secure Apps Permission" for Gmail to receive the mail from the localhost. But Google disabled that setting from June 30. There's no error But I am not receiving the emails. I've tried using the app passwords from gmail but it's not working as well. Now how I can be able to send emails from localhost? -
Django multiple image upload CRUD funcionality with two forms
I want to let the user upload multiple images per product like in an ecommerce application. Therefore I created two models. In forms.py I added the ImageField to the ProductForm. My create_product view seems to work but I do not really know how I can create the update and delete view. Thanks! models.py class Product(models.Model): owner = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.CASCADE) title = models.CharField(max_length=200) describtion = models.TextField(null=True, blank=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) class ProductImage(models.Model): project = models.ForeignKey(Product, on_delete=models.CASCADE) image = models.FileField() forms.py class ProductForm(ModelForm): image = forms.ImageField(widget=ClearableFileInput(attrs={'multiple':True})) class Meta: model = Product fields = ['title', 'describtion'] views.py def create_product(request): form = ProductForm() profile = request.user.profile if request.method == 'POST': form = ProductForm(request.POST) images = request.FILES.getlist('image') if form.is_valid(): project = form.save(commit=False) project.owner = profile project.save() for i in images: ProductImage.objects.create(project=project, image=i) context = {'form':form} return render(request, 'projects/project_form.html', context) -
Django and OpenApi compliance
We are using Django for our api development and we need to be OpenAPI 3.0 compliant. In this article it is written that "Django Automates generation of OpenAPI 3". Do we need to do anything extra for this or by default the api(developed in Django) is OpenAPI complaint? How can we test/ verify this? -
Django Project, Versioning Management
Is there a way to run single Django app separately? First, why ? As we know, when you make a user upgrade or downgrade your system from UI inside system, if there a crash during replace changed files, then the system will break down. Second, the solution. if the UI of version control run separately, the user can redo the change to make system survive . -
django and matplotlib , how i can see the plot on html
actually when i run my code, i have a visualisation of the plot but not on html How i can see the plot on my html? ''' def inf_norm_detection(df_abs, crop_left, crop_right, clean_param=500): ''' infinum norm outlier detection, it is the first step of outlier detection computes matrix of inf norm (max of absolute values) of the samples one to onother inputs: clean_param (int) - usualy 150-500, smaller means more outliers, df_abs (pandas DataFrame) - data of interest, usualy absorbance or asmptotic data crop_left, crop_right - values to crop the data according to MPF measurments. output: indexes of df_abs that are suspected to be outliers, if none were identified, None is returned ''' X = df_abs.iloc[:, crop_left:crop_right].to_numpy() l = X.shape[0] D = np.zeros((l, l)) idx = range(len(X)) for j in range(1, X.shape[0]): idx = list(set(idx) - {j}) A = X[idx] - X[j] D[j, idx] = np.abs(A).max(1) D = np.maximum(D, D.transpose()) d = D.sum(0) / l diff = np.sort(d)[1:] - np.sort(d)[:-1] if np.where(diff > clean_param * np.median(diff))[0].size != 0: threshold = np.sort(d)[np.where(diff > clean_param * np.median(diff))[0] + 1].min() return df_abs.iloc[np.where(d >= threshold)].index def show_absorbance(df_abs, crop_left, crop_right, clean_param): outliers = inf_norm_detection(df_abs,crop_left, crop_right, clean_param) colors = [color for color in mcolors.CSS4_COLORS.values() if color !='yellow'] … -
How can I run 4 tests at once during parallel tests on 4 different processes with Django tests?
I'm trying to test if my tests are properly isolated, and I'm scratching my head what is the easiest way to do this. Basically what I need is some barrier implementation. 4 processes stops, picks up each of the test, wait until all of them are ready I must call tests with python manage.py test --parallel each test is a class what I have: class TestCacheIndependentInParallel: def test_cache_not_varying(self): cache.set('key', self.cache_value) for _ in range(100): self.assertEqual(cache.get('key'), self.cache_value) time.sleep(random.uniform(0.001, 0.005)) cache.set('key', self.cache_value) class TestCachesIndependentInParallel_1(TestCase, TestCacheIndependentInParallel): cache_value = 1 class TestCachesIndependentInParallel_2(TestCase, TestCacheIndependentInParallel): cache_value = 2 class TestCachesIndependentInParallel_3(TestCase, TestCacheIndependentInParallel): cache_value = 3 class TestCachesIndependentInParallel_4(TestCase, TestCacheIndependentInParallel): cache_value = 4 I must be sure tests 1-4 are truly executing in parallel to each other. -
Receive Discord messages via socket in python/Django
Previously I was using Gateway to connect with discord ws = websocket.WebSocket() ws.connect('wss://gateway.discord.gg/?v=6&encording=json') while True: event = recieve_json_response(ws) but now this While True is causing issues it is not working for multiple users . Is there any way to connect to discord and receiving messages live from it . I tried discord.py bot but I think for that I need my own server but in my current scenerio I am not the owner of that discord server from where I want message I am just a member -
Getting error while redirecting to some page in django(python)
I am getting the following error: Reverse for 'showuser' with keyword arguments '{'bid': 1}' not found. 1 pattern(s) tried: ['showuser/(?P[0-9]+)\Z'] urls.py path('showuser/<int:broadcastid>', views.showuser, name="showuser") views.py def showuser(request, broadcastid): vrbrlstnm = BroadcastListSms.objects.get(id=broadcastid) showDepartment = AddContact.objects.values('dept_nm').distinct() if request.method == "GET": if request.GET.get('select') == "All": departmentData = AddContact.objects.all() else: departmentData = AddContact.objects.filter(dept_nm=request.GET.get('select')) return render(request, "showuser.html", {'adduser': vrbrlstnm, 'showDepartment': showDepartment, 'departmentData': departmentData}) return HttpResponseRedirect("showuser", {'showDepartment': showDepartment, 'departmentData': departmentData}) adduser.html <a href="{% url 'showuser' int:broadcastid=adduser.id %}" class="btn btn-primary"> Add Existing User </a> Note: adduser.id is the foreign key value, from where we get broadcastid. I am stuck here from so many days. Not able to understand what to do now. models.py class BroadcastListSms(models.Model): brl_name = models.CharField(max_length=100, null=False) class AddContact(models.Model): f_name = models.CharField(max_length=100, null=False) l_name = models.CharField(max_length=100, null=False) broadcast_list = models.ForeignKey(BroadcastListSms, on_delete=models.CASCADE, related_name='adduser', null=True) -
Azure web app not copying code from tmp to home
I am deploying a Django appication to a Azure Web App via Github Actions. The code is deployed to the tmp folder but is never copied to wwwroot. What can be the cause of this? -
Combine Data of Two Tables in single DropDown using Django
Problem: I have Two Tables Users and Users Group and in front end on request of that particular page need to send all data from both the table together, as there is specific drop down to show them both, and after done with the operation of that page data will get back in POST request (current models structures is given below), i am not getting how do i make connection in all these three tables so that it will get managed, Please let me know. Model: User.py class Users(AbstractBaseUser): vendor_name = models.ForeignKey(Vendor, on_delete=models.CASCADE, default=None, null=True) username = models.CharField(max_length=100, verbose_name="username", unique=True) password = models.CharField(max_length=100) created_by = models.DateField(verbose_name="created_by", auto_now_add=True) USERNAME_FIELD = "username" REQUIRED_FIELDS = ['password', 'hardware_id'] is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_role_vendor = models.BooleanField(default=False) is_role_customer = models.BooleanField(default=True) def __str__(self): return self.username objects = UserManager() Model: UserGroup.py class UserGroup(models.Model): vendor_id = models.ForeignKey(Vendor, on_delete=models.CASCADE, default=None, null=True) id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) description = models.CharField(max_length=1000) users = models.ManyToManyField(Users) def __str__(self): return self.name Model: Rules.py class Rules(models.Model): vendor_id = models.ForeignKey(Vendor, on_delete=models.CASCADE, default=None, null=True) id = models.IntegerField(primary_key=True) name = models.CharField(max_length=100) description = models.CharField(max_length=1000) # Here i need to mention the code for field where i can store the combined value of User and UserGroup [selected … -
Working with Wagtail on Replit, facing "common-passwords.txt.gz" error
So, I am trying to pip install Wagtail in a Python repl. But when I start a project and try to create a superuser, I get the following issue: FileNotFoundError: [Errno 2] No such file or directory: '/home/runner/.cache/pip/pool/f7/e7/0e/common-passwords.txt.gz' It seems Wagtail cannot seem to find the common-passwords.txt.gz file for some reason. Any way I can solve this? Thanks in advance,,, -
I need to affected row count in PostgreSQL Python or Django when run same query 2 or more time
I need to get all affected row count in PostgreSQL . If i run update query then got right row count but if i run again same query then i also get same row count but i think second time no row affected so in this case row count will be 0. Here is my simple code import psycopg2 #db connection conn = psycopg2.connect( host="localhost", database="test_db", user="postgres", password="123456" ) #Setting auto commit false conn.autocommit = True #Creating a cursor object using the cursor() method cursor = conn.cursor() sql = "UPDATE test_table SET balance = 11 WHERE last_block = '14529343'" cursor.execute(sql) print("Rows returned = ",cursor.rowcount) conn.commit() conn.close() #Closing the connection After run this python script my current row affected is: Rows returned = 70 second time also same output Rows returned = 70 but it is not correct, result will be 0 but if i run same update query then same result but in this case output will be 0. This is screenshot -
How to add header when we writing test cases in django rest framework?
I'm trying to write test cases for my project. Now the problem is, that I don't figure out how to pass custom keyword arguments in the header. Here's my test case class below. class ProjectTestClass(APITestCase,URLPatternsTestCase): allow_database_queries: True def projects_notifications_list(self,token,project_key): url = reverse('projects:project_noti_list',kwargs={"category": "all"}) response = self.client.get( url, format='json', HTTP_AUTHORIZATION="JWT "+token, headers={"platform-subscriber-id":project_key} ) print("data -> ",response.data) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(len(response.data), 3) as you can see I'm passing plaform-subsciber-id in the header. but getting an error that {'message': 'Platform subscriber id is required in header'}. It seems like id is not properly configured in the header. Does anybody know this? -
Django: send notifications at user based on database change
I have 3 database tables: users (stores info about users e.g. email, name) metadata (stores data) activity (stores changes made to users/metadata tables) I want to achieve the following: to store any change into the activity table (e.g. new user is created, a user updates the metadata table) to send notifications to users whenever a change into the users/metadata tables happens. What are the libraries/method that I could use in order to achieve the desired functionalities? Thank you! -
How yo get Parameters in swagger Post Request Django
I am not able to get request parameter in my post request on swagger . I am using Classes based components in my project . I am using drf_yasg module in my project to integrate swagger . I am not using any database for now in my project . enter image description here -
Cannot get te value from HTML buttons to Django view
Here's my original HTML with the "radio" buttons: <div data-value="attending" class="radio-tempo col-sm-12"> <button class="btn btn-default active" data-value="yes"><i class="fa fa-smile-o"></i>Yes</button> <button class="btn btn-default" data-value="no"><i class="fa fa-frown-o"></i>No</button> </div> I wanted to capture the values into my POST request so I modified it and added names and values to my HTML code: <div data-value="attending" class="radio-tempo col-sm-12"> <button name="button_yes" value="yes" class="btn btn-default active" data-value="yes"><i class="fa fa-smile-o"></i>Yes</button> <button name="button_no" value="no" class="btn btn-default" data-value="no"><i class="fa fa-frown-o"></i>No</button> </div> And the views.py def index(request): if request.method == 'POST': print(request.POST) The output: <QueryDict: {'csrfmiddlewaretoken': ['zSRXL8dUDyWlSMdnHs3qTrNHWOHu3WC9eOWnDuI4wW95VvndDArPlS4vGPFTooDs'], 'FirstName': ['John'], 'LastName': ['Smith'], 'Message': ['bla bla']}> What am I doing wrong? I know that best way would be to use plain radio buttons but I would like to avoid CSS styling of the radio buttons and keep the original HTML template elements. -
Django is_staff flag resets every time user log in
How to set is_staff flag permanently? I have LDAP connected to my Django app. When i set up is_staff flag in admin panel its all ok but when this user relogs it is changed back to no-flag. Is there any way to prevent changing it back and set is_staff flag permanently?