Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make it work datetime datetime strptime
can you tell me why it doesn't translate the date into numbers? import datetime from datetime import datetime as dt from datetime import timedelta from django.db import models from django.utils import timezone from django.utils.timezone import now def end_date(): return datetime.date.today() + timedelta(days=7).strftime("%d %B, %Y") def add_date(): add_date = datetime.date.today() data_object = dt.datetime.datetime.strptime(add_date, "%d %B, %Y").date() return data_object class add(models.Model): add_date = models.DateField('Дата додавання', auto_now_add=True) as I do not output from the DB string month -
Django: How to join two models and get the fields of both as a result?
My models : I have 2 (simplified) models: class Message(models.Model): mmsi = models.IntegerField() time = models.DateTimeField() class LastMessage(models.Model): mmsi = models.IntegerField() time = models.DateTimeField() From the most recent Message, I want to check if there are Message not in LastMessage. I can get the most recent Message like that : recent_messages = (Message.objects.distinct('mmsi') .order_by('mmsi', '-time')) From there, I have no idea how to extract the informations I want from recent_message and LastMessage. I'd typically like to have the information displayed like this : MMSI | Message_Time | LastMessage_Time I can do that with SQL like this for example : SELECT r.mmsi, r.time as Message_Time, l.time as LastMessage_Time FROM recent_message as r INNER JOIN core_lastmessage as l on r.mmsi = l.mmsi WHERE r.time <> l.time LIMIT 10; ┌─────────┬────────────────────────┬────────────────────────┐ │ mmsi │ message_time │ lastmessage_time │ ├─────────┼────────────────────────┼────────────────────────┤ │ 2000000 │ 2019-09-10 10:42:03+02 │ 2019-09-10 10:26:26+02 │ │ 2278000 │ 2019-09-10 10:42:24+02 │ 2019-09-10 10:40:18+02 │ │ 2339002 │ 2019-09-10 10:42:06+02 │ 2019-09-10 10:33:02+02 │ │ 2339004 │ 2019-09-10 10:42:06+02 │ 2019-09-10 10:30:07+02 │ │ 2417806 │ 2019-09-10 10:39:19+02 │ 2019-09-10 10:37:02+02 │ │ 2417807 │ 2019-09-10 10:41:18+02 │ 2019-09-10 10:36:55+02 │ │ 2417808 │ 2019-09-10 10:42:23+02 │ 2019-09-10 10:30:39+02 │ │ 2470087 … -
How to inform a variable with a random value in Django 2.0?
I have a client list in Django, and I need to return a random number between 1 and 999 for each new client. Also, for each new client and random number generated, I need to inform whether or not the client is approved to receive a certain amount of credit. And, if approved, there are some conditions as well. I need this for a job interview as a Junior dev, who's gonna be working with Django RESTFramework and, in the future, a little bit of React as well. This is what I have tried so far: income = float() score = random.randint(1, 999) aprovado = False credit = float() if 0 < score < 300: aprovado = False elif 299 < score < 600: aprovado = True credit = 1000 elif 599 < score < 800: aprovado = True if income < 2000: credit = 1000 else: credit = income * 0.5 elif 799 < score < 951: aprovado = True credit = income * 2 else: aprovado = True credit = 1000000 The logic is working properly in a separate (blank) file, but I cannot find a way to insert this to the Django app. The 'score' needs to … -
How to Unit or Integration Test in Python Django Models in Docker
I watched this tutorial on YouTube https://www.youtube.com/watch?v=6wxO8hRIP4w and it helped me in a way but the tutorial lacks on how to test a Django Model. Here's the code I've got so far: conftest.py import pytest from urllib3.util.retry import Retry from requests.adapters import HTTPAdapter import requests @pytest.fixture(name="homepage") def fixture_homepage(function_scoped_container_getter) -> str: service = function_scoped_container_getter.get('app').network_info[1] base_url = f"http://{service.hostname}:{service.host_port}" retry = Retry( total = 30, backoff_factor=10, status_forcelist = [500, 502, 503, 504] ) session = requests.Session() session.mount('http://', HTTPAdapter(max_retries=retry)) return base_url first_test.py from requests import get pytest_plugins = ["docker_compose"] def test_one(): assert 1==1 def test_initial_ticket(homepage: str): print("HOMEPAGE: ", homepage) temp_str = get(homepage+"/admin").text #check if the pytest can already open the admin login page assert "Admin Login" in temp_str When I run pytest integration_tests/initial_user_receipt_test.py -s, both of the tests in first_test.py passes. I can also see that when I run this script, the docker image is built. However, I want to test inserting to a model.py which is located in the same folder as the integration_tests folder. I have tried importing the model directly and some classes inside it but it doesn't work. My folder structure is as follows: - Project - integration_tests - conftest.py - first_test.py - apps.py - models.py #contains a User class -
cv2 can't open base64 decoded video
I had the video uploaded to my django-rest project by send the base64 encoding, but i need to check if the upload file is video by trying to open it using cv2 but it doesn't accept it and throws an error class VideoBase64File(Base64FileField): ALLOWED_TYPES = ['Video'] def get_file_extension(self, filename, decoded_file): try: cv2.VideoCapture(decoded_file) return 'Video' except: return 'non-valid' I want a way to check if the 'decoded_file' is a video -
How am I able to create a file structure based on the current date?
I'm trying to log changes in our CMS to a logging file. I make use of the def logging_on_activity(). What I want is a new file for each day to keep the log records a bit organised. I've already tried to use the datetime package to manually edit the filename. def logging_on_activity(platform, appname, msg): import datetime now = datetime.datetime.now() if SITE_TYPE == SiteType.LOCAL: filename = 'path_to/../logs/' + str(now.__format__('%Y')) + '/' + str(now.__format__('%m')) + '/' \ + str(now.__format__('%d')) + '/logging.log' import datetime date = datetime.date.today().isoformat() time = datetime.datetime.now().strftime('%H:%m:%S') # Write to file with open(filename, 'a') as handle: handle.write("{0} {1} [ii] [{2:^19}] [{3:^19}] {4}\n".format(date, time, platform, appname, msg)) The error I get is: FileNotFoundError at .. [Errno 2] No such file or directory: 'itdb_tools/logs/2019/09/11.log' Example of what I want? Date: 2019/09/11 -> System is writing to: path_to/../logs/2019/09/11/logging.log Date: 2019/09/12 -> System is writing to: path_to/../logs/2019/09/12/logging.log I hope what I want to achieve is possible. Thanks in advance and I hope someone can help me in the right direction! -
How to click through a datatables row and populate a detailed view with the data in django?
I have a datatables table that works fine and is populated with data. I would like to allow the user to click on one of the rows, which would then take them to a detailed view which would display the record in a more user friendly, readable format. I have the form ready, I am just not sure how to go about passing all the row data through to the target view - I've got a general idea how to do it by POSTing it as an AJAX request, capturing it in my views.py and getting the data out of it and passing it to the target view but I am not sure on the actual implementation. Does anyone have any kind of similar example that achieves this? Many thanks! -
Having trouble linking two fields with one anoter, then implementing them to another model
I'm working on a project which helps users find jobs. So one of the models, named Oferta is used for details about a job. Someone who is looking for emplooyes, just completes a form which is based on this model, and people will be looking at it. Here's this model: class Oferta(models.Model): solicitant = models.ForeignKey(User, on_delete=models.CASCADE) cor = models.CharField(max_length=50) dataSolicitare = models.DateField(default=date.today) denumireMeserie = models.CharField(max_length=50) locuri = models.IntegerField() agentEconomic = models.CharField(max_length=50) adresa = models.CharField(max_length=150) dataExpirare = models.DateField() experientaSolicitata = models.CharField(max_length=200) studiiSolicitate = models.CharField(max_length=200) judet = models.CharField(max_length=20) localitate = models.CharField(max_length=25) telefon = models.CharField(max_length=12) emailContact = models.EmailField(max_length=40) rezolvata = models.BooleanField(default=False) def __str__(self): return self.cor The COR field is the code asociated to a job. Also, denumireMeserie means job name. So these should be linked. Let's say, if code 1 means "Cook", these should be link - there will be no other job with a different code, or another job for code 1. So, in my opinion, these two fields should have a OneToOne relationship between them, if I'm not mistaken. But these codes and jobs need to be implemented in the database - so they need a model too. class CORMeserii(models.Model): CodCOR = models.CharField(max_length=25, primary_key=True, unique=True) MeserieCor = models.OneToOneField(CodCOR, max_length=50, unique=True, on_delete=models.CASCADE) … -
Unit tests in Django with requests for different subdomains
With the help of the package "django-hosts", we have implemented two subdomains for our Django project. One subdomain is "registration" and another one is "lectures". The Django admin interface is located and accessible from both subdomains. We have a unit test in which a POST request is sent to the "lectures" subdomain. However, in the testing environment, Django uses "testserver" domain, so our POST request is sent to the "testserver/en/reset-credentials" instead of "lectures.ourdomain.com/en/reset-credentials" because the "reverse" method is from "django-hosts" package and it returns URLs with these subdomains. We use "django_webtest" package for implementing these requests. We tried using "HTTP_HOST" parameter with "lectures.ourdomain.com" as its value. However, that does not seem to work as expected, because after a successful request (which worked in the beginning, before subdomain implementation) no email is sent, and our view which accepts this POST request sends an email by default. In the local, development environment, subdomains are defined in the hosts file for testing purposes. What would be the best approach for writing unit tests with Django project that has subdomains? -
Django doesn't provide a DB representation for AnonymousUser
I doing custom reset password with email confirm. path('password_reset', views.reset_password_view, name='password-reset'), path('password_reset/done', views.reset_password_done_view, name='password_reset_done'), path('reset/<uidb64>/<token>/', views.password_confirm_view, name='password_reset_confirm') def password_confirm_view(request, uidb64, token): context = {} if request.method == 'POST': form = SetPasswordForm(data=request.POST, user=request.user) if form.is_valid(): form.save() #I have error update_session_auth_hash(request, form.user) return redirect('password_reset_done') else: form = SetPasswordForm(user=request.user) context['form'] = form return render(request, 'mdm/registration/password_confirm.html', context) Exception Type:NotImplementedError Exception Value:Django doesn't provide a DB representation for AnonymousUser. How i can autherisation user? I think, I must used (uidb64, token). -
'str' object has no attribute 'verified'
I am including OTP in my project with twilio. But When verifying phone number it throws following error. phone.verified = True AttributeError: 'str' object has no attribute 'verified' models.py class User(AbstractBaseUser, PermissionsMixin): phone = models.CharField(max_length=15, unique=True) is_active = models.BooleanField(default = True) is_staff = models.BooleanField(default = False) USERNAME_FIELD = 'phone' key = models.CharField(max_length=100, unique=True, blank=True) verified = models.BooleanField(default=False) objects = UserManager() views.py @api_view(['GET']) def send_sms_code(request, format=None): time_otp = pyotp.TOTP(request.user.key, interval=10000) time_otp = time_otp.now() user_phone_number = request.user.phone client.messages.create( body="Your verification code is "+time_otp, from_=twilio_phone, to=user_phone_number ) return Response(status=200) @api_view(['GET']) def verify_phone(request, sms_code, format=None): code = int(sms_code) if request.user.authenticate(code): phone = request.user.phone phone.verified = True phone.save() return Response(dict(detail = "Phone number verified successfully"),status=201) return Response(dict(detail='The provided code did not match or has expired'),status=200) it sends me a verification code but When I am going to verify it does not work properly. I know where the problem is but How can I solve it? Any help would be appreciated! Thanks beforehand! -
Django migrations no changes detected after changing directory structure
I have created a Django project using this directory structure : bi3online __init__.py migrations __init__.py static templates media manage.py models.py urls.py views.py wsgi.py ... When I run python manage.py makemigrations and python manage.py migrate it only creates migrations for auth app and then when I try again it says no changes detected. It seems that migrations work only with apps but I'm not sure. -
How to enforce a static order for row_result diff list in ModelResource?
I'm using django-import-export module to import data from spreadsheet to my model via a ModelResource. After the instance initialization process and after the diff between the original and the imported object fields are calculated and a row result is generated, I want to be able to: 1) change the order of the headers in the html, which shows you the imported field values. 2) Add custom values for fields. So far I have tried to override the after_import_row method in my ModelResource to tackle the problem stated in #2: def after_import_row(self, row, row_result, **kwargs): diff = row_result.diff custom_value = 'Custom: {}'.format(row['Reason']) diff[2] = custom_value I expect the third column header value of the HTML table to be changed to what I put in the step above. But since the header order is changed, I cannot ensure that the custom value is matching the header I want. That is why I want to enforce a static order for the diff headers in the row result. How can I do this? -
How to place default value in to dropdown form field in django
I'm building a post-comment model in one view, one page, something like facebook. I have two forms in my home.html and view.py: new post and new comment. In each post container, there is a new comment form. I have a problem because I don't know how to relate comment to post - specifically how to pass post.id to my comment form. Is it possible to pass my {{ post.id }} to my {{newCommentForm.field }}? That each comment has a default value of post's id? My home.html: {% for post in posts %} <div class="container"> <a class="user" href="#">{{ post.author }}</a>, {{ post.date_posted }} <img src="{{ post.author.profile.image.url }}" alt="{{ post.author }}"style="width:100%;"> <p>{{ post.content }}</p> <form METHOD="POST" class="new_post"> {% csrf_token %} {{ newCommentForm.content }} {{ newCommentForm.post }} <button type="submit" name="newCommentSubmit">Add</button> </form> </div> {% endfor %} models.py class Post(models.Model): content = models.TextField(max_length=1000) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.content class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField(max_length=500) date = models.DateTimeField(default=timezone.now) def add_coment(self): self.date = timezone.now() self.save() def __str__(self): return self.content My model is working now, comments are added, but I need to choose my post (post.id) manually from the default dropdown field witch all … -
how to export data with date and foreign key
Ive managed to export the required data. However, as for date, it gives me a string of number instead of date. Tried to use data_format but does not work. Also, I have a foreign key in the database which is studName. I want to export the student name instead of the id. below is model code: class Namelist(models.Model): name = models.CharField(max_length=100) program = models.CharField(max_length=10) year = models.IntegerField(default=1) studType = models.CharField(max_length=15) courseType = models.CharField(max_length=15) nationality = models.CharField(max_length=20) VMSAcc = models.CharField(max_length=30) classGrp = models.ForeignKey('GroupInfo', on_delete=models.SET_NULL, null=True) def __str__(self): return self.name def get_day(self): return self.day def get_time(self): return self.time class MarkAtt(models.Model): studName = models.ForeignKey(Namelist,on_delete=models.SET_NULL,blank=True, null=True, default=None) classGrp = models.ForeignKey(GroupInfo, on_delete=models.SET_NULL, null=True) currentDate = models.DateField(default=now()) week = models.IntegerField(default=0) attendance = models.IntegerField(default=1) Below is my view code: def export_users_xls(request): response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="attendance.xls"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('attendance') # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True #date_format = xlwt.XFStyle() #date_format.num_format_str = 'dd/mm/yyyy' columns = ['id', 'Student Name', 'Class Group', 'Date','week', 'Attendance' ] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # at 0 row 0 column # Sheet body, remaining rows font_style = xlwt.XFStyle() rows = MarkAtt.objects.all().values_list('id', 'studName', 'classGrp', 'currentDate', 'week', 'attendance') for row,obj in … -
Django fetch records with custom joins
I have three models Employee, User and Address. Suppose Employee and User both have an Address, so in Address model, I added two columns addressable_type and addressable_id. addressable_type contains the name of the model either Employee or User, addressable_id contains the id of the Employee or User. So now I want to order all addresses based on Employee or User name. How can I do this as this is not a direct foreign key association? Please suggest a solution. -
Page url not found in Django
I make this app in django for showing Category in Django. I made the views and the urls app for this feature bat don' t work. I don'know why it don't work, can someone help me please? I have tried a lot of different codes to solve it bat they didn't work. Sorry for my English. Urls.py from django.conf.urls import url from . import views from django.contrib import admin from django.views.generic import ListView, DetailView from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf import settings from django.conf.urls.static import static from django.urls import path urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.index, name='index'), #Index url(r'^all-articles$', views.PostList, name='PostList'), #All Posts url(r'^category$', views.Category, name='Category'), #All CAtegory path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), #Single Posts ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += staticfiles_urlpatterns() Views.py from django.shortcuts import render, get_object_or_404 from django.shortcuts import render from django.http import HttpResponse from .models import * from django.views.generic import View from django.views import generic def index(request): #HomePage return render(request, 'blog/index.php', {}) # Post Section def PostList(request): #Articles List articles = Article.objects.all().order_by('data') return render(request, 'blog/post/PostList.php', {'articles':articles}) class PostDetail(generic.DetailView): #Single Article model = Article template_name = 'blog/post/post_detail.php' def Category(request): #Category List category = Category.objects.all() return render(request, 'blog/post/category.php', {'category':category}) Models.py from django.db import models from django import forms from … -
call task from any django app with celery
i would like to use celery to start a python script from a django api and run the python script periodic simultaneously. This tutorial help me to configure celery in django. Now my project looks like: |- web |- api |- migrations |- __init__.py |- admin.py |- apps.py |- models.py |- serializers.py |- tests.py |- urls.py |- views.py |- project |- __init__.py |- celery.py |- settings.py |- tasks.py |- url.py |- wsgi.py Now you can see i followed the tutorial but how can i call the function in my tasks.py from my api app? -
get_object_or_404 latest = True
I want to retrieve the last object of a matching query. How can I get that? Something like : get_object_or_404(Passwordreset, otp=5) My model has multiple objects with otp 5. Is there something by which I can get the last object which has otp=5? -
Model values saved as object ( <Model_Name object>) in DB rather than simple values
I have a model called Love as class Love(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ans = models.CharField(max_length=1024) and a ModelForm class LoveForm(forms.ModelForm): class Meta: model = Love fields = ('ans',) and my views to display this form and save data in DB is def love_form(request): #user can input as my answers he wants to thats wht multiple times rendering the same template form = LoveForm() if request.method == 'POST': form = LoveForm(request.POST) if form.is_valid(): answer = form.save(commit=False) answer.user = request.user answer.save() return render(request, 'purpose_using_DB/love_form.html', {'form': form, 'message': 'Successfully Saved'}) else: return render(request, 'purpose_using_DB/love_form.html', {'form': form, 'message': 'Error Occured'}) else: return render(request, 'purpose_using_DB/love_form.html', {'form': form}) but the problem is that the Data saved in DB after admin.site.register(Love) is shown as an object rather than the ans values Is this normal? Why it isn't showing the values like ans=something in the admin ? -
How to add automatically generated fields in model?
I need to create model with automatically generated fields, that can be used for filtering. This fields must be added by users in user interface. I've found 2 ways: to create chained model by FK, for example UserExtraFieldModel for User model, or to use JsonField for extra_fields field. But both methods have risks with efficiency. Is there better way to do it? -
facebook-messenger-bot error: When & why this error raised "(#100) Length of param name_placeholder[text] must be less than or equal to 640"
I have a Django application that is connected to Messenger for a Facebook page. When any Facebook user messages to the Facebook page my application try respond automatically after parsing Facebook user's message. If any error occurred during sending message from my Django application I stored the error text in a column of a table. When I tried to analyze the errors generated while sending message I found one error text is as follow "(#100) Length of param name_placeholder[text] must be less than or equal to 640" and I can not regenerate it. There is another similar error "(#100) Length of param message[text] must be less than or equal to 2000" which is very clear and I can regenerate it. I have searched on Google and found nothing that can help me. I just wants to know that when and why the error occur so that I can modify my application to handle it. I have used the following api for sending messages to Facebook user https://graph.facebook.com/v2.6/me/messages?access_token=PAGE_ACCESS_TOKEN with this header parameter {'content-type': 'application/json'} and this data { "messaging_type": "RESPONSE", "recipient": { "id": "receiver_id" }, "message": { "text": "message_text" } } Note: I know Facebook gives error code, type, error_subcode and … -
manage.py is running fine but not showing in the local host
I'm using Django 1.10.0, python 2.7. Can you please tell me Where am I going wrong ? Been stuck with this for weeks. I'm using AWS server to run a chatbot.Ubuntu 16.04.6 LTS When I run "./manage.py run server 0.0.0.0:8000 - The model is being trained and it's running with no error in the terminal. It is running in the terminal :- "Read weights from disk [Parallel(n_jobs=1)]: Done 50 out of 50 | elapsed: 0.2s finished {'multicast_ids': [7269965488589568215], 'canonical_ids': 0, 'success': 0, 'topic_message_id': None, 'results': [{u'error': u'NotRegistered'}], 'failure': 1} System check identified no issues (0 silenced). September 11, 2019 - 09:59:07 Django version 1.10.1, using settings 'exp.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C." My virtual env is activated. and Django is also installed in the virtual environment. My manage.py:- "#!/usr/bin/env python import os import sys print(sys.path) if name == "main": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "exp.settings") try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " … -
How can I utilise the built in first and last name features of the Django User Model?
So I know that Django has a built in system with the User, and it contains things like Username, e-mail, password, and first and last name. I want to know how I can utilise this in my site. So I have a first_name and last_name field in the models.py file, and they are CharFields. I want to know how to connect them to the already existing UserForm that comes with Django. I have tried a few things already, such as doing this with the models.py file. class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.OneToOneField(User, on_delete=models.CASCADE) Here is some code for the form.py file. class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = ('username','email','password','first_name') As you can see from the form, I added the first_name attribute, and in the models.py file, I have the first_name connected with the forms.py one. I am now getting this error. HINT: Add or change a related_name argument to the definition for 'UserProfileInfo.user' or 'UserProfileInfo.first_name'. So I added a related name field to the model, as shown here first_name = models.OneToOneField(User, on_delete=models.CASCADE,related_name='first_name') But, wouldn't you know it, I got yet another error: ValueError: Cannot assign "''": "User.first_name" must be a "UserProfileInfo" instance. … -
How can I specify a ?-based url parameter with django-rest-framework routers
I am working on a very simple school/student API and I want to handle url ?-based filters like /students/?name="Harry" I know how to do it with custom url patterns but I want to use routers (particularly nested routers) and I don't know how to set my urls.py and views.py in order to handle handle this kind of parameter. my urls.py : router = routers.DefaultRouter() router.register(r'schools', SchoolViewSet, basename='school') router.register(r'students', StudentViewSet, basename='student') schools_router = routers.NestedSimpleRouter(router, r'schools', lookup='school') schools_router.register(r'students', StudentViewSet, basename='school-students') urlpatterns = [ url(r'^', include(router.urls)), url(r'^', include(schools_router.urls)), ]