Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Make a function call using Django-cron
I want to call a method once in a week for which I made an implementation as mentioned here https://gutsytechster.wordpress.com/2019/06/24/how-to-setup-a-cron-job-in-django/ I am not sure how it works, but let me explain what I did. I need to call a method as mentioned in folder structure below. proj_application | |- myapp | |-views.py (Method call Inside) |- poll_tracked() In settings.py, I have mentioned INSTALLED_APPS = [ 'django_crontab', ] CRONJOBS = [ ('* * * * *', 'myapp.views.poll_tracked', '>>' + os.path.join(BASE_DIR, 'data.log')) ] After then I run python3.7 manage.py crontab add python3.7 manage.py runserver When I run crontab -l, I can see, * * * * * /Library/Frameworks/Python.framework/Versions/3.7/bin/python3.7 /Users/domain/dashboard/proj_application/manage.py crontab run dceca84af9ceab8a4d39d08fa148969f >>/Users/domain/dashboard/proj_application/data.log # django-cronjobs for proj_application A new log file called data.log is generated but the method poll_tracked() mentioned is not called and the logs is empty. Any assistance is appreciated. Thanks. -
How do I compare two text files in Django?
I'm building an online judge system in Django like the one we used to have in Kickstart earlier. They gave you a text file, input.txt and then you got an output after you ran that in the form of an output.txt file. I'm aware of how this is done in Python but I'm not sure how to implement it in a Django application. My partial understanding : The user submits the output.txt file to the form and then we need to implement the Python function in the view using the form_class ( since I'm using CBVs ). But the point is that I'm not able to figure out how would the FormView ( or UpdateView ) CBV applies that function to the uploaded file. Tl;dr: How do I implement a Python function in Django that compares two text files and return if they are the same? P.S I'm not including a compiler to the online judge since I'm in the early stages of this app and it might be an overhead expense. -
I tried to upload a Django project in Heroku and end up with +4000 pending changes in source control
the other day I was doing a guided project and the final step was to upload the project in Heroku and everything went fine but now I want to do the same, followed the same steps but it's not working Somehow following the commands I ended up with this, how can I go back or start again from scratch? Even following Heroku website guide is so confusing Can someone tell me the easiest steps to upload the project in Heroku? I'm using Python but it's so confusing Also does the project has to be upload in Github properly in order to upload in Heroku? -
Digital Signature Web Application with Cryptographic Devices in Django (Python)
I am developing a web application and it needs a pdf document to be digitally signed using a cryptographic device. The characteristics of the device are specified in the following link: https://csrc.nist.gov/Projects/cryptographic-module-validation-program/Certificate/2825 The programming language used is Python (Django). I have searched for information in some forums and scientific articles. And most agree that the most elegant solution is to use the browser extension. I understand that the signing process has to be developed on the client side, more precisely using Javascript. I would like to know if there is any open source solution that can guide me. models.py class Documento(models.Model): area = models.ForeignKey(Area, on_delete=models.CASCADE, null=True, related_name="documentos") tipo_documento = models.ForeignKey(TipoDocumento, on_delete=models.CASCADE, null=True, related_name="tipo_documentos") naturaleza = models.ForeignKey(Naturaleza, on_delete=models.CASCADE, null=True, related_name="naturaleza_documentos") autor = models.ForeignKey(Funcionario, on_delete=models.CASCADE, related_name="autor_documentos") archivo_pdf = models.FileField('Subir Archivo PDF', upload_to='documentos/', validators=[validate_file, FileExtensionValidator(['pdf'])]) nombre_documento = models.CharField('Nombre del Documento', max_length=200) numero_documento = models.CharField('Numeración del Documento', max_length=200, null=True, blank=True) fecha = models.DateTimeField('Fecha de Subida', default=timezone.now) firmado = models.BooleanField(default=False) estado = models.BooleanField(default=True) def __str__(self): return self.nombre_documento def save(self): self.nombre_documento = self.nombre_documento.upper() self.numero_documento = self.numero_documento.upper() if not self.fecha: self.fecha = datetime.datetime.now() super(Documento, self).save() def delete(self, *args, **kwargs): self.archivo_pdf.delete() super().delete(*args, **kwargs) class Firma(models.Model): documento = models.ForeignKey(Documento, on_delete=models.CASCADE, related_name="documentos_firmas") funcionario = models.ForeignKey(Funcionario, on_delete=models.SET_NULL, null=True, blank=True, related_name="funcionarios_firmas") fecha_firma … -
Api root on django rest framework
I am newbie on DRF so I wonder if there a "elegant" way to add more endpoints to API Root. I have an endpoint to manage my users and another to manage their posts, but on http://localhost:8000/api/ only profiles appears. I search for some solutions that implies change the URL but I don't want that. For example my current endpoint to get all posts is localhost:8000/api/posts that looks fine. I don't want something like api/posts/posts or similar. Is there any alternative? { "profiles": "http://localhost:8000/api/profiles/" } main urls.py urlpatterns = [ path('docs/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path('admin/', admin.site.urls), path('api/', include('profiles.urls')), path('api/', include('posts.urls')), path('api/', include('comments.urls')), path('api/', include('private_messages.urls')), ] userprofile urls.py from django.urls import path, include from rest_framework.routers import DefaultRouter from rest_framework_simplejwt import views as jwt_views from .views import UserProfileViewSet router = DefaultRouter() router.register('profiles', UserProfileViewSet) urlpatterns = [ path('', include(router.urls)), path('auth/login', jwt_views.TokenObtainPairView.as_view()), path('auth/refresh', jwt_views.TokenRefreshView.as_view()), ] posts urls.py from django.urls import path, include from rest_framework.routers import DefaultRouter from .views import PostViewSet, PostByAuthorViewSet router = DefaultRouter() router.register('posts', PostViewSet) urlpatterns = [ path('posts-by-author/<author_id>', PostByAuthorViewSet.as_view()), path('', include(router.urls)) ] -
How can I join two child tables using Django Querset API?
I have a model with two child tables and one parent table. Here is the sample model classes. # Stores list of unique category names class Category(models.Model): category = models.CharField(max_length=20, unique=True, validators=[MinLengthValidator(limit_value=5)]) name = models.CharField(max_length=20, validators=[MinLengthValidator(limit_value=8)]) # Parent class for the next two child classes class DailyLog(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=100, validators=[MinLengthValidator(limit_value=8)]) code = models.CharField(max_length=4, validators=[MinLengthValidator(limit_value=3)]) suggested_values = models.CharField(max_length=100, null=True, blank=True) # First child class defines display order for dailylog items class DailyLogDisplayOrder(models.Model): category_item = models.ForeignKey(DailyLog, on_delete=models.CASCADE) display_order = models.PositiveIntegerField() # Second Child class publishes dailylog on a daily bases class DailyLogCheckList(models.Model): daily_task = models.ForeignKey(DailyLog, on_delete=models.CASCADE) publish_date = models.DateField(auto_now=True) daily_task = DailyTaskCategoryManager() # Log manager to get records per category How do I perform a cartesian product query? The last column comes from the first child table Dailylogdisplayorder. Here is the raw sql. select daily_task_id, checklist.publish_date, disporder.display_order from dailylogchecklist checklist, compliance_dailylogdisplayorder disporder where checklist.daily_task_id = disporder.category_item_id and checklist.publish_date='2020-07-12' I have tried using cursor.execute() method per Django documentation. However, I am not able to figure out how to return results in QuyerySet. And also looking for a better way to combine child columns using QuerySet. The return queryset is assigned to a formset. class DailyTaskCategoryManager(models.Manager): def with_displayorder(self, user): … -
need correct template syntax. Django, Jinja
{% if url == 'home' %} <h2>{{obj.name}}</h2> <span class="subheading">% {{obj.subhead}} %</span> {% else %} <h2>{{obj.en_name}}</h2> <span class="subheading">% {{obj.en_subhead}} %</span> {% endif %} just need to write without syntax error.. logic is easy: if url from (views.py name=home) is 'home' show me obj.name, else url is 'en_home' show me obj.en_name -
How to Post a List in Django Tests
How can I post a list in a django test? I retrieve the data through this command: listVar = request.POST.getlist('list[]') I know this receives a list properly because I interface with Jquery and it returns the proper list, but how can I do this is python? I have been trying code like this however printing 'listVar' always yields an empty list: form = {"list": ["element 1", "element 2"]} response = self.client.post('/viewurl/', form, follow=True) -
What might be the causes if the change to template was not reflected in the browser?
I made some changes to my Django template but it could not reflected in the browser(chrome). However, if I open another browser(safari), the change were shown. What might be the cause of this phenomenon? I am using the Django development server. -
Jinja2 with WeasyPrint is too Slow
I am creating a "Resume Builder" website using React and Django. React sends the resume data as json to django, where the pdf is generated. I am using WeasyPrint to generate pdfs and Jinja2 to insert data into the template. Jinja code includes few logical statements (I tried my best to use the least) and it contains little heavy CSS too. The time to generate a single page template is around 14-20 seconds and 20-30 seconds for a two page template. I tried to remove the CSS and kept only the HTML and data, the pdf was generated in a second or two then I removed the data and kept only the HTML and CSS and the pdf was generated in 5-10 seconds. Is there any solution to generate pdf in less than 5 seconds with HTML, CSS and data? Are they any Jinja2 configurations or tricks to improve the performance? An sample of Jinja2 used to map data on template: <div class="resumeThree-section-2"> <div class="resumeThree-left-section"> <div> <p class="resumeThree-left-section-title">PERSONAL PROFILE</p> <div class="resumeThree-descriptionBox"> {{ data.profile }} </div> </div> <div class="resumeThree-section"> <p class="resumeThree-left-section-title">CONTACT DETAILS</p> <div class="resumeThree-inputs"> <span>{{ data.email }}</span> <span>{{ data.phone }}</span> <span>{{ data.url }}</span> <span>{{ data.address}}</span> </div> </div> <div class="resumeThree-section"> <p class="resumeThree-left-section-title">SKILLS … -
how to update database table values using update function in django
I have an entry already in my database table and i want to update it with the values 12 and 6. But for some reason the update function doesn't seem to be doing anything. I dont want to create a new instance, i just want to write over the value that are already in there. PF is the name of my DB table. I understand that the objects links both to the pass_number and fail_number attributes of the table model, so i presume that both would be updated with the values. However when I go into the table i still see the old values. event1 = PF( pass_number = 12, fail_number = 6, ) event1.objects.update(event1) -
The Ticket could not be created because the data didn't validate
My model Class: class Ticket(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ticket_number = models.IntegerField('Ticket Number', null=True) date = models.DateTimeField('Date', default=datetime.now()) name = models.CharField('Customer Name', max_length=50) company = models.CharField('Company / Community', max_length=50, null=True) address = models.CharField('Address', max_length=50, null=True) total_card = models.DecimalField('Total Card Payment', max_digits=6, decimal_places=2, null=True) total_cash = models.DecimalField('Total Cash Payment', max_digits=6, decimal_places=2, null=True) tip_card = models.DecimalField('Tip in card', max_digits=6, decimal_places=2, null=True) tip_cash = models.DecimalField('Tip in cash', max_digits=6, decimal_places=2, null=True) gas_fee = models.DecimalField('Gas Fee', max_digits=6, decimal_places=2, null=True) prc_fee = models.DecimalField('Percent fee', max_digits=6, decimal_places=2, null=True) The form works when coded like that: <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit"> But i cant validate when using the forms like these: <form method="post"> {% csrf_token %} {{ form.ticket_number.errors }} {{ form.ticket_number.label_tag }} {{ form.ticket_number }} <br> {{ form.name.errors }} {{ form.name.label_tag }} {{ form.name }} <br> {{ form.company.errors }} {{ form.company.label_tag }} {{ form.company }} <br> {{ form.address.errors }} {{ form.address.label_tag }} {{ form.address }} <br> {{ form.total_card.errors }} {{ form.total_card.label_tag }} {{ form.total_card }} <br> {{ form.total_cash.errors }} {{ form.total_cash.label_tag }} {{ form.total_cash }} <br> {{ form.tip_card.errors }} {{ form.tip_card.label_tag }} {{ form.tip_card }} <br> {{ form.tip_cash.errors }} {{ form.tip_cash.label_tag }} {{ form.tip_cash }} <br> {{ form.gas_fee.errors }} {{ form.gas_fee.label_tag }} … -
Django models diamond inheritance problem
I'm trying to figure out how I could cope with diamond inheritance in Django models. class Address(models.Model): street = models.CharField() city = models.CharField() country = models.CharField() class Meta: abstract = True class Person(Address, models.Model): name = models.CharField() class Caffe(Address, models.Model): place_name = models.CharField() owner_name = models.CharField() signature_drink = models.CharField() I know I could just inherit after Address and it'll still work. But it doesn't look correct - it makes code and inheritance unclear (assuming each model is in different file). Or maybe it is the only way and it is acceptable by Django standards? -
how to filter a ManyToManyField in m2m_changed to update
i want to to update field whenever an instance been created i tried signals but it seems complicate to ManyToManyField def update_m2m(sender,instance,*args,**kwargs): Imei.objects.filter(pk=instance.id).update(active=False) m2m_changed.connect(update_m2m,sender=SelectMobile.imei.through) but doesnt update anything !? these are my models.py class MobileCustomer(models.Model): customer = models.CharField(max_length=30) phone = models.CharField(max_length=13) mobile = models.ManyToManyField(MobileStorage,through='SelectMobile') class SelectMobile(models.Model): mobile = models.ForeignKey(MobileStorage,on_delete=models.CASCADE) item = models.ForeignKey(MobileCustomer,on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) imei = models.ManyToManyField(Imei) class MobileStorage(models.Model): mobile = models.ForeignKey(Mobile,on_delete=models.CASCADE) quantity = models.PositiveIntegerField() class Mobile(models.Model): mobile_name = models.CharField(max_length=40,unique=True) class Imei(models.Model): imei = models.CharField(max_length=15,verbose_name='IMEI',unique=True) mobile = models.ForeignKey(MobileStorage,on_delete=models.CASCADE) active = models.BooleanField(default=True) i want to update active field in Imei model when MobileCustomer created !? is there something i've missed ?thanks for helping -
Django Project 1 implementation issue
I am trying to complete a project and it is not working as intended. This is the following requirements: Search: Allow the user to type a query into the search box in the sidebar to search for an encyclopedia entry. If the query matches the name of an encyclopedia entry, the user should be redirected to that entry’s page. If the query does not match the name of an encyclopedia entry, the user should instead be taken to a search results page that displays a list of all encyclopedia entries that have the query as a substring. For example, if the search query were Py, then Python should appear in the search results. Clicking on any of the entry names on the search results page should take the user to that entry’s page. This is my code: urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:title>", views.wiki, name="wiki"), path("search", views.search, name="search"), ] util.py def save_entry(title, content): """ Saves an encyclopedia entry, given its title and Markdown content. If an existing entry with the same title already exists, it is replaced. """ filename = f"entries/{title}.md" if default_storage.exists(filename): default_storage.delete(filename) default_storage.save(filename, ContentFile(content)) def get_entry(title): """ Retrieves … -
Django channels or periodic ajax requests?
Need some pro tips. I use django rest framework + vue js for my web application project and developed an easy chat app. The messages refresh dynamically by sending ajax requests every 2 seconds on the client part. Should I keep this variant or it's better to use django channels instead? -
How can I post data to the django database and to a CSV file
I am trying to have an output (csv/txt) from a Django form input in addition to saving in the SQL tables my code is here def booking_view(request): global form if request.method == 'POST': form = BookingForm(request.POST, request.FILES) if form.is_valid(): form.save() **WRITE TO A CSV FILE** form = BookingForm() return render(request, 'booking/sandpit.html', {'form': form}) else: form = BookingForm() return render(request, 'booking/sandpit.html', {'form': form}) How can i take the form data and save as CSV/TXT Thanks in advance -
Django reverse error: invalid literal for int() with base 10: 'objectidXXXXXXX in string'
I'm new to MongoDB/Django I'm using djongo as shown below. I could save. But I'm get the error as title. settings.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'webpage', } } models.py class Test(models.Model): title = models.CharField(max_length=100) content = models.TextField() def get_absolute_url(self): return reverse('tests:test-detail', kwargs={'pk': self.pk}) views.py class TestDetailView(LoginRequiredMixin, DetailView): model = Test urls.py app_name = 'tests' urlpatterns = [ path('test/<pk>/', TestDetailView.as_view(), name='test-detail'), ] When the code runs get_absolute_url, it returns error as below: invalid literal for int() with base 10: 'objectidXXXXXXX in string' Thx in advance. -
Please how can I improve my code by using django's ORM instead of for loops
''' I recently learnt that it is wrong to use python to loop through records in my database, because it would make my web applications slow. I was wondering if it is possible to replace the code I attached with django's ORM to make this more efficient and race condition free.''' def get_book_title(): new = {} for post in Post.objects.all(): for book in Book.objects.all(): if post.book_title.strip().lower() == book.title.strip().lower(): if book.title in new: new[book.title]+= 1 else: new[book.title] = 1 book_titles = dict(sorted(new.items(), key=operator.itemgetter(1), reverse=True)) N = 6 limited_book_titles = dict(list(book_titles.items())[0:N]) return book_titles def prev_and_next(): posts = Post.objects.all() for i in range(len(posts)): if posts[i].previous_post is None: if i != 0: posts[i].previous_post = posts[i -1] posts[i].save() if posts[i].next_post is None: length = len(posts) - 1 if i != length: posts[i].next_post = posts[i + 1] posts[i].save() return posts -
Django RQ Scheduler not working periodically?
I am using django-rq where I specify the default queue together Redis host, port, db & password in the settings.py file. I also have a task.py in one of my app folder where I specify the Scheduler, see below: #tasks.py import django_rq from django_rq import get_scheduler scheduler = django_rq.get_scheduler('default') scheduler.schedule( scheduled_time = datetime.utcnow(), func = some_test_function, result_ttl=100, interval = 240) Finally, I have 2 separate Systemd services, one for RQ and the other RQScheduler. #RQWORKER.service [Service] Type=simple WorkingDirectory=/home/user/project ExecStart=/home/user/project/project_env/bin/python \ /home/user/project/manage.py \ rqworker #RQSCHEDULER.service [Service] Type=simple WorkingDirectory=/home/user/project ExecStart=/home/user/project/project_env/bin/python \ /home/user/project/manage.py \ rqscheduler Bottom line is, if I start the rqscheduler.service, it is fired once (showing me at least that it is working). Unfortunately, is not executed periodically again after 3 minutes. What I am doing wrong here? Thanks! -
Trying to map two corrosponding values with different keys in python django
in my django project, I am trying to map the following: In the views.py context = {'name': [a, b, c], 'price': [x, y, z], 'date': [1, 2, 3]} return render(request, 'index.html', context) In my index.html: {% for value in context %} <tr> <td>{{ value.name }}</td> <td>{{ value.price }}</td> <td>{{ value.date}}</td> </tr> {% endfor %} My target is to get a table in this way: name | price | date a | x | 1 b | y | 2 c | z | 3 I have tried different ways, but so far I have only been able to get one column. I am new to Python. Any help is much apapreicated. -
Django {% trans myvar %} not adding anything to po file
I've been trying to translate variables with the django trans tag but unfortunately nothing seems to appear in the po file. I tried to add the translation directly in the po file and compile it and worked for some texts. Is there another way to translate variables? -
Which Django module to use to compose images from multiple layers?
Let's say we have a room, 320 by 240 px room And I want the image to be supplemented with layers (optionally it is None) Well, for example, add a layer with a table there, like this: room with table and there are several such layers: room full The question is: What modules for Python / django can implement this with? -
Duplicate log output when using Django logging module
I am using the following logging snippet in my Django settings.py file. As seen in image below, all the logs are being captured twice. The reason I kept root object as I wanted to capture logger.info() in console as well as log file settings.py LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': '[%(asctime)s] %(levelname)s|%(name)s|%(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S', }, }, 'handlers': { 'applogfile': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(BASE_DIR, 'django_blend.log'), 'backupCount': 10, 'formatter': 'simple', }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple' } }, 'root': { # this tells to capture logger.info() to console as well as in log file 'handlers': ['console', 'applogfile'], 'level': 'INFO', }, 'loggers': { 'django': { 'handlers': ['applogfile', 'console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), } } } django.log -
Django annotate StrIndex for empty fields
I am trying to use Django StrIndex to find all rows with the value a substring of a given string. Eg: my table contains: +----------+------------------+ | user | domain | +----------+------------------+ | spam1 | spam.com | | badguy+ | | | | protonmail.com | | spammer | | | | spamdomain.co.uk | +----------+------------------+ but the query SpamWord.objects.annotate(idx=StrIndex(models.Value('xxxx'), 'user')).filter(models.Q(idx__gt=0) | models.Q(domain='spamdomain.co.uk')).first() matches <SpamWord: *@protonmail.com> The query it is SELECT `spamwords`.`id`, `spamwords`.`user`, `spamwords`.`domain`, INSTR('xxxx', `spamwords`.`user`) AS `idx` FROM `spamwords` WHERE (INSTR('xxxx', `spamwords`.`user`) > 0 OR `spamwords`.`domain` = 'spamdomain.co.uk') It should be <SpamWord: *@spamdomain.co.uk> this is happening because INSTR('xxxx', '') => 1 (and also INSTR('xxxxasd', 'xxxx') => 1, which it is correct) How can I write this query in order to get entry #5 (spamdomain.co.uk)?