Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Django performing independent interval tasks
It became necessary, in certain situations, to create a periodic task that will check the state of the user every minute. For this I am using django_celery_beat + PeriodicTask + IntervalSchedule When this task is 1, everything is fine. But when a new one is created for another user, the task execution shifts: for example, the first user was checked every minute starting from 10:14:40, the next check should have been at 10:15:40, but a new task was created at 10:15:35 and both users end up being verified at 10:16:35 How can I solve my problem? each user should be checked every minute within its own interval. -
Django deploy Pythonanywhere
The site work fine on my localhost, but I have problems deploying It. wsgi log -
Adding a parent class between models.Model and my Model classes
I have different apps that pertain to different functionalities, but typically they all follow more or less the same patterns. In order to have easy (and flexible) access to the data I need in my templates, I need to implement some methods in my Models. For instance, these methods would be needed in a few different apps in order to populate a list view that contains only a small subset of all the fields of the model: class Produit(models.Model): # fields to present the summary summary_table_headers = ["id","no_prod","descfr","descang", ...] @classmethod def get_list_summary_headers(cls): """ returns the table headers so the template can easily populate <th>""" # return [h for h in cls.summary_table_headers] return [(h, cls._meta.get_field(h).verbose_name) for h in cls.summary_table_headers] def get_fields_values(self): return [field.value_to_string(self) for field in Produit._meta.get_fields()] @classmethod def get_fields(cls): fields = [field.name for field in Produit._meta.get_fields()] return fields Then I have bunch of different apps, but all needs to present a summary list view of sorts. Things are still very much in development, so I wanted to be able change what is to be part of the summary in ONE place (e.g. the models). Then the template just iterates and renders everything that's handed to it. If I need to … -
Connecting Django User model with custom models error using one_to_one_field
models.py This is the models.py file of my django project. I am getting this error in 5 line of the code below.I wanted to connect django default User model to my model by OneToOneField to provide multiple account functionality to my project. but I am stuck at this error that I don't understand. plz, help. from django.contrib.auth.models import User # Create your models here. class DailyTrack(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, related_name = 'Profile', default='') income = models.IntegerField() expense = models.IntegerField() added = models.DateTimeField(auto_now_add=True) def __str__(self): return f'Income {self.amount} Income {self.amount}' error is in the 4th line at the default field, I tried removing default or adding it but I am unable to understand this. There is an error for Operations to perform: Apply all migrations: admin, auth, contenttypes, dailytrackapp, sessions Running migrations: Applying dailytrackapp.0003_dailytrack_user...Traceback (most recent call last): File "C:\Users\NIitin\AppData\Roaming\Python\Python39\site-packages\django\db\models\fields\__init__.py", line 1774, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'null' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\NIitin\Desktop\MultiProj\DailyTrack\manage.py", line 22, in <module> main() File "C:\Users\NIitin\Desktop\MultiProj\DailyTrack\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\NIitin\AppData\Roaming\Python\Python39\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\NIitin\AppData\Roaming\Python\Python39\site-packages\django\core\management\__init__.py", line 395, in execute … -
how to fix "'coroutine' object has no attribute 'get' and UploadFileForm() takes no arguments
im trying to write a Asynchronous File Uploads with Django Forms. form.py: from django import forms class UploadFileForm(forms.Form): file_name = forms.CharField(max_length=30, min_length=3) file = forms.FileField() views.py: import aiofiles from django.shortcuts import render from .forms import UploadFileForm async def handle_uploaded_file(file): """awaitable function to upload a file and put it in media folder""" async with aiofiles.open(f"media/{file.name}", "wb+") as destination: for chunk in file.chunks(): await destination.write(chunk) async def upload(request): if request.method == 'GET': form = UploadFileForm() context = {'form': form} return render(request, 'upload.html', context) if request.method == 'POST': form = UploadFileForm(data=request.POST, files=request.FILES) if form.is_valid(): await handle_uploaded_file(request.FILES['file']) return render(request, 'upload.html') i got these errors: TypeError: UploadFileForm() takes no arguments "'coroutine' object has no attribute 'get'" hope you guys can help me to fix this:) -
username and password in Qrcode with django
I have a simple qr scanner and qrcode in python. This opens a website after scanning. What i want: the django username and password in a qrcode. So the user scans the qr and logs in. I dont know how to convert the password of the user because of the hash. Here is the code for creating the qrcode (from model). def create_Qrcodes(sender, instance, created, **kwargs): if created: url = the url to go to after scanning the qrcode new_qrcode = Qrcodes.objects.create(vacature=instance) qrcode_img = qrcode.make(url + str(instance.id) + "/") new_qrcode.url_vacature = url + str(instance.id) + "/" new_qrcode.save() canvas = Image.new('RGB', (600,600), 'white') draw = ImageDraw.Draw(canvas) canvas.paste(qrcode_img) random_nummer = random.randint(10000000, 90000000) fname = f"{new_qrcode.id}{random_nummer}.png" buffer = BytesIO() canvas.save(buffer, 'PNG') new_qrcode.image.save(fname, File(buffer)) canvas.close() So what i want is an qrcode of the username and password. -
Why is my object's new data not saving inside a function
newbie to Django here. So I made a model with an attribute being a list. Then I made an instance of it. Then I have a function that has a for loop that appends to the "class list" attribute of the object. This is not permanently saving the list data to the attribute of the object (isn't that the whole point of model objects?). I am very confused on how to do that. class Mymodel: class_list = [] my_object = Mymodel() def myFunction(): for loop: my_object.class_list.append(some_value_that_I_want) return something_unrelated -
Should I use select_for_update in my django application with postgresql database?
I am currently building a booking tool (django and postgresql) where people book spaces in a location. The location has limited capacity and therefore might run out of space while a user is trying to book a space. I imagine that this could happen when another user books a place slightly before the current user is booking, e.g. if only 1 space is left, the other user might book too and the database cannot handle it. So my question is would you strongly advise using select_for_update or is there something else that might help me overcome this issue? -
how can I delete all non-matching query results in django?
Say I have a list of values list =['value1',value2'value3'...'...'] Is there a way I can run a query against a whole Db and delete any entries that don't match? The opposite of the below almost: models.objects.filter(value__in=list).delete() -
How to invoke DRF has_object_permission() method with a function based view and Token auth?
I am using DRF with authentication. I have implemented both Session and Token auth. The first is used by the browsable API that I use to debug and the second is the auth that will be used by the actual client. I have the following detail view: @api_view(['GET', 'PUT', 'DELETE']) @permission_classes([permissions.IsAuthenticated, IsTrainingOwner]) # this view is only available to authenticated users def training_detail(request, pk, format=None): """ Retrieve, update or delete a training. Need to be authenticated """ print(request.user) try: training = Training.objects.get(pk=pk) except Training.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = TrainingSerializer(training) return Response(serializer.data) elif request.method == 'PUT': serializer = TrainingSerializer(training, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': training.delete() return Response(status=status.HTTP_204_NO_CONTENT) As you cas see I am using a custom permission: class IsTrainingOwner(permissions.BasePermission): """ Custom permission to only allow owners of an object to see and edit it """ def has_object_permission(self, request, view, obj): # Read permissions are allowed to any request, # so we'll always allow GET, HEAD or OPTIONS requests. if request.method in permissions.SAFE_METHODS: print("Object owner: ", obj.owner) print("Request user: ", request.user) return True # Instance must have an attribute named `owner`. print("Object owner: ", obj.owner) print("Request user: ", request.user) return … -
API returns image as binary, trying to convert to image or serialize the binary in DRF to send to FE
I'm working on Azure AD authentication in a React and Django/DRF app. I have the token exchanges, validations, handshakes, etc. figured out between the services. Part of the process is querying the user against http://graph.microsoft.com/v1.0/me end-point to get information about the user so it can be added/updated in the database. What I'm trying to do now is get the tiny image of the user to display in the navbar. The image comes from the http://graph.microsoft.com/v1.0/me/photo/$value end-point. Per the documentation (1, 2): Response Contains the binary data of the requested photo. The HTTP response code is 200. This is what I have so far: # serializers.py class AadTokenSerializer(serializers.Serializer): access_token = serializers.CharField(write_only=True) user_picture = serializers.CharField(read_only=True) # user_picture = serializers.ImageField(read_only=True) def validate(self, data): try: ... data['user_picture'] = aad.ms_graph(data['access_token']) return data except: ... # aad.py def ms_graph(access_token): graph_response = requests.get( # Use token to call downstream service 'https://graph.microsoft.com/v1.0/me/photo/$value', headers={'Authorization': 'Bearer ' + access_token},) return graph_response.text This returns a long string of symbols and this is what is sent back to the FE: Returning just graph_response instead of graph_response.text just returns the URL string. I've been stuck for a few hours now so I have some questions: Should I be converting this to an image … -
Translating the fields' labels of wagtail's form
I used Wagtail Forms builder to create a simple form, I'm rendering it manually kind of in the template because I need to style the labels and the fields so I display the fields like this {% for field in form %} <div class="form-group"> {% if field.name == "wagtailcaptcha" %} {{ field }} {% endif %} {% if field.field.widget.input_type %} <label class="control-label">{% trans field.label %}{% if field.field.required %}*{% endif %}</label> <input value="{{ field.value|default_if_none:'' }}" name="{{ field.name }}" id="{{ field.id_for_label }}" type="{{ field.field.widget.input_type }}" class="form-control" placeholder="{% trans field.help_text %}"> {% endif %} {% endfor %} Now unfortunately this part {% trans field.label %} is not working, also translating the placeholder is not working as well, so when I run the makemessages command, no msgid is generated, although other translations are working just fine, any idea? -
NoReverseMatch at / 'usuario' is not a registered namespace inside 'accounts'
I'm trying to build a custom user registration system but when creating the profile page it throws me that error. I've seen other similar problems in Github but those doesn't match the same problem as the one I'm facing. Any idea why {% url 'accounts:usuario:pk' %} throws this error? Here is what I got accounts/views.py from django.views.generic.detail import DetailView from django.shortcuts import get_object_or_404 ... class UserProfileView(DetailView): model = CustomUser template_name = 'registration/edit_profile.html' def get_context_data(self, *args, **kwargs): user = CustomUser.objects.all() context = super(UserProfileView, self).get_context_data(*args, **kwargs) usuario = get_object_or_404(CustomUser, id=self.kwargs['pk']) context['usuario'] = usuario return context ... accounts/urls.py from django.contrib import auth from django.contrib.auth import views as auth_views from django.urls import path from .views import ( ... UserProfileView, ) app_name = 'accounts' urlpatterns = [ ... path('perfil/<int:pk>', UserProfileView.as_view(), name='usuario'), ... ] projectname/urls.py from django import contrib from django import urls from django.conf import settings from django.contrib import admin from django.urls import path from django.urls.conf import include from .views import ( home_page ) urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('accounts.urls', namespace='accounts')), path('accounts/', include('django.contrib.auth.urls')), path('', home_page, name='home'), ... ] if settings.DEBUG: #test mode from django.conf.urls.static import static urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) templates/navbar.html {% load static %} <!-- Navigation--> <nav class="navbar navbar-expand-lg … -
Unable to install Django package in a Docker container
I'm trying to install a simple Django package in a Docker container. Here is my dockerfile FROM python:3.8 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY Pipfile Pipfile.lock /app/ RUN pip install pipenv && pipenv install --system COPY . /app/ And here is my docker-compose: version: '3.7' services: web: build: . command: python /app/manage.py runserver 0.0.0.0:8000 volumes: - .:/app ports: - 8000:8000 depends_on: - db db: image: postgres:11 volumes: - /Users/ruslaniv/Documents/Docker/djangoapp:/var/lib/postgresql/data/ environment: - POSTGRES_USER=XXX - POSTGRES_PASSWORD=XXX - POSTGRES_DB=djangoapp volumes: djangoapp: So, I start my container with docker-compose up then install a package and rebuild an image docker-compose exec web pipenv install django-crispy-forms docker-compose down docker-compose up -d --build Then I add 'crispy_forms' into local settings.py and register crispy forms tags in a local html file with {% load crispy_forms_tags %} and then use them for the form with {{ form|crispy }} But the form is not rendered properly. Since the package itself and its usage are very simple I think there is a problem with installing the package in a container. So the question is how to properly install a Django package in a Docker container and am I doing it properly? -
Display img from an Id in Django
In my Django work in progress website, I have a folder with more than a thousand of thumbs, with an Id inside their names, just like this : the_name_of_the_thumbnail_123456_low.png This Id is retrieved from a request from a database. For displaying the corresponding picture on my site I have to build the url string, maybe like this : {% static images/low/the_name_of_the_thumbnail_ {{var}} _low %}. How can I perform this task ? With regex, from the template ? or another way ? Thank's a lot -
Django - setting staff member as default for new users
everybody! I'm trying setting as default staff_member to new users, but I cannot find any solution. I really need help. My codes are below. models class Participante(models.Model): nome = models.CharField(max_length=100) cpf = models.CharField(max_length=13) email = models.EmailField() dt_criacao = models.DateTimeField(auto_now=True) is_staff = models.BooleanField( ('staff status'), default=True, help_text=('Designates whether the user can log into this admin site.'), ) def __str__(self): return self.nome forms class ParticipanteForm(UserCreationForm): first_name = forms.CharField(max_length=100, label='Primeiro nome') last_name = forms.CharField(max_length=100, label='Último nome') class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'password1', 'password2'] views def cadastro(request): form = ParticipanteForm() if request.method == 'POST': form = ParticipanteForm(request.POST) if form.is_valid(): #User(request, username=username, password=password1) form.save() return redirect('dashboard') return render(request, 'cadastro.html', locals()) -
Must the classes in Django's many-to-many relationship be in the same models.py file?
Please help me better understand how the ManytoManyField works in Django. Maybe the examples I've seen are simple ones for beginners, but it seems in all the examples, the classes involved in ManytoManyFields are in the same models.py file. In my exercise (following a tutorial, I put the two classes in two different models.py file(different apps), and am struggling to make them connect. So my question #1: Do the classes in Django's many-to-many relationship have to be in the same models.py file? #2 For a true many-to-many relationship, do I need to create a "through" table/relationship? Here is the relevant code snippets from the tutorial: #app='household' class Member(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) # household = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) photo = models.ImageField( upload_to='uploads/members/', default='/icons/member.svg') def __str__(self): return '%s Household | %s' % (self.user, self.name) #app=meals class Meal(models.Model): name = models.CharField(max_length=255) date = models.DateField() members = models.ManyToManyField('Member') -
Best way to create forms in django
I am learning django, when it comes to creating forms, there are three ways to create a forms in django, create forms in html Forms api ModelForm what method should i use for creating forums, are there any advantage of using one instead of other, or all are equal? -
How do I get user IP address for each user in django?
I have to get each user's IP, compare to the last IP used by that user and if it's different i should notify the different IP and send a messagge like "Your IP address is different than last time, are still you?" Any help is appreciated. -
I keep getting a 'Reverse for 'pdf' not found. 'pdf' is not a valid view function or pattern name.' error
This is actually a student result portal, when a student wants to check for his result, he clicks a search button. On clicking the search button, his result is to be displayed on the screen but that is not the case for this code. Whenever I click on the search button, this line of code is highlighted so, I think the problem this from this line ' return render(request, 'result.html', {'object': object,'pk': pk, 'marks': marks})'. Please help. This is the error it produces. django.urls.exceptions.NoReverseMatch: Reverse for 'pdf' not found. 'pdf' is not a valid view function or pattern name. [06/Apr/2021 12:44:00] "GET /dashboard/find-result/6/result/ HTTP/1.1" 500 166385 This is the code Django def index(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] print("\nUser Name = ",username) print("Password = ",password) user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('dashboard:dashboard') else: context = {'message':'Invalid Username and Password'} return render(request, 'index.html', context) return render(request, 'index.html', {'name': 'Risky', 'pass': 'risky'}) class DashboardView(LoginRequiredMixin,TemplateView): template_name = "dashboard.html" def get_context_data(self, **kwargs): context = super(DashboardView, self).get_context_data(**kwargs) context['cls'] = StudentClass.objects.count() context['results'] = DeclareResult.objects.count() context['students'] = Student.objects.count() context['subjects'] = Subject.objects.count() return context def find_result_view(request): student_class = DeclareResult.objects.all() if request.method == "POST": data = request.POST # … -
How to pass the fetched tweet(tweepy.StreamListener) into html page using django
I want to create a web page which should scrap twitter to fetch user data by given location I am using tweepy's StreamListener to fetch tweet by location but i don't know how to pass that to html page using render in django MyListerner class is fetching the tweets but its not returning the fetched tweet I want to fetch tweets by given location and pass that into html file when I tried to render the page inside MyStreamListener class I couldn't pass request value in on_status Error : undefined parameter request inside filter() method Without passing request inside filter its raising on_status missing one argumet request and without defining request parameter in on_status i couldn't render the template Error : join() should not contain dict value Is there any proper way to return the fetched tweet into django template class Authenticator: def authenticate_and_get_API_object(self): apiKey = "LkfFnN703BrTCz8HVzG7nIqwj" apiSecretKey = "4NItiGYdtWdqfOIn6POsfKJPXbKe4MWYDNBJRhfZNlrZCc3xRj" accessToken = "1151434267139825664-zqjDQaDjy3GjoA1gS157kSL0YDh6cU" accessTokenSecret = "nv1PtIhEqaDmV55N8if1Fl8LkER8Jw4AidcJ7r3Q7jSYk" auth = tweepy.OAuthHandler(apiKey, apiSecretKey) auth.set_access_token(accessToken, accessTokenSecret) api = tweepy.API(auth) return api class MyStreamListener(StreamListener): def __init__(self): super().__init__() self.start_time = time.time() self.limit = 5 def on_status(self, status): api = Authenticator().authenticate_and_get_API_object() if (time.time() - self.start_time) < self.limit: tweets = tweepy.Cursor(api.search, count=10, q="python", lang="en", since='2021-03-18').items(100) count = 1 … -
why django apps don't have a urls.py file?
why when we create a app django doesn't provide a urls file and we have to create our own url file? however, when we start a project django provide us this file? Someone know why this happens? -
Getting error when I try to convert raw queryset to queryset
The query itself is correct and I am able to get the raw query set. I need to convert this into query set for further processing and I am facing below error. Creating corresponding django query was hard for me and that is why I created SQL query, got the raw query set and now attempting to convert it to query set for further processing. I have changed model and table names for anonymity. queryset = Test1.objects.filter(id__in=RawSQL("SELECT DISTINCT ON (test1.start_time, test1.id) test1.id, test1.name, test1.start_time FROM test1 WHERE EXISTS (SELECT * FROM test2 JOIN test3 ON test2.test3_id = test3.id AND test3.value = '{param}' JOIN test4 ON test2.test4_id = test4.id AND test4.test1_id = test1.id) ORDER BY test1.start_time DESC".format(param=val))) Traceback (most recent call last): File "<console>", line 1, in <module> TypeError: __init__() missing 1 required positional argument: 'params' Here is the formatted raw query SELECT DISTINCT ON (test1.start_time, test1.id) test1.id, test1.name, test1.start_time FROM test1 WHERE EXISTS ( SELECT * FROM test2 JOIN test3 ON test2.test3_id = test3.id AND test3.value = '{param}' JOIN test4 ON test2.test4_id = test4.id AND test4.test1_id = test1.id ) ORDER BY test1.start_time DESC.format(param = val) ) -
Django : invalid date format with Pandas - \xa0
I would like to create objects from a CSV file with Django and Pandas. Everything is fine for FloatFields and CharFields but when I want to add DateFields, Django returns this error: ['The date format of the value "\xa02015/08/03\xa0" is not valid. The correct format is YYYY-MM-DD.'] However, the CSV file proposes this type of data for the columns concerned: '2015/08/03'. There is no space in the data as Django seems to suggest... here is what I tried in views : class HomeView(LoginRequiredMixin, View): def get(self, request,*args, **kwargs): user = User.objects.get(id=request.user.id) Dossier.objects.filter(user=user).delete() csv_file = user.profile.user_data df = pd.read_csv(csv_file, encoding = "UTF-8", delimiter=';', decimal=',') df = df.round(2) row_iter = df.iterrows() objs = [ Dossier( user = user, numero_op = row['N° Dossier'], porteur = row['Bénéficiaire'], libélé = row['Libellé du dossier'], descriptif = row["Résumé de l'opération"], AAP = row["Référence de l'appel à projet"], date_dépôt = row["Date Dépôt"], date_réception = row["Accusé de réception"], montant_CT = row['Coût total en cours'], ) for index, row in row_iter ] Dossier.objects.bulk_create(objs) If I change my Model to CharField, I no longer get an error. I tried to use the str.strip() function: df["Date Dépôt"]=df["Date Dépôt"].str.strip() But without success. Could someone help me? I could keep the CharField format but … -
Create Chatroulette-like application
I want to create Chatroulette like web application, but not sure where to start and what technologies to learn (and in which order). My current tech stack (stuff I am more or less familiar with): Django Flask React Of course I will be happy to familiarize myself with other technologies similar to ones I'm already familiar with if they propose significant advantages for Chatroulette case, but prefer to utilize familiar technologies to the most. Thank you in advance!