Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django DataError in /register/ 'interger out of range'
i'm trying to make a custom registration system with django, but when i submit my registeration form, i get a DataError at /register/, 'integer out of range'. What could be the problem Django says the error is from this file "forms.py" P.S; im using postgres database my code: from django import forms from django.conf import settings from .models import recordBuddyUser from django.views.generic import CreateView from django.core.exceptions import ValidationError # from django.contrib.auth.forms import UserCreationForm class RegisterForm(forms.ModelForm): companyname = forms.CharField(widget=forms.TextInput( attrs={ 'type': 'text', 'name': 'company-nam', 'placeholder': 'company Name', 'id': 'exampleInputcompanyName', 'class': 'form-control rounded-pill btn-user p-4 form-control-user' } ) ) companyadministrator = forms.CharField(widget=forms.TextInput( attrs={ 'type': 'text', 'name': 'administrator', 'id': 'exampleAdminName', 'placeholder': 'company Admin', 'class': 'form-control rounded-pill btn-user p-4 form-control-user' } ) ) companyphone = forms.IntegerField(widget=forms.NumberInput( attrs={ 'maxlenght': '15', 'type': 'number', 'name': 'companyphonenumber', 'placeholder': 'company Phone', 'id': 'examplecompanyPhoneNumber', 'class': 'form-control rounded-pill btn-user p-4 form-control-user' } ) ) companyemail = forms.CharField(widget=forms.EmailInput( attrs={ 'type': 'email', 'name': 'company-email', 'id': 'exampleInputEmail', 'placeholder': 'Email Address', 'class': 'form-control rounded-pill btn-user p-4 form-control-user' } ) ) companypassword = forms.CharField(widget=forms.PasswordInput( attrs={ 'type': 'password', 'name': 'password', 'placeholder': 'Password', 'id': 'exampleInputPassword', 'class': 'form-control rounded-pill btn-user p-4 form-control-user' } ) ) companypasswordconfirm = forms.CharField(widget=forms.PasswordInput( attrs={ 'type': 'password', 'name': 'confirm-password', 'id': 'exampleRepeatPassword', 'placeholder': 'Repeat Password', 'class': … -
I want to see the tables at terminal by using visual studio code(Window)
[click this line, here is the screenshot][I want you let to see tables that was automatically created on terminal. what code should I write? ( I'm using Django, and my OS is window.)] -
SynchronousOnlyOperation Error in with django 3 and django channels
I had a django 2 app and i used django channels for socket connection. i just update django to version 3. and now daphne show this error when i try to make a socket connection. i had not any problem with django 2. [Failure instance: Traceback: <class 'django.core.exceptions.SynchronousOnlyOperation'>: You cannot call this from an async context - use a thread or sync_to_async. /home/ubuntu/pl_env/lib/python3.6/site-packages/autobahn/websocket/protocol.py:2844:processHandshake /home/ubuntu/pl_env/lib/python3.6/site-packages/txaio/tx.py:429:as_future /home/ubuntu/pl_env/lib/python3.6/site-packages/twisted/internet/defer.py:151:maybeDeferred /home/ubuntu/pl_env/lib/python3.6/site-packages/daphne/ws_protocol.py:83:onConnect --- <exception caught here> --- /home/ubuntu/pl_env/lib/python3.6/site-packages/twisted/internet/defer.py:151:maybeDeferred /home/ubuntu/pl_env/lib/python3.6/site-packages/daphne/server.py:201:create_application /home/ubuntu/pl_env/lib/python3.6/site-packages/channels/routing.py:54:__call__ /home/ubuntu/pl_env/lib/python3.6/site-packages/channels/security/websocket.py:37:__call__ /home/ubuntu/petroline_django/orders/token_auth.py:25:__call__ /home/ubuntu/pl_env/lib/python3.6/site-packages/django/db/models/manager.py:82:manager_method /home/ubuntu/pl_env/lib/python3.6/site-packages/django/db/models/query.py:411:get /home/ubuntu/pl_env/lib/python3.6/site-packages/django/db/models/query.py:258:__len__ /home/ubuntu/pl_env/lib/python3.6/site-packages/django/db/models/query.py:1261:_fetch_all /home/ubuntu/pl_env/lib/python3.6/site-packages/django/db/models/query.py:57:__iter__ /home/ubuntu/pl_env/lib/python3.6/site-packages/django/db/models/sql/compiler.py:1142:execute_sql /home/ubuntu/pl_env/lib/python3.6/site-packages/django/utils/asyncio.py:24:inner it says the problem is in token_auth.py, line 25. this line is token = Token.objects.get(key=token_key) this is my token_auth.py that handles token authentication. from channels.auth import AuthMiddlewareStack from django.contrib.auth.models import AnonymousUser from django.db import close_old_connections from rest_framework.authtoken.models import Token class TokenAuthMiddleware: """ Token authorization middleware for Django Channels 2 see: https://channels.readthedocs.io/en/latest/topics/authentication.html#custom-authentication """ def __init__(self, inner): self.inner = inner def __call__(self, scope): headers = dict(scope['headers']) if b'authorization' in headers: try: token_name, token_key = headers[b'authorization'].decode().split() if token_name == 'Token': # Close old database connections to prevent usage of timed out connections close_old_connections() token = Token.objects.get(key=token_key) scope['user'] = token.user except Token.DoesNotExist: scope['user'] = AnonymousUser() return self.inner(scope) TokenAuthMiddlewareStack = lambda inner: TokenAuthMiddleware(AuthMiddlewareStack(inner)) -
Unable to render Django app with Jelastic
I want to render my Django with jelatic. I cloned my Django app on jelastic. I configured my Postgres database and modified my settings.py so that my app is connecting to my database. Finally to render my app I run this in the SSH : python manage.py runserver And everything seems to work : But I get this response on my browser: Any help will be appreciated =) -
Related Field got invalid lookup: blog_posts_name
I am trying to add author to the search_field but it's throwing the error-Related Field got invalid lookup: icontains models.py class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250,unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE,related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') class Meta: ordering = ('-publish',) def __str__(self): return self.title admin.py @admin.register(Post) class PostAdmin(admin.ModelAdmin): list_display = ('title', 'slug', 'author', 'publish', 'status') list_filter = ('status', 'created', 'publish', 'author') search_fields = ('title', 'body','status','author__blog_posts_name') prepopulated_fields = {'slug': ('title',)} raw_id_fields = ('author',) date_hierarchy = 'publish' ordering = ('status', 'publish') I have tried search_fields =('author','foreinkeyfield__author','author__name','author__User_name',) as per suggested by the users in the previously answered questions but none of them seems to be working. -
How to import django data from windows on ubuntu correctly?
I am moving the django page from the windows server to the ubuntu server. I get a utf8 error while executing the python manage.py loaddata command. Unfortunately, I don't know why. Below I send the message I receive. 'utf8' codec can't decode byte 0xff in position 0: invalid start byte I will add that the site uses the MySQL database. -
Full media absolute paths with graphene-django
I'm currently switching from using DRF to django-graphene while using boto3 and s3 for media content. When using DRF, the file field would come back with the full path for the media inside of the s3 bucket. However, graphene-django file fields are only returning relative paths. For instance with DRF a file field would come back with it's full url like: https://bucket.s3.amazonaws.com/logos/logos_2019-11-07_172356.1808000000.png But with graphene-django it's coming back as: /logos/logos_2019-11-07_172356.1808000000.png Is there a middle where that needs to be added? Or do I need to create my own scaler to deal with this? I'm very new to graphene-django and graphql in general. So any help is very much appreciated. -
Django Nested Admin validation of nested inlines from parent forms
What I'm trying to do is assert the start_date of the child form is after the start_date of the parent form. For example, if I have the following models: class Parent(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) starts_at = models.DateTimeField(blank=True, null=True) class Child(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) parent = models.ForeignKey(Parent, on_delete=models.CASCADE, related_name='children') starts_at = models.DateTimeField(null=True, blank=True) And admin forms setup like: class ChildInline(nested_admin.NestedTabularInline): model = models.Child extra = 0 @admin.register(models.Parent) class ParentAdmin(nested_admin.NestedModelAdmin): inlines = [ChildInline] How would I validate the child based on the parent (or vice-versa)? So far I've explored: Form.clean() - but this doesn't include the child/parent instances. Formset.clean() - but despite making formsets it appears that django-nested-admin ignores them and their clean methods are never used. Has anyone found a solution for this kind of issue? -
Display Database image in django
My database images get deleted from Heroku but the logo is not deleted. I use static to display the logo in this way => <img src="{% static 'img/techshelta_logo.png' %}"> but my database images are displayed without using static => <img src="{{ object.image.url }}" class="img-fluid" alt="object.title">. Is that the reason why Heroku deletes them? NOTE When I try to use static as in the example below to display the DB images locally they are not show <img src="{% static 'object.image.url' %}" class="img-fluid" alt="object.title" > Kindly help me resolve this problem. Thank you -
Using Django BooleanField to screen filter and screen job applicants
I am working on a job portal where applicants can apply for a role and I can easily screen them based on the fields they filled and the information they give. I have three models Job, Apply, Screen. The screen model contain Boolean fields which when ticked should be able to screen/filter and bring out qualified applicants. models.py class Job(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) years_of_experience = models.IntegerField(blank=True, null=True) ...... class Apply(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) job = models.ForeignKey(Job, on_delete=models.CASCADE, related_name='applicants') experience = models.IntegerField(blank=True, null=True) cv = models.FileField(upload_to=user_directory_path) certification = models.FileField(upload_to=user_directory_path, blank=True) class ScreenApplicant(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) job = models.ForeignKey(Job, on_delete=models.CASCADE) applicants = models.ForeignKey(Applicants, on_delete=models.CASCADE, related_name='screen_applicant') screen_experience = models.IntegerField(blank=True, null=True) screen_cv = models.BooleanField(default=False) screen_certification = models.BooleanField(default=False) forms.py class ApplyJobForm(forms.ModelForm): class Meta: model = Applicants fields = ('job', 'experience', 'degree', 'cv', 'certification', 'start_date', 'end_date') class ScreenApplicantForm(forms.ModelForm): class Meta: model = ScreenApplicant fields = ('job', 'applicants', 'screen_experience', 'screen_cv', 'screen_certification') From this I want to be able to compare the ApplyJob fields and ScreenApplicant fields and then check if screen field is True(marked), use those field to screen/filter the candidate to qualified.html I tried using something similar to this Filtering with multi field in django orm But I am not … -
Change form output from Django Template
I have a form: class InspectionReportForm(forms.ModelForm): class Meta: model = InspectionReport fields = ('Date', 'Comment', 'Signature') labels = {"Date": "Date (YYYY-MM-DD)"} def __init__(self, *args, **kwargs): super(InspectionReportForm, self).__init__(*args, **kwargs) self.fields["Comment"].widget = forms.HiddenInput() self.fields["Date"].widget = forms.HiddenInput() self.fields["Signature"].widget = forms.HiddenInput() Which stores a report, in addition to the date and who wrote it. In the case of a generic "Pass" or "Fail" report. I want a generic comment in the report, so this would be auto-filled, which is why I have hidden this field. Date and Signature will be taken from the date of submission and the signature will be the logged in user. So mostly all auto-filled. However I have a "maybe" option which prompts the user for a comment and submits that instead of the generic ones. My question is how do I change the comment value of the form from the HTML Template/Javascript stage of my project? My current code is as follows: <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <center><button type="button" id="pass">Pass</button> <button type="button" id="fail">Fail</button> <button type="button" id="check" class="collapsible">Check</button> <div class="content"> Comment: <input type="text" name ="comments"> <button id="submitCheck">Submit</button> </div> </center> The Check button is just a collapsible container that has an input box and a submit button … -
How to reliably run custom code when related (ForeignKey) objects change
In a simple ForeignKey relation, I want to run specific code when one of the related object is modified. Here a schematic code : class Car(models.Model): pass class Wheel(models.Model): car = models.ForeignKey('Car', on_delete=models.CASCADE, related_name='wheels', null=True) def save(self, *args, **kwargs): super().save(*args, **kwargs) my_custom_code() According to django's documentation, the reverse related manager method .add perform the save in database using update() instead of save() by default. (idem for .remove, etc...) So in the below code, the my_custom_code isn't called when using .add: car = Car.objects.create() wheel = Wheel.objects.create() # ok my_custom_code called here car.wheels.add(wheel) # not called here because django use "update mechanism" which do not use save method We need to indicate bulk=False to add method in order to force using save method. car.wheels.add(wheel, bulk=False) # ok my_custom_code called here This is a problem for me as it is important that the my_custom_code is called when any of the related objects is modified. If someone forgot to indicate bulk=False, it will generate inconsistent data. There is a signal for this case ? (like m2m_changed signal) There is a way to force bulk=False for all methods of a ForeignKey relation ? Thanks for your help. Why I need this ? My X … -
Correct implementation of UserPassesTestMixin or AccessMixin in class based view
When using class-based views, you can use the UserPassesTestMixin in the following way (docs): from django.contrib.auth.mixins import UserPassesTestMixin class MyView(UserPassesTestMixin, View): def test_func(self): return self.request.user.email.endswith('@example.com') The docs also state: Furthermore, you can set any of the parameters of AccessMixin to customize the handling of unauthorized users However, no example of the syntax is provided as to how to do this. For example, how would I set raise_exception and permission_denied_message so authenticated users get an exception error and not a 403? This does not work, as users are still returned a 403 error: class MyView(UserPassesTestMixin, View): raise_exception = True permission_denied_message = 'You have been denied' def test_func(self): return self.request.user.email.endswith('@example.com') -
Reverse for 'results' with arguments '('',)' not found. 1 pattern(s) tried: ['polls/(?P<question_id>[0-9]+)/results/$']
I just got to the generic views section of the Django tutorial on their website, but I'm stuck at this part and keep getting this error. This question has been answeared before, but for an older version of the tutorial and Django. I was hoping someone here could help me. Here is the code: urls.py app_name = 'polls' urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name = 'vote'), ] views.py def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = { 'latest_question_list' : latest_question_list, } return render(request, 'polls/index.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question' : question}) def results(request, question_id): question = get_object_or_404(Question, pk = question_id) return render(request, 'polls/results.html', {'question_id' : question_id}) def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) detail.html <h1>{{ question.question_text }} </h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p> {% endif %} <form action="{% url 'polls:vote' question.id %}" method ="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name = "choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" > <label … -
Django Nested ManyToManyField objects count query
we have Project as main model, which contains 2 fields of M2M relationship. class First(models.Model): first_results_M2M = models.ManyToManyField(First_Results) class Second(models.Model): second_results_M2M = models.ManyToManyField(Second_Results) class Project(models.Model): project_first_M2M = models.ManyToManyField(First) project_second_M2M = models.ManyToManyField(Second) I m trying to count all the objects present in first_results_M2M of all the project_first_M2M objects within each Project object. Here's the below example to count all the objects of first_results_M2M for Project object 1. total_first_all = First_Results.objects.filter(first__project__id=1).count() I want to render the total count of total_first_all and total_second_all in the template. Project_Query = Project.objects.all() for each_proj in Project_Query: print(each_proj.total_first_all) ## should print the count the `first_resuls_M2M` for each project obj. Please let me know how to do achieve it in more effecient/fast way. -
selenium.common.exceptions.WebDriverException: Message: Reached error page: about:neterror?
I'm using bok_choy which uses Selenium in order to write acceptance tests. The tests are working fine with chromedriver/geckodriver on a local machine but it doesn't work with Selenium Images inside docker container. Gives the following error: ====================================================================== ERROR: test_result_page (__main__.TestPolls) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/bok_choy/page_object.py", line 329, in visit self.browser.get(self.url) File "/usr/local/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 333, in get self.execute(Command.GET, {'url': url}) File "/usr/local/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute self.error_handler.check_response(response) File "/usr/local/lib/python3.8/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: Reached error page: about:neterror?e=nssFailure2&u=https%3A//demo.app%3A8000/polls/&c=UTF-8&f=regular&d=%20 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "app/tests/test_polls.py", line 35, in test_result_page self.polls_index_page.visit().click_question('question1') File "/usr/local/lib/python3.8/site-packages/bok_choy/page_object.py", line 332, in visit raise PageLoadError(u"Could not load page '{!r}' at URL '{}'".format( bok_choy.page_object.PageLoadError: Message: Could not load page '<pages.PollsIndexPage object at 0x7f19190eed00>' at URL 'http://demo.app:8000/polls/' ====================================================================== ERROR: test_vote_again (__main__.TestPolls) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/bok_choy/page_object.py", line 329, in visit self.browser.get(self.url) File "/usr/local/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 333, in get self.execute(Command.GET, {'url': url}) File "/usr/local/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute self.error_handler.check_response(response) File "/usr/local/lib/python3.8/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: Reached error page: about:neterror?e=nssFailure2&u=https%3A//demo.app%3A8000/polls/&c=UTF-8&f=regular&d=%20 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "app/tests/test_polls.py", … -
Why are django INFO logs being silenced on the server?
When I run my app locally, the INFO logs are sent to stack driver and the logfile just fine. But when I deploy the same to my remote server only WARN and above logs are being printed. It is not a GCP authentication issue since WARN and ERROR logs are received. My settings.py looks like: # StackDriver setup from google.cloud import logging as gc_logging gc_logging_client = gc_logging.Client() LOGGING = { 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(filename)s %(lineno)d %(message)s' }, 'w_hostname': { 'format': '%(message)s - {} %(filename)s %(lineno)d'.format(HOST_NAME) }, }, 'handlers': { 'log_file': { 'level': 'INFO', 'class': 'logging.handlers.RotatingFileHandler', 'filename': 'apnaTimeBackend/django.log', 'maxBytes': 16777216, # 16megabytes 'formatter': 'verbose', }, 'stackdriver': { 'class': 'google.cloud.logging.handlers.CloudLoggingHandler', 'client': gc_logging_client, 'level': 'INFO', 'formatter': 'w_hostname', } }, 'loggers': { 'django': { 'handlers': ['stackdriver', 'log_file'], 'level': 'DEBUG', 'propagate': True, 'name': ENV }, }, 'version': 1, 'disable_existing_loggers': False, } -
Accessing django-rest-swagger folder in heroku
I deployed an API on Heroku and I configured the UI with django-rest-swagger. On deploying, the "TemplateSyntaxError at /admin 'staticfiles' is not a registered tag library." showed up when I try to open up my domain on heroku. How can I access the django-rest-swagger in production so as to change the 'staticfiles' to 'static' in 'index.html' file? -
How to display json results in Django?
I am trying to display the results from my get request with the Privacy API but I'm not sure what I'm doing wrong. This API call works perfectly fine, so how would I display this on a webpage through Django? def privacy_api(): import requests url = 'https://api.privacy.com/v1/card' headers = {'Authorization':'api-key MYKEY'} r = requests.get(url, headers=headers) print(f"Status code: {r.status_code}") response_dict = r.json() repo_dicts = response_dict['data'] repo_dict = repo_dicts[0] print(repo_dicts) for repo_dict in repo_dicts: print(f"Last Four: {repo_dict['last_four']}") privacy_api() views.py from .models import Drop from .forms import DropForm, EntryForm import requests def index(request): return render(request, 'phrxns/index.html') def drops(request): drops = Drop.objects.all() context = {'drops': drops} return render(request, 'phrxns/drops.html', context) def drop(request, drop_id): drop = drop.objects.get(id=drop_id) entries = drop.entry_set.order_by('date_added') context = {'drop': drop, 'entries': entries} return render(request, 'phrxns/drop.html', context) def priv(request): response = requests.get('https://api.privacy.com/v1/card/.json', headers = 'Authorization:api-key MYKEY') geodata = response.json() return render(request, 'phrxns/index.html', { 'last': geodata['data'] }) index.html {% extends "phrxns/base.html" %} {% block page_header %} <div class="jumbotron"> <h1 class="display-3">Phrxn</h1> <p class="lead">Receive buying power.</p> <a class="btn btn-lg btn-primary" href="{% url 'users:register' %}" role="button">Enter &raquo;</a> </div> {% endblock page_header %} {% block content %} <h2>PRIVACY CARD</h2> <p>Your card number is {{ last }} </p> {% endblock %} This is what is displayed on my … -
Getting bytes when using axios
I'm sending post-request from front using axios var data = { key1: value1, }; axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"; axios({ method: 'post', url: 'my_url', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json; charset=utf-8' }, data: JSON.stringify(data), }).then(function (response) { console.log(response); }); But on django-backend I got bytes object b'{"key1":"value1"}' Is there a way got get json object on backend? Or I need to decode the request? -
Serve django static files from s3, without allowing server to write to s3
I am trying to server django statics from s3. I've googled it, and all of the solutions involve django-storages and boto3 libraries, allowing djangos collectstatic function to upload the statics to s3, and then serve them. Instead, I would like to upload statics separately (manually), and just allow django to point to them. What is the minimum configuration to do this? -
How to programmatically upload local file as Django model field?
I'm having troubles trying to upload files to FileField from local path. I have correctly configurred CDN backend in S3 bucket and use it as PrivateMediaStorage for one of my model fields: class MyModel(models.Model): some_file = models.FileField(storage=PrivateMediaStorage()) ... With this very simple configuration whenever I'm creating/updating model through django-admin it is saved and file attached as some_file is correctly uploaded to S3 bucket. Yet if I try to create/update model instance programmatically, say through custom manage.py command, model instance itself is created but attachment is never uploaded to CDN. Here's simplified version of code I'm using to upload files: class Command(BaseCommand): help = 'Creates dummy instance for quicker configuration' def handle(self, *args, **options): some_file = os.path.join(os.path.dirname(__file__), '../../../temporary/some_image.png') if not os.path.exists(some_file): raise CommandError(f'File {some_file} does not exist') else: instance, created = MyModel.objects.get_or_create(some_file=some_file) What is missing in my implementation and what needs to be adjusted to allow file uploads from local storage? -
How to access the ajax response of the datatable outside the datatable in django?
In my django app the datatable makes a ajax REST api request where the response is as follows: { "data": ["some content here"], "time_data": [ { "Last_updated": "Jan 07 2020 06: 09 CST", "Next_scheduled": "Jan 07 2020 07: 09 CST" } ] } In the above json the data key has been accessed and used to populate the datatable and it works fine. But the next key i.e, time_data needs to be used in a div which is outside the datatable. How can i access the contents of time_data in javascript? -
.save() does not change the value of a field , django
I am trying to implement a notification system. When the user clicks onto one of the notification from the drop down box , i will use a AJAX Post request to modify the boolean field to indicate that that particular instance of the Notification has been read before. here is my code: This is my HTML template: <ul class="dropdown-menu dropdown-menu-right myDropDown"> {%for noti in notifications%} {{noti}} <li> <a href="#" class="top-text-block" id="{{noti.id}}" onClick="return booleanchanger(this.id);"> <div class="top-text-heading">{{noti.object_type}}</div> <p class = 'text-muted'><small>{{noti.time}}</small>></p> <div class="top-text-light">{{noti.message}}</div> </a> </li> {%endfor%} </ul> This is my ajax call : function booleanchanger(clicked_id){ var a = clicked_id $.ajax({ url : "{% url 'read-notification' %}", type : "POST", data : { 'csrfmiddlewaretoken' : "{{ csrf_token }}", 'pk' : a }, success : function(result) { } }); This is my notifications model: class Notifications(models.Model): time = models.DateTimeField(auto_now=True) target = models.ForeignKey(User , on_delete=models.CASCADE) message = models.TextField() object_type = models.CharField(max_length=100) object_url = models.CharField(max_length=500,default = 'test') is_read = models.BooleanField(default=False) This is my view that handles the ajax request: def ReadNotificationView(request): if request.method=='POST' and request.is_ajax(): pk = request.POST.get('pk',False) obj = Notifications.objects.get(pk=pk) obj.if_read = True obj.save() print(obj.if_read) return JsonResponse({'status':'Success', 'is_read': 'changed'}) else: return JsonResponse({'status':'Fail', 'is_read':'not changed'}) this is the url.py: path('notification/update/' , views.ReadNotificationView , name = 'read-notification') … -
How to test edit function on django? (error django.db.utils.IntegrityError: NOT NULL constraint failed)
i try to write code for editing records and its unit test. here is my code: test_view.py def test_edit_address(self): address1 = Address.objects.create(first_name='Edith', last_name='Star', address='Some City', phone_number='123455') response = self.client.post( reverse('edit', kwargs={'address_id': address1.id}), {'first_name': 'Patrick', 'last_name': 'Stars', 'address': 'Other City', 'phone_number': '0123455'}) self.assertEqual(response.status_code, 302) address1.refresh_from_db() self.assertEqual(address1.first_name, 'Patrick') models.py from django.db import models class Address(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) address = models.TextField() phone_number = models.CharField(max_length=200) urls.py from django.urls import path from addressbooksapp import views urlpatterns = [ path('', views.home_page, name='home'), path('delete/<address_id>',views.delete, name='delete'), path('edit/<address_id>',views.edit, name='edit'), ] But when run the test i got error "django.db.utils.IntegrityError: NOT NULL constraint failed: addressbooksapp_address.first_name"