Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how do I properly write django helper functions in order to check for new rows, and if the data was changed?
I am trying to write two functions in Django as helpers where it will help me to check if new data is coming or if the existing data was changed for further update is_new_row - will understand if the row is new and add it to an array that will be bulk created is_data_modified - will look for the row in the old data and understand if the data of that row is changed and will update only if its changed old_data = Person.objects.all() for row in api_data: if is_new_row(row, old_data): new_rows_array.append(row) else: if is_data_modified(row, old_data): ... # do the update else: continue helpers def is_new_row(row, old_data): ?? def is_data_modified(row, old_data): ?? -
Django-crontab can't make model query
I have a model inside tools app called ApiKeys and tried to update the model in specific time intervels. I used django-crontab for this purpose. CRONJOBS = [ ('*/1 * * * *', 'tools.cron.reset_api_calls','>>logs.log') ] function - from .models import ApiKeys def reset_api_calls(): try: keys = ApiKeys.objects.all() for key in keys: key.api_calls = 0 key.save() except Exception as e: print(e) model - class ApiKeys(models.Model): key_token = models.CharField(max_length=50, primary_key=True) api_calls = models.IntegerField(default=0) las_used_date = models.DateTimeField(default=timezone.now) But it gives error log - no such table: tools_apikeys Note: The table does exist in database and accessible through django-shell and views.py as well. -
How to create own model that can authenticate like admin user in django
I create own model user but can't authenticate it like in admin user # myapss/models.py from django.db import models from django.contrib.auth.hashers import make_password, check_password from django.db.models.manager import Manager class MyOwnManager(Manager): ... class MyOwnUser(models.Model): username = models.CharField(max_length=50, unique=True) password = models.CharField(max_length=255) ... objects = MyOwnManager() I want to authenticate this model without using AbstractUser or AbstractBaseUser #myapps/views.py from .models import MyOwnUser def login(request): # Authentication -
Kafka custom logging handler makes django app unlisten on port
I have a django app and I need to send my logs to the kafka server. So I implemented a custom handler as below: import logging from kafka import KafkaProducer class KafkaHandler(logging.Handler): def __init__(self, hosts=['DEFAULT_KAFKA_HOST:DEFAULT_KAFKA_PORT'], topic='DEFAULT_KAFKA_TOPIC'): logging.Handler.__init__(self) self.producer = KafkaProducer( bootstrap_servers=hosts, security_protocol='SASL_SSL', sasl_mechanism='SCRAM-SHA-512', sasl_plain_username='KAFKA_USER', sasl_plain_password='KAFKA_PASSWORD', value_serializer=lambda v: json.dumps(v).encode('utf-8'), linger_ms=10) self.topic = topic The problem here is that when I run the django app via python manage.py runserver in my local app runs without any trouble but my localhost doesn't listen on the specific port. output of netstat -tulpn: (Not all processes could be identified, non-owned process info will not be shown, you would have to be root to see it all.) Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 127.0.0.53:53 0.0.0.0:* LISTEN - tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN - tcp6 0 0 :::80 :::* LISTEN - tcp6 0 0 ::1:631 :::* LISTEN - udp 0 0 127.0.0.53:53 0.0.0.0:* - udp 0 0 0.0.0.0:631 0.0.0.0:* - udp 0 0 0.0.0.0:5353 0.0.0.0:* - udp 0 0 0.0.0.0:54922 0.0.0.0:* - udp6 0 0 :::58148 :::* - udp6 0 0 :::5353 :::* - But after I comment out the producer initialization everything works … -
Celery retry exception errors
I'm working on a project that requires me to reschedule tasks and I'm running into a problem. Would appreciate any feedback. I get a celery.exceptions.Reject error when attempting to retry a celery task. I've tested with a minimal tasks.py as listed below. Here is the code. tasks.py: from celery import Celery, Task from celery.utils.log import get_task_logger from django.conf import settings app = Celery('tasks', broker=settings.CELERY_BROKER_URL, backend=settings.CELERY_RESULT_BACKEND) logger = get_task_logger(__name__) @app.task(bind=True) def task_process_notification(self): try: if not random.choice([0, 1]): # mimic random error raise Exception() requests.post('https://httpbin.org/delay/5') except Exception as e: logger.error('exception raised - retry in 5 secs') raise self.retry(exc=e, countdown=5) Celery log traceback: [2021-06-19 04:21:19,342: INFO/MainProcess] celery@macbook-pro-16.lan ready. [2021-06-19 04:21:23,762: INFO/MainProcess] Received task: stocks.tasks.task_process_notification[ff372faa-febf-4d47-8628-2851a740cac3] [2021-06-19 04:21:23,765: ERROR/ForkPoolWorker-9] stocks.tasks.task_process_notification[ff372faa-febf-4d47-8628-2851a740cac3]: exception raised - retry in 5 secs [2021-06-19 04:21:23,775: ERROR/ForkPoolWorker-9] stocks.tasks.task_process_notification[None]: exception raised - retry in 5 secs [2021-06-19 04:21:23,777: WARNING/ForkPoolWorker-9] Task stocks.tasks.task_process_notification[ff372faa-febf-4d47-8628-2851a740cac3] reject requeue=False: Traceback (most recent call last): File "/Users/TLK3/PycharmProjects/stratbot/stocks/tasks.py", line 303, in task_process_notification raise Exception() Exception During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/TLK3/PycharmProjects/stratbot/venv/lib/python3.8/site-packages/celery/app/task.py", line 721, in retry S.apply_async() File "/Users/TLK3/PycharmProjects/stratbot/venv/lib/python3.8/site-packages/celery/canvas.py", line 235, in apply_async return _apply(args, kwargs, **options) File "/Users/TLK3/PycharmProjects/stratbot/venv/lib/python3.8/site-packages/celery/app/task.py", line 561, in apply_async return self.apply(args, kwargs, task_id=task_id or uuid(), File "/Users/TLK3/PycharmProjects/stratbot/venv/lib/python3.8/site-packages/celery/app/task.py", line … -
How to list integer field of distinct values in ascending order in Django
I am using django as backend and PostgresSql as backend. One problem I'm getting is sorting the distinct values in ascending order. I Have Distinct values in filter as: 16,14,4,64,8,6,12,10,18,2,32,24 now i want those values as 2,4,6,8,10....... I have code like this to get those distinct values filter_cores = Processor.objects.distinct().values('cores') HOW I CAN DO IN ASCENDING ORDER? -
how can i delete a permission from a group
I'm working on a small project using Django / Rest Framework, and now i would like to add soem permissions / Groups. I would like to know how can i add and delete a permission from a group i already did some research on Google and here i found only how to add but i'm steel looking for a way to delete a permission from a group, this is what i found : from django.contrib.auth.models import Group, Permission from django.contrib.contenttypes.models import ContentType from api.models import Project new_group, created = Group.objects.get_or_create(name='new_group') # Code to add permission to group ??? ct = ContentType.objects.get_for_model(Project) # Now what - Say I want to add 'Can add project' permission to new_group? permission = Permission.objects.create(codename='can_add_project', name='Can add project', content_type=ct) new_group.permissions.add(permission) Can someone explain to me how to delete a permission from a group ? Thank you -
Better ways to generate codes in django (python)
I am working on an authentication project where I am applying different features like email verification, password reset and these features rely on emails. Now i want to send a code to the user through an email and verify that on the backend. Now to generate the code(5-digit), this is what i did; import random code = random.randint(10000, 99999) print(code) I just want to know is this a better way to do so. Are there any drawbacks or just fine. -
bootstrap5 - how to next and prev button reduce the area?
I want to use bootstrap carousel. But the next and previous buttons are too long up and down to use the nevbar. how to next and prev button reduce the area? -
django.urls.exceptions.NoReverseMatch: Reverse for 'drafts' with keyword arguments '{'pk': 3}' not found. 1
Iam getting error "django.urls.exceptions.NoReverseMatch: Reverse for 'drafts' with keyword arguments '{'pk': 3}' not found. 1" I have created a button for delete view, and it is not working. whebever iam clicking on button the above error is coming. Kindly help here is the code : in views.py class DraftsView(ListView): model=models.NewPost context_object_name='newpost' class DraftsEditView(DetailView): context_object_name='draft_view' model=models.NewPost template_name='blogapp/newpost_details.html' # pk_url_kwarg="id" class DraftsUpdateView(UpdateView): fields=('Author','Title','Text') model=models.NewPost class DraftsDeleteView(DeleteView): model=models.NewPost context_object_name='newpost' success_url=reverse_lazy("blogapp:drafts") In urls.py urlpatterns=[url('about/',views.about,name='about'), url('register/',views.register,name='register'), url('user_login/',views.user_login,name='user_login'), url('newpost/',views.NewPostView,name='newpost'), url('drafts/',views.DraftsView.as_view(),name='drafts'), # path('drafts/<int:pk>/',views.DraftsEditView), path('<int:pk>',views.DraftsEditView.as_view(),name='view_draft'), path('update/<int:pk>/',views.DraftsUpdateView.as_view(),name='update'), path('delete/<int:pk>/',views.DraftsDeleteView.as_view(),name='delete') ] in newpost_details.html <a href="{% url 'blogapp:delete' pk=draft_view.pk %}"> <input class="btn btn-danger" type="text" name="" value="Delete"> </a> -
How to pass values to input field's value with spaces
<form action="handleAppointment/" method="post" > {% csrf_token %} <div class="inputfield"> <label for="doctor" class="label">Doctor</label> <input type="text" name="doctor" id="doctor" class="input" value={{ doctorName.name }} > </div> this is my form i want full value from database.but here {{doctorName.name}} is showing value which is before space. def bookAppointment(request , id ): doctor = Doctor.objects.filter(id = id ).first() print(doctor.name) context = {'doctorName': doctor} return render(request , 'patient/appointmentForm.html' , context) after running this code it shows ' Tapan Shah ' as output in terminal. which is full name but it shows ' Tapan ' before space value in frontend. -
Deploy django with apache2 error - ModuleNotFoundError: No module named 'encodings'
I tried to deploy my django app to my local vagrant but show the error below. '/var/www/venv/lib/python3.8/lib/python38.zip', '/var/www/venv/lib/python3.8/lib/python3.8', '/var/www/venv/lib/python3.8/lib/python3.8/lib-dynload', Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x00007f69c61ddc40 (most recent call first): <no Python frame> This code is log with apache2 tail /var/log/apache2/error.log <VirtualHost *:80> ServerName 192.168.2.26 DocumentRoot /var/www/django_app WSGIScriptAlias / /var/www/django_app/dj_rest_ql/wsgi.py # adjust the following line to match your Python path WSGIDaemonProcess 192.168.2.26 processes=2 threads=15 display-name=%{GROUP} python-home=/var/www/venv/lib/python3.8 WSGIProcessGroup 192.168.2.26 <directory /var/www/django_app> AllowOverride all Require all granted Options FollowSymlinks </directory> Alias /static/ /var/www/django_app/static/ <Directory /var/www/django_app/static> Require all granted </Directory> </VirtualHost> This is directory deployment /var/www/django_app /var/www/venv Is everyone used to meet this problem, please give me the solution, Thanks you in advance. Or if anyone have an good article for deploy djano with apache2 or nginx, please recommend me some. -
How to pass a token to views that require authentication in django rest framework
I have an app that stores users and their posts. To view the page of a user, I want it to require authentication for a given user. I'm not quite sure how to implement this because before without DRF, I'd just check if the current user was the same as the id requested in the url like page/users/10. DRF generates tokens for each user which I have specified when they register with this: class RegisterView(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": Token.objects.get(user=user).key }) Each token keys to a user like here: What I am wondering is how can I get each of these tokens to be used to authenticate the user. If the user logs in with his account, how will I be able to get the token and then pass it to the restricted views? -
How to render fields with many-to-many relationship on django templates
I am using generic views in Django-3.2 where I have a many-to-many relationship. I am trying to put the names of all the authors for a book as a string on a template. The model is like this: class Book(models.Model): book_name = models.CharField(max_length=200) author = models.ManyToManyField(Author) The Author class has a field called author_name which is also returned from the __str__ method. The generic view class that I am using is like this: class BookView(generic.DetailView): model = Book template_name = 'books/book.html' I tried using <span>{{ book.author }}</span> which produced books.Author.None. Later, I tried using <span>{{ book.author.author_name }}</span>, and this didn't retrieve any result. I didn't get an error in either of the cases. How do I put the data on the template for such many-to-many field? -
How to pass data acquired from vue.js to django template
The problem is that I can't utilize the data of vue instance within the tag of django template. So, Here is example code vue.js const vm=new Vue({ el:#app, delimiters:["${", "}"], data(){return{name:""}}, methods:{ /* getting data from django model with axios/DRF */ ..... axios.get("api/items/").then(response) => {this.name=response) this code work well and index.html .... <body> <p>Your item is ${name}</p> <p v-html=name></p> <p> Price is {{price}} </p> /*this come from context of django view */ </body> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script> "name" can be displayed on the django template What I want to do is "name" can function as value (or parameter) in tag of django template for example <body> {% with bookname=name %} {{bookname}} {% endwith %} ...... <a herf="{% url 'top:booklist' name %}" > </body> <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script> This does return error, not work. Of course, "${name}" is no success, instead "name" <a herf="{% url ' top:booklist ' ${name %}" > Please tell me how to pass "name" to django template tag I use Pyhton 3.7 Django 2.2 Vue CDN, not use Vue CLI thank you -
Adding a simple new account in the django admin doesn’t ask for the correct fields
I’m new to django and am sure this is probably a quick spot for most. I essentially want to: Change the default User model to use an email (and password) to log in (instead of username) Add extra fields to the default User model I’ve followed a video tutorial that resulted in me writing this code: Models.py: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError("Users must have an email address") if not password: raise ValueError("Users must have a password") user = self.model( email=self.normalize_email(email), # converts chars to lowercase password=password, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): # password=None? user = self.create_user( email=self.normalize_email(email), password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=100, unique=True) date_joined = models.DateTimeField( verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) first_name = models.CharField(max_length=100, null=True, blank=True) last_name = models.CharField(max_length=100, null=True, blank=True) # username field unwanted - only added to get rid of fielderror "Unknown field(s) (username) specified for Account. Check fields/fieldsets/exclude attributes of class AccountAdmin." username = models.CharField(max_length=30, unique=True, blank=True) # … -
Can pytest-django completely replace Django built-in test
I prefer to use pytest for writing all of my tests. I don't really like the unittest-style that the django.test offers, and I'm sure I'm not the only one... I made the switch to pytest years ago, and have never looked back! However, now I'm working my way through the Django tutorials, and have reached the testing section, and would like to use pytest instead of django.test. So far, it seems that pytest-django would be the perfect tool for the job! This blog post makes a good argument for using pytest-django, and it seems like I would be able to test my entire Django application using pytest-django. My question is: Can I completely forego using django.test and use pytest-django instead? Or, will there be some parts of my application that I would need to test using django.test? -
How to render form 'attribute'/field widget with template tag
Here is my html template code {% if subject == 'BAFS' %} {{ form.bafs_result.errors }} {{form.bafs_result.label}} {{ form.getSubjectResultAttrName:subject }} here is the python code in the template filter from django import template register = template.Library() @register.filter def getSubjectResultAttrName(form, subject): subjectAttrName = subject.lower() + "_result" subjectAttr = form.fields[subjectAttrName] return subjectAttr What I am trying to do is to render {{form.bafs_result}}, in which bafs_result is a Choicefield in the form. However, the above yields this: I have also tried replacing the subjectAttr assignment with: subjectAttr = form.fields[subjectAttrName].widget or subjectAttr = getattr(form, subjectAttrName) which gives the error: 'Form' object has no attribute 'bafs_result' -
Django doesn't serve all js files in development
I have two js files in my static folder, main.js and animation.js. When I run py manage.py runserver and go to localhost, I only see main.js. I've tried hard refreshing Chrome and Firefox, running collectstatic, and it's still the same. One time when I first loaded the page I saw both js files, but after clicking around the site, the animation.js file just disappeared. My terminal output shows that both js files were found. I'm confused why only one shows up in the browser. If both were missing that would indicate something wrong in settings, but I don't know with just one missing. What could be my problem? Here's my settings.py: DEBUG = TRUE STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] -
Problem sending a signal when adding a django child model
I'm facing the problem that I can't track the creation of an object in a child model. I am using inline in my model. And I want all objects of child model AuthUrl to be output when saving ServerAuth model. This code works correctly and outputs any changes but when I add a new AuthUrl object I get the error that supposedly the id doesn't exist. How can this be fixed? class ServerAuth(models.Model): name = models.CharField(max_length=120, default="name") allow_default = models.BooleanField() class AuthUrl(models.Model): url = models.CharField(max_length=120) server_auth = models.ForeignKey(ServerAuth, on_delete=models.CASCADE, related_name="auth_urls") @receiver(post_save, sender=ServerAuth) @receiver(post_save, sender=AuthUrl) def do_something(sender, **kwargs): auths = AuthUrl.objects.filter(server_auth_id =kwargs.get('instance').id) print(auths) -
Handling server timeout (503) for request with heavy calculations
I deployed my first project in which I'm visualising clusters in a user's Spotify playlist, using Django for backend and React for frontend. One of the services of my Django backend receives an array of features of the tracks in the selected playlist. These features are then reduced using Scikit Learn's TSNE. However, it may take more than 30 seconds before the service returns a response with output to visualise, meaning that the server times out with code 503. I'm looking for suggestions to solve this issue and any would be appreciated. -
sign up form doesn't work (CSRF token missing or incorrect.) django
I'm trying to do a registration form where users get added to users group in the admin interface but for some reason, the registration form doesn't get saved in the database instead it gives me this error Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: CSRF token missing or incorrect. can someone tell me what I'm missing here? decorators.py from django.http import HttpResponse from django.shortcuts import redirect def unauthenticated_user(view_func): def wrapper_func(request, *args, **kwargs): if request.user.is_authenticated: return redirect('index') else: return view_func(request, *args, **kwargs) return wrapper_func def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse('You are not authorized to view this page') return wrapper_func return decorator def admin_only(view_func): def wrapper_function(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group == 'user': return redirect('home') if group == 'admin': return view_func(request, *args, **kwargs) return wrapper_function views.py @unauthenticated_user def sign_up(request): data = CreateUserForm() if request.method == 'POST': data = CreateUserForm(request.POST or None) if data.is_valid(): user = data.save() username = data.cleaned_data.get('username') group = Group.objects.get(name='user') user.groups.add(group) messages.success(request, 'Account was created for ' + username) return redirect('login') context = {'info':data,} return render(request, 'signup.html', context) … -
Django - Change the default invalid email error message in ModelForm
I'm using a ModelForm to save users. The User model is the default django.contrib.auth.models.User. My ModelForm class is like this class RegisterForm(ModelForm): password = CharField(label="Password", widget=forms.PasswordInput(attrs={'class': 'form-control'})) confirm_password = CharField(label="Confirm your password", widget=forms.PasswordInput(attrs={'class': 'form-control'})) class Meta: model = User fields = ('username', 'email', 'password') labels = { 'username': 'User name', 'email': 'E-mail', } widgets = { 'username': TextInput(attrs={'class': 'form-control'}), 'email': TextInput(attrs={'class': 'form-control'}) } When I put an invalid email, I have in RegisterForm.email.errors the message "Enter a valid email address." How do I change this message? -
The ModelResource Meta field import_id_fields seems that it doesn't work as expected
I'm building a web app using the Django framework and the django-import-export package. I would like to import data from files and want to prevent importing it twice to the DB. For this, I used the import_id_fields when declaring the resource class, but it seems that it doesn't work as expected. 1- The first time I import the file everything is working fine and rows created in the DB. 2- The second time I import the same file, also new rows created in the DB (here is the problem, this is not supposed to happen) 3- The third time I import the same file, here I get errors and no rows added to the DB. So I would like to know if this is normal behavior or not, and if is normal I would like to know how can I stop the import in point 2 and show the errors. You can find below portions from the code and the error messages. # resources.py class OfferingResource(ModelResource): ACCESSIONNUMBER = Field(attribute='company', widget=ForeignKeyWidget(Company, 'accession_number')) quarter = Field(attribute='quarter') # other fields ... class Meta: model = Offering import_id_fields = ('ACCESSIONNUMBER', 'quarter') def before_import_row(self, row, row_number=None, **kwargs): Company.objects.get_or_create(accession_number=row.get('ACCESSIONNUMBER')) # models.py class Company(models.Model): accession_number = models.CharField(max_length=25, … -
Form for editing a page doesn't work in Django (CS50 Project)
I am creating a Wikipedia like web app in django and one of the features is that the user is able to edit a page. I have tried to code this, however it doesn't seem to work. I have spent hours trying to figure out the problem and I am unable to fix it. When I enter data into the form, it isn't getting saved onto the file. I press the edit page link, it takes me to editpage.html (which is /wiki/pageName/editpage) and I can type in different data, but when I press the save button, nothing is saved and when I look at the actual file on the disk, it is still the original and none of the edits have been saved. my views.py editpage function: def editpage(request, title): if request.method == 'post': form = editPageForm(request.POST) if form.is_valid(): pageTitle = form.cleaned_data['title'].capitalize() pageContent = form.cleaned_data['content'] util.save_entry(pageTitle, pageContent) return HttpResponseRedirect(f'/wiki/{pageTitle}') else: return render(request, 'encyclopedia/editpage.html', { 'title': title, 'content': util.get_entry(title) }) my urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path('<str:title>/editpage', views.editpage, name='editpage'), path('newpage', views.newpage, name='newpage'), path(f'<str:title>', views.display, name='display') ] the editpage.html website: {% extends "encyclopedia/layout.html" %} {% block title %} Editing: {{ title }} …