Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django / Python: Generate random timezone respecting datetime within the next 24h
I need to generate a random datetime within the next 24 hours (so any hour, minute, and second but within 24h of when the method is run). This will go in a django model.DateTimeField(). I know that I can get the current timezone-aware datetime with from datetime import timezone timezone.now() but it's not quite clear to me how to pick a random time 24h into the future from timezone.now(). -
Where to specify "use_natural_primary_keys" with generic class views?
I've been reading about natural_keys and have added the get_by_natural_key() and natural_key() methods to my model(s), but the Django docs (and several posts here in SO) say: "Then, when you call serializers.serialize(), you provide use_natural_foreign_keys=True or use_natural_primary_keys=True arguments" ...followed by this example: >>> serializers.serialize('json', [book1, book2], indent=2, ... use_natural_foreign_keys=True, use_natural_primary_keys=True) But that example is from running in a python shell, not in the actual context of where to put it in code. From DRF, I'm using generic class based views. Where should I specify those arguments in that case? -
Gitlab CI setup: reset database
I setup Gitlab Cloud CI and everything worked fine, but I have reset the database on my local machine and so cleaned up all migration files(Django). Now on python manage.py migrate step I get the issue about incorrect migration dependencies. On my local machine, everything works fine and so I just need to reset the database on Gitlab Cloud. Does anybody know how to do it? Here is my config file(.gitlab-ci.yml): image: python:3.6 services: - name: postgres:latest stages: - test variables: POSTGRES_DB: python-test-app cache: paths: - ~/.cache/pip/k test job: stage: test script: # use attached postgres database that is run on `postgres` host - export DATABASE_URL=postgres://postgres@postgres:5432/$POSTGRES_DB - apt-get update -qy - make clean - make requirements-dev - make migrate - make lint - make test only: - merge_requests - master - tags -
Can I use this pattern on the visual studio for Angular?
I am trying to do the previous and next record just like way back Visual Studio's Automated TableDataAdapter with Recordset embedded. I got the picture somewhere in the internet. But what I'm trying to do is the [|< < 1 of 3 > >| Delete Save] and then I manipulate the fields on record next fill the next record on the fields. Can I achieve this using any PlainPHP with pagination or what? can I also achieve this using Angular or React? -
When I added default in foreign-key, "django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet." occurred
I am developing Django&Wagtail blog app. Unfortunatly, "django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet." is occurred. If there is no default, app works propely. However, if I added default, it does not work... I researched some article but they could not help me. class hoge(models.Model): """ ... """ page = models.ForeignKey( "blog.BlogIndexPage", on_delete=models.CASCADE, verbose_name=_("blog"), default=BlogIndexPage.objects.latest("id"), # add here ) Environment: Mac(Mojave 10.14.6) Virtualenv python 3.7 Django 2.2.4 wagtail 2.6.1 Error: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. -
what is meaning of this error below and how to connect Django to SQL Server
I have a django project that must use Sql Server database in order to stored and retrieve data. I changed the engine in the settings.py and perform the migration. the database was successfully migrate into the sql server. The problem is when I tried to create a model in django and try to insert data to the model it seams that as there is no connection between the model and the sql server. I tried to open django shell and try to connect to sql server using this command : import pyodbc connection = pyodbc.connect('Driver={ODBC Driver 17 for SQL Server};' 'Server=localhost;' 'Database=testDB;') it display the below error : Traceback (most recent call last): File "", line 1, in pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]Named Pipes Provider: Could not open a connection to SQL Server [2]. (2) (SQLDriverConnect); [08001] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0); [08001] [Microsoft][ODBC Driver 17 for SQL Server]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books … -
map(lambda,list) return None instead object
I want add attribute to all object (that are model instance in django) in a list. for example the list is: persons = [ {"age":"12","name":"John"}, {"age":"10","name":"Joye"} ] and we assume that i want put value of person.age in person.numberand i have a new list that all of person have new attribute number so my function is : new_persons_list=list(map(lambda person:setattr(person, 'number', person.age), persons)) but the output is [None,None] while i expect that output be: persons = [ {"age":12,"name":"John","number":12}, {"age":10,"name":"Joye","number":10} ] if possible i don't like to add new function in map and i want use lambda.what is the problem?thank you -
how to set value for column from another column when insert from django admin form
I have book stock form and it has two columns to indicate the the stock value: current stock, and the stock, current stock and stock should be the same when inserting the first time, but, when borrow a book the current stock should be decreased, and the stock column will be at the first value: for instance: book1 has stock 5 and current stock 5, someone borrowed the book1, so book1 stock 5 and current stock 4, I don't want to do it from database triggers because my application is database independent. please help me how can I do it from django admin form? models.py: class BooksCopy(models.Model): book = models.ForeignKey(Book, on_delete=models.PROTECT) branch = models.ForeignKey(Branch, on_delete=models.PROTECT) no_of_copies = models.IntegerField('Stock') current_no_of_copies = models.IntegerField('Current Stock') admin.py: class BooksCopiesAdmin(admin.ModelAdmin): models.BooksCopy.current_no_of_copies = models.BooksCopy.no_of_copies exclude = ('current_no_of_copies',) list_display = ('branch', 'book', 'no_of_copies', 'current_no_of_copies',) -
How to make a celery task work in Django?
I am working on a project that requires to create a model entry every time the date has exceeded the booking date. I am using celery for it. Everything seems to run fine but my task does not work. I don't know what is wrong with it. I am attaching codes of my celery task and model. Please help. task.py @task(name="create_payment") def create_payment(): try: booked_client = Booking.objects.get(client__user__username=request.user) len = Payment.objects.filter(username__user_username=request.user) due = Payment.objects.filter(user__user_username=request.user).values_list('due_date')[len - 1] print(due) if datetime.date.now - due >= 0: form = PaymentsForm() form.username = request.user form.save() except: pass celery.py os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'qworky.settings') app = Celery('qworky') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) app.conf.beat_schedule = { 'add-every-5-seconds': { 'task': 'create_payment', 'schedule': 10.0, 'args': (), }, } @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) models class Payment(models.Model): username = models.ForeignKey(UserProfile,on_delete = models.CASCADE, related_name='name') amount = models.IntegerField() date = models.DateField(blank=False, default = date.today) due_date = models.DateField() collected_by = models.ForeignKey(UserProfile,on_delete = None, related_name='collected_by', blank=True, null = True) is_due = models.BooleanField(default = True) def save(self, *args, **kwargs): self.due_date = self.date + monthdelta(1) amt = list(map(int,Booking.objects.filter(client__user__username=self.username).values_list('cabin__price', flat='True'))) self.amount = sum(amt) super(Payment, self).save(*args, **kwargs) celery worker in terminal INFO/ForkPoolWorker-3] Task create_payment[532389a2-31a1-43e8-8155-87c0a6cbc8e3] succeeded in 0.003159977000905201s: None celery beat in terminal Scheduler: Sending due task add-every-5-seconds (create_payment) -
How to mock celery send_task function in django Unit test
I want to write a unit test in Django, for a function which has celery send_task function. So how to write its UT in Django and how to mock celery. def push_to_queue(self, data): """ function to add task in the backend queue Args: Accept data dictionary returns: Nothing """ try: LOG.info( "Pushing %s to queue %s " % (data, settings.SCHEDULER_STATUS_QUEUE_NAME) ) # sqs handler handle = Celery("scheduler_service", broker="sqs://") handle.send_task( settings.BACKEND_TASK, queue=settings.SCHEDULER_STATUS_QUEUE_NAME, kwargs=data, ) LOG.info( "Pushed message successfully to %s queue." % settings.SCHEDULER_STATUS_QUEUE_NAME ) except Exception as err: LOG.error("Exception while pusing meesage to queue %s " % str(err)) -
Django admin css not being applied after loading
I am using nginx to serve my django static files. In the browser I can see that they are loaded, base.css, login.css, responsive.css all got status 200, I can click on them and see their content. The problem is that they don't seem to be applied in the html. The html still looks like it has no css formatting applied to it at all. There are no errors in the nginx logs and no errors in the network tab in chrome. I have tried chrome and firefox Using Django 2.2.4 -
How to save all user clicks and inputs in Django?
This is may be an obvious question to a Django expert, but is there a way that I can save all user input (clicks and text-based). If this is possible, then how do I access it later? Or must I create models for each entry and then save each click by hand in the view with something like to save user behavior, obviously it would be way bigger than this, in the application: #(within a view function) UserInputs.objects.get_or_create(user=request.user, selection1=request.POST.get('selection1'), id=request.POST.get('id')), thumbs_up=request.POST.get('thumbs_up'), thumbs_down=request.POST.get('thumbs_down'), comments=request.POST.get('comments') ) -
How can I set my very own JSON key label in Django REST API framework?
I'm trying to use REST API framework in Django and I noticed that the JSON format for it always takes the particular model's field name as the key. eg: A field called image in my model stores images in the database. When viewed in JSON format, it's seen as : {"image": "apple.png"} I want to change the image to my own personalized label. How can I do this? -
Invalid HTTP_HOST header even after adding it to the allowed host
I have a python/django website running on amazon lightsail instance. I have included my domain name in the allowed_hosts. But sometimes I am getting the error that i need to include my static IP to the allowed_hosts. This error is showing to only some users but I dont know where is the real problem. I don't want to include my static IP to the allowed_host as it is not a best practice. Does anyone know the problem here? -
Data output from Froala Editor is not in the format i wanted - Django
I integrated Froala editor in my django forms to save data into the database. I have noticed that Froala editor save the data with html tags.I have a table on my django web apps which retrieve data from the database and display. The data from the database is displayed with html tags. Is there a way to fix this? User can't be looking at the html tags with the data. Any help would be appreciated. -
How to fix: when I'm trying to follow the link with a name of another anchor the page crashes
I'm setting up a website based on Django. I want to link several pages using the positional link (..../#anchor_name), but when I follow the link the page crashes and I really confused. I have done some googling, but there was nothing that helped This is the anchor with a link that I followed. Normal links (without ../#anchor_name) work just fine. <a href="{% url 'home_page' %}#get_in_touch">CONTACT</a> This is the endpoint anchor. I've also tried to set an id, but unfortunately, it leads to the same consequences. <a name="get_in_touch"> <section class="section"> </section> </a> Eventually, it happens: https://i.ibb.co/ZLjMr07/Screenshot-6-LI.jpg I have also tried different browsers. Thanks in advance -
How to know which user added another user?
How do I know which user added another user? User A registers and is assigned admin status. User A adds User B within the application. How can I save User A in my extended user model so I know who has added who? This is a multi-tenant application. Django/Postgres -
How to return list of dicts in `SomeTable.objects.raw()` in Django?
I have code below: SomeTable.objects.raw(custom_query) And I need to get results as list of dicts. Something similar to when SomeTable.objects.filter(some_filter).values_list() which returns a ValuesQuerySet SomeTable.objects.raw returns a RawQuerySet and don't seem to have easy way to extract/convert it to list. Although using cursor is also doable: cursor.execute(custom_query) return [ dict(zip([col[0] for col in cursor.description], row)) for row in cursor.fetchall() ] -
Django's create method for models is not accepting my dictionary
I have been trying to simplify my testing file test_client_api.py for my django model Client in models.py. However, I am running into an error when I try to make a sample_client method that simplifies the creation of this Model for testing purposes. Here is my Repo's full code: https://github.com/StrawHatAaron/duplicagent-api when I change the code in app/clients/tests/test_client_api.py on line 50 to client1 = sample_client(user=self.user, fein="helloword") from client2 = Client.objects.create( user=self.user, fein = 'Yolo dude', business_name = 'Dont know why it wont work', first_name = "Test", last_name = "Name", emails = "test@sacappdev.com", phone = 69696969, address = 'none your damn biz', city = 'nonya', state = 'fu', zip_code = 12345, ) I get an unexpected error: ERROR: test_retrieve_clients (clients.tests.test_client_api.PrivateClientApiTests) Test retrieving a list of recipes ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.DataError: integer out of range The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/clients/tests/test_client_api.py", line 50, in test_retrieve_clients client1 = sample_client(user=self.user, fein="helloword") File "/app/clients/tests/test_client_api.py", line 35, in sample_client return Client.objects.create(user=user, **defaults) File "/usr/local/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 413, in create obj.save(force_insert=True, using=self.db) File "/usr/local/lib/python3.7/site-packages/django/db/models/base.py", line 718, … -
Accesing to a print remotely from WEB API
I used Django to develop a WEB API which allows me to register food orders and I want them to be sent directly to my EPSON TM-m30 command printer. This command printer would be connected via ETHERNET to my modem. For printing I use python-escpos module, which works fine when I run my app locally as following: p = printer.Network("192.168...") p.text('Hello world') p.cut I'm hosting my app in Digital ocean with Ubuntu 18.04 VM. As expected, my printer is not discoverable when I run my code from the digital ocean server... so what I supposed to do in order to allow that? Any suggestions would be appreciated. -
How to limit django allowed_hosts to one docker container
In my production environment, I have two docker container one for the web and one for nginx. Is it possible to specify the allowed_hosts in django to only the nginx container? Thank you. I've tried the service name and container name, none worked. -
Unable to get send_mail to send an email message Django
I posted a question earlier where I asked how to get my email to send and was told that it's the provider, so I tried 3 providers and the send_mail and/or EmailMessage function doesn't work with any of them. So, I strongly think it's something related to my set-up. I get a message in the send_email folder, but no email ever sends and no error is logged. Here is my settings.py file: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'myemails@gmail.com' EMAIL_HOST_PASSWORD = 'pass' EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = EMAIL_HOST_USER SERVER_EMAIL = 'myemail@gmail.com' Might someone else have an idea? -
Change value for paginate_by on the fly
I would like to be able to allow users change the default page size (paginate_by). My current page size is set to 10; I'd like to have buttons for say 25, 50, and all. I am running Django 2.2 and Python 3.73 with postgresql 11.4. My views.py creates a queryset and sets up pagination. My prod_list.html template properly displays the data in pages with ten rows per page. Here is what I currently have in my views.py: class ProdViewSet(viewsets.ModelViewSet): queryset = Proddetails.objects.all() serializer_class = ProdSerializer class ProdListView(ListView): model = Proddetails template_name = 'prod_list.html' # added for pagination context_object_name = 'prods' #Default: object_list paginate_by = 10 I want to be able to let my users change the number of rows per page. I'm thinking I need to reset paginate_by based on which button the user clicks, but how can I do that? Thanks-- Al -
Django DetailView and get request
I have a detail view with a drop-down list. The user can choose an item in the drop-down list and the information about that item should appear below it. This requires that the DetailView includes something like this: def get_context_data(self, **kwargs): context = super(InvoiceDetail, self).dispatch(*args, **kwargs) request = self.request if request.GET: try: invoice_selector = request.GET.get('invoice_selector', None) invoice = Invoice.objects.get(id = int(invoice_selector) ) # either a string representing a number or 'add invoice' context_object_model = invoice except ValueError: return HttpResponseRedirect(reverse('accounting:add_invoice')) return context How do I over-write the context_object_model? The above code does not make the change. -
How to include quaggajs script tag in django
I have installed quagga using npm and moved quagga.min.js and quagga.js into the static directory of my app(recordmgnts), so i have recordmgnts/static/recordmgnts/quagga.min.js. I tried using src="{% static 'recordmgnts/quagga.min.js' %}" in my script tag but it is not working. How can i include it in my template? Thank you in advance.