Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to run the "manage.py runserver" command in PyCharm by pressing the up arrow on every time?
When I open the Pycharm the first time or killed the terminal after executing some commands, I need to type the "manage.py runserver" command (or other commands) every time. Is it possible to run the last used command by pressing the up arrow? -
Bootstrap Carousal doesn't change next/previous picture
So I've been trying to make a portfolio website in Django, I've been following some tutorial for this. The Carousal on my page doesn't seem to change images when clicking next/previous button. The images displays properly (need to resize it for appropriate looks) but no matter what I do it won't show next/previous image. I am providing the carousal code and the whole html code: Carousal code: <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <img class="d-block w-100" src="https://source.unsplash.com/1600x800/?food,food" alt="First slide" style="width:100%;"> </div> <div class="carousel-item active"> <img class="d-block w-100" src="https://source.unsplash.com/1600x800/?cat,cat" alt="Second slide" style="width:100%;"> </div> <div class="carousel-item active"> <img class="d-block w-100" src="https://source.unsplash.com/1600x800/?car,car" alt="Third slide" style="width:100%;"> </div> </div> <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> Whole HTML code: <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous"> <script src="js/bootstrap.js"></script> <title>Home</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="#">OMEGA</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria- expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link … -
Django extremely slow page loads when using remote database
I have a working Django application running fine locally using an sqlite3 database. However, when I change the Django database settings to use my external AWS RDS database all my pages start loading extremely slow. Sometimes up to 40 seconds latency for each page. I have checked my AWS metrics and my instance is not even close to being fully utilized. How can I diagnose what is causing this latency? My app was finished and getting ready to be deployed so I am desperate for answers at this point.. AWS monitoring -
Performing actions on a related model while saving
Guys and girls, I need help. For several days now I have been unable to figure out how to get around one problem. I would appreciate any idea or advice. For simplicity, there is a set of models: class A(models.Model): name = models.CharField(max_length=255) class B(models.Model): name = models.CharField(max_length=255) owner = models.ForeignKey(A, on_delete=models.CASCADE, null=False) def foo(): do something The number of instances of B belonging to A is not known in advance. The number of instances of B is determined by the user at the time of creating a new instance of A. Moreover, he can create an instance of A without creating a single instance of B (empty set). Challenge: I need to run foo after saving a new instance of A. This function should handle both the fields of the new instance of A and fields of B (back relation). Yes, I set the receiver to post_save signal model A. But here's the problem, at the moment when A is already saved (post_save), instances of B have not yet been saved (pre_save), and the values of the corresponding fields have not been determined. In other words, I cannot get raw B values in receiver A. Any ideas? Am I … -
celery worker ,is not working ,if i can write project name then working and results is not disabled
-------------- celery@krishna-H310M-S2 v5.0.5 (singularity) --- ***** ----- -- ******* ---- Linux-5.8.0-45-generic-x86_64-with-glibc2.29 2021-03-17 17:04:03 *** --- * --- ** ---------- [config] ** ---------- .> app: default:0x7ff4a3f2cf70 (.default.Loader) ** ---------- .> transport: amqp://guest:**@localhost:5672// ** ---------- .> results: disabled:// *** --- * --- .> concurrency: 4 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery -
I am trying to deploy(ubuntu18.04) my DAJNGO application using django-channels, redis, nginx and daphne for websocket connection
NGINX CONFIG FILE Browser Error Nginx error Daphne Config File -
Redirect/Render many pages in DJANGO at once
I write a project in django. I've got data from MS SQL called orders - there are few rows from the table. I would like to loop it, and each of them should render new tab '/print' with some context. Like: for o in orders: HttpResponseRedirect('/print') Is this possible? -
V model on input texbox on key up updates text on other v model input text in django for loop
I have this Django for loop where i have this form with input textbox that has v model. When i type a text on it , on key up it updates text on ther input texbox inside this django for loop : {% for drama in theatre %} <div class="comment-input" id="postcomment-{{tweet.id}}"> <form v-on:submit.prevent="submit0comment({{tweet.id}})" id="comment-{{tweet.id}}" > <input id=".input_1" type="text" v-model="comment_body" class="form-control"> <div class="fonts"> <button class="btn-share">Post</button> </div> </form> </div> <br> <div class="d-flex flex-row mb-2" v-for="comment in comments"> <img :src="comment.avatar" width="40" class="rounded-image"> <div class="d-flex flex-column ml-2"> <span class="name">[[comment.commenter]]</span> <small class="comment-text">[[ comment.comment_body]]</small> <div class="d-flex flex-row align-items-center status"> <small>Like</small> <small>Reply</small> <small>[[ comment.created_at ]]</small> </div> </div> </div> {% endfor %} -
not able to hide result count in django admin list view
I have added the following in my admin file and the related pagination functions are below. But there is no change. Count is not disabled in any of the places and the list view is very slow as there are many items. My Backend is SQL server. paginator = NoCountPaginator show_full_result_count = False from cached_property import cached_property from django.core.paginator import Paginator from django.db import connection, transaction, OperationalError class NoCountPaginator(Paginator): @cached_property def count(self): return 20 class TimeLimitedPaginator(Paginator): @cached_property def count(self): # We set the timeout in a db transaction to prevent it from # affecting other transactions. with transaction.atomic(), connection.cursor() as cursor: cursor.execute('SET LOCK_TIMEOUT 200;') try: return super().count except OperationalError: return 9999999999 -
Compute average value
I have set up a table where players can input three income values in three different cells. I would like to set up a fourth cell where the average value is computed. Any idea? <table class="table-bordered" style="width:100%"> <tr style="background-color:#ffb380"> <th scope="col" colspan="1" style="text-align:center"> Anno </th> <th scope="col" colspan="1" style="text-align:center"> 2018 - 2019 </th> <th scope="col" colspan="1" style="text-align:center"> 2019 - 2020 </th> <th scope="col" colspan="1" style="text-align:center"> 2020 - 2021 </th> <th scope="col" colspan="1" style="text-align:center"> Reddito MEDIO</th> </tr> <tr style="background-color:#ffe0cc"> <td scope="col" colspan="1" style="text-align:center"> Reddito/ettaro </td> <td scope="col" colspan="1" style="text-align:center"> {% formfield 'income1'%} €/ha </td> <td scope="col" colspan="1" style="text-align:center"> {% formfield 'income2'%} €/ha </td> <td scope="col" colspan="1" style="text-align:center"> {% formfield 'income3'%} €/ha </td> <td scope="col" colspan="1" style="text-align:center"> 'inc_avg' €/ha </td> </tr> </table> {%formfield 'income1' %} and so on are integer.Field where the players inputs the values. ps I am using otree -
how to generate qr code with python and when scanned make it open a url defined?
Hi how are you? how do I generate a qr code which when scanned opens a url? is it possible to use a library like qrcode or pyqrcode to accomplish this? something like this : pyq = QRCode() pyq.generate(url="http://google.com/") thanks in advance! -
Django template var in Javascript
Let's take a dictonary: mydict = { 'color': "blue", 'brand': "Ford", 'year': 1969 } We pass this dict to our template, then, in the template, we have a select list with options according to our dictionary keys (color, brand, year). Now, I want to change some text in my rendered template regarding the selected option. So we have some Jquery that is getting the value of the selected option, like this: $('#myselect').change(function() { var selected = $( "#myselect option:selected" ).text(); }); Now that we have the selected text, I would like to use it as a key to display a value from our dictionary. Something like this $('#myselect').change(function() { var selected = $( "#myselect option:selected" ).text(); $('#mytext').text('{{ mydict.selected }}'); }); But I guess mixing Django var and JS var like this, is not going to work... Any idea how I can do this ? -
How to add new class argument while keeping the original (inherent ones)?
My problem The graphql_social_auth.SocialAuthMutation in the following Claas class SocialAuth(graphql_social_auth.SocialAuthMutation): class Arguments: id = graphene.Int(required=False) user = graphene.List(schema.Users) is passing few arguments and functionalities. But when I added class Arguments: id = graphene.Int(required=False) To it, I lost the original arguments. My goal I want to pass the new arguments while keeping the arguments and the functionalities of graphql_social_auth.SocialAuthMutation If you can't understand GraphQL Generally, in python and in Django you can pass a functionality in a class like models.Model which have hidden functionalities and argument that help you create a model without explicitly adding all the code. # models.py class Post(models.Model): # in this example if I tryied to use `class Arguments:` the arguemnts that came from models.Model will not be passed . But what I want is to keep the `models.Model` and add class`class Arguments:` ass well description = models.CharField(max_length=9999999) title = models.CharField(max_length=200) -
django-queryable-properties confusion
I ran into a problem with django-queryable-properties package. I have this model: class MyModel(Model): f1 = CharField() f2 = AnnotationProperty( annotation=RegexpMatches(source='f1', regexp=MY_REGEXP, group=1) ) objects = QueryablePropertiesManager() And the problem is: postgres throw an error when i try to filter on field f2 because postgress do not allow functions on where clause. After some researches i found that field f2 do not figure in select clause of generated sql. In other words: when i try MyModel.objects.filter(f2='a').first() the folowing sql is generated: SELECT "myapp_mymodel"."f1" FROM "myapp_mymodel" WHERE (regexp_matches("myapp_mymodel"."f1", (^m.+)_.+))[1] = 'a' And my question is: How can i add f2 into select clause to make it possible to lookup on this field using django-queryable-properties package. -
Django _set behaving just like .objects?
I have been trying to override objects behavior using a custom manager. class AbstractBase(models.Model): # ... objects = CustomManager() My objects will automatically filter out the instances that have their field is_deleted as True I was wondering... if I were to grab the same model's instances using _set.all(), would this behave just like that custom objects? Otherwise, do I have no choice but to find every _set.all() and refactor it to _set.filter(is_deleted=False)? -
is there any function or method to auto-update the attribute in record of django admin,when the record is saved
Present I am working on commerce website when the seller updates the order status to delivered condition , delivered time attribute must be auto-updated -
Simple CreateView returns 405 Method Not Allowed
Very simple CreateView is not working, and I do not know why: view: class CreateProduct(CreateView): template_name = "app/product_create2.html" form_class = ProductForm success_url = reverse_lazy("index") form: class ProductForm(ModelForm): class Meta: model = Product fields = ("description", "name", "price") def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.field_class = 'mb-2' self.helper.form_method = 'POST' self.helper.add_input(Submit('submit', 'Submit', css_class='btn-success')) urls: path("create/", views.CreateProduct.as_view(), name = 'create'), template: <div class="modal-body"> {% csrf_token %} {% crispy form %} </div> When I input Data in the form I get: Method Not Allowed (POST): / and I can seet the 405 error in the console. -
how to check if new entry is added to postgres DB?
In my Django project, I am getting new values every other second with an MQTT client and save them in Postgresql. In the front end, I try to get new values and plot them with ajax calls. Consider a situation when, for any reason, the connection gets lost and no new data comes to the DB. I want such functionality: if no new data is added to DB, then null values should be sent via AJAX. I tried checking the id of the latest object of the previous query, but I couldn't implement it for a situation when the DB is empty. -
OS Time in Python 3.8.5
I've got the following dictionary in my code: "morning": now.hour > 0, "afternoon": now.hour > 12, "evening": now.hour > 18, "bit_late": now.hour > 21, It's part of a Django project (v3.1), and whenever I run the server it throws up no errors, but it is using UTC time instead of my local system's time (+ 5 1/2 UTC). Hence, when I viewed the page at 3 PM, it wished me "Good morning" (which it's programmed to do). I've included the datetime library, but I don't know how to use it or any other library to try and get the program to run using system time. Am I missing any particular library? What method should I use to get the system time, and where do I put it? now = datetime.datetime.now() This is the code I used for "now", just for reference! Thanks in advance! -
How to pass data to the model field when saving the form? django form models save
get the form and process it in post. It is necessary to save the unique uuid of the record to the model, I do it like this: formOne.save(related_uuid=related_uuid) but doesn't work, the error is - save() got an unexpected keyword argument 'related_uuid' models class Orders(models.Model): device = models.CharField(max_length=150) uuid = models.CharField(max_length=22, blank=True) views class OrderAddView(TemplateView): template_name = 'orders/order_add.html' def get(self, request, *args, **kwargs): context = super().get_context_data(**kwargs) ... some work code return self.render_to_response(context) def post(self, request, *args, **kwargs): formOne = SimpleOrderAddForm(self.request.POST, prefix='one_form') if formOne.is_valid(): related_uuid = shortuuid.uuid() formOne.save(related_uuid=related_uuid) return HttpResponseRedirect('orders_home') else: print('NotValid') return self.form_invalid(formOne, **kwargs) def form_invalid(self, formOne,, **kwargs): context = self.get_context_data() ... some work code return self.render_to_response(context) -
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) when migrating
I am building a Location based webapp and I am stuck on a Problem. What i am trying to do I am trying to load json file and saving into database. The Problem When i run python manage.py migrate in console then it keep showing me json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) migrations.py DATA_FILENAME = 'data.json' def load_data(apps,schema_editor): Shop = apps.get_model('mains','Shop') jsonfile = Path(__file__).parents[2] / DATA_FILENAME with open(jsonfile,'r',encoding='utf-8') as datafile: objects = json.load(datafile) for obj in objects['elements']: try: objType = obj['type'] if objType == 'node': tags = obj['tags'] name = tags.get('name','no-name') longitude = obj.get('lon',0) latitude = obj.get('lat',0) location = fromstr(f'POINT({longitude} {latitude})', srid=4326) Shop(name=name,location = location).save() except KeyError: pass class Migration(migrations.Migration): dependencies = [ ('mains', '0003_shop'), ] operations = [ migrations.RunPython(load_data) ] What have i tried I tried bz2 function to unzip json data but it was unhelpful for me. I tried replacing file name into full path but nothing worked for me. I don't know what to do. Any help would be appreciated. Thank You in Advance. -
Django - Referential integrity on OneToOneField
I am trying to import a product feed (Product) into Django. I need to maintain a set of selected products (SelectedProduct) which also hold overrides for the product descriptions. I thought the best way to represent this is as a OneToOneField linking SelectedProduct with Product. class Product(models.Model): sku = models.CharField(max_length=32, primary_key=True) title = models.CharField(max_length=200) description = models.TextField(max_length=2000, blank=True, null=True) class SelectedProduct(models.Model): product = models.OneToOneField(Product, db_column='product_sku', on_delete=models.DO_NOTHING) description = models.TextField(max_length=2000, blank=True, null=True) For simplicity, each time the product feed is read, I am intending to delete all the products and re-import the whole product feed (within a transaction, so I can rollback if required). However, I don't want to truncate the SelectedProduct at the same time, since this contains the descriptions which have been overridden. I was hoping that models.DO_NOTHING might help, but it doesn't. I suppose I either need to temporarily disable the referential integrity while I import the feed (and delete any entries from SelectedProduct which would break the integrity) or I need to represent the relationship differently. Any advice appreciated please :-) Note - the above is a simplified representation. I have variants hanging off products too and will have selected variants overriding variant prices. -
trying to install exchangelib package in dockerized django i receive following error
Building wheel for cryptography (PEP 517): started Building wheel for cryptography (PEP 517): finished with status 'error' ERROR: Command errored out with exit status 1: command: /usr/local/bin/python /usr/local/lib/python3.8/site-packages/pip/_vendor/pep517/_in_process.py build_wheel /tmp/tmp_g7gpo_c cwd: /tmp/pip-install-2y_1vrjf/cryptography_c327dead1e3c4d5ead1c1745ab7281d2 Complete output (151 lines): running bdist_wheel running build running build_py -
Page not found (404) jquery django python
jquery does not load - Page not found (404) base.html {% load static %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="{% static 'bootstrap-5.0.0/css/bootstrap.css' %}" rel="stylesheet"> <link href="{% static 'css/style.css' %}" rel="stylesheet"> <!-- jQuery --> <script src="{% static 'jquery/jquery.js' %}"></script> </head> setting.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [os.path.join(BASE_DIR, 'ServiceCRM3/static'),] static folder created the script is in the path static / jquery / jquery.js bootstrap picks up ok in the same folder the server restarted what's wrong? -
Delete an user object automatically after some time in django models
I want automatically delete the user object or make default="" in my model after 2 min. Here is my model. What am I doing wrong!! from django.db import models from django.contrib.auth.models import User from datetime import datetime, timedelta from django.utils import timezone from datetime import date class Action(models.TextChoices): REQUESTED = 'Requested' ACCEPTED = 'Accepted' REJECTED = 'Rejected' class UserMembership(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=255, default='') student_id = models.CharField(max_length=10, default='') membership_type = models.CharField(max_length=50) membership_action = models.CharField(max_length=50, choices=Action.choices, default=Action.REQUESTED) start_date = models.DateTimeField(default=timezone.now,blank=True,) @property def delete_after_thirty_days(self): time = self.start_date + datetime.timedelta(minutes=2) if time < datetime.datetime.now(): e = UserMembership.objects.get(user=self.user) e.delete() return True else: return False def __str__(self): return self.name Basically, after 2 minutes the values of the UserMembership model related to the specific user should be deleted or change back to default values. currently, nothing happens and I don't get any errors as well. Thank you for your time.