Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to fix Improperly Configured exception?
i have a django project called mysite, it has 2 apps (projects, blog) i have not added any urls in my blog.urls yet this is my settings.py INSTALLED_APPS = [ 'projects.apps.ProjectsConfig', 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] this is my project.urls from . import views urlpatterns = [ path("", views.project_index, name="project_index"), path("<int:pk>/", views.project_detail, name="project_detail"), ] i got this error raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'blog.urls' from 'D:\\firstwebapp\\mysite\\blog\\urls.py'>' does not appear to have any patterns in it. If you s ee valid patterns in the file then the issue is probably caused by a circular import. -
How can I put the PasswordChangeView class into a function?
How can I put the PasswordChangeView class into a function? I know there is a PasswordChangeForm form, but it always fails to be validated. -
How to print django model data with template forloop?
Here I have template for tags, and i want print them all by forloop but with the tag id. e.g: {% for tag in tags %} <div class="row"> <div class="col-md-3 col-sm-6 col-xs-12"> <div class="photo-rounded-fluffs"> <a href="#"> <img class="img-responsive" src="{% static 'assets/img/fluffs/1.jpg'%}" alt="Image"> <h1 class="text-center">{{tag.title}}</h1>#Here i want print tag with tag id 1 </a> </div> </div> <div class="col-md-3 col-sm-6 col-xs-12"> <div class="photo-rounded-fluffs"> <a href="#"> <img class="img-responsive" src="{% static 'assets/img/fluffs/2.jpg'%}" alt="Image"> <h1 class="text-center">{{tag.title}}</h1> #here i want to print tag with id 2 </a> </div> </div> </div> {% endfor%} Right now the both tag title are same because same tag is repeating twice. How can I handle this behavior in forloop in templates.. If more information is required than tell me will update my question with that information. -
Django - allauth: How to remove allauth login and signup urls
I am trying to use Django-allauth for some password resetting functionalities, however, I am trying to disable login/signup with django-allauth. So far I have not been able to find a way to either redirect users to my custom signup and login or completely disable those URLs. I was wondering if there is a workaround on how I can remove those URLs? My current approach was to add all the URLs manually without those, but that is causing an error with my social-login links. Currently, I have added the following to my URLs: url(r"^accounts/logout/$", allauth_views.logout, name="account_logout"), url(r"^accounts/password/change/$", allauth_views.password_change,name="account_change_password"), url(r"^accounts/password/set/$", allauth_views.password_set, name="account_set_password"), url(r"^accounts/inactive/$", allauth_views.account_inactive, name="account_inactive"), # E-mail url(r"^accounts/email/$", allauth_views.email, name="account_email"), url(r"^accounts/confirm-email/$", allauth_views.email_verification_sent,name="account_email_verification_sent"), url(r"^accounts/confirm-email/(?P<key>[-:\w]+)/$", allauth_views.confirm_email,name="account_confirm_email"), # password reset url(r"^accounts/password/reset/$", allauth_views.password_reset,name="account_reset_password"), url(r"^accounts/password/reset/done/$", allauth_views.password_reset_done,name="account_reset_password_done"), url(r"^accounts/password/reset/key/(?P<uidb36>[0-9A-Za-z]+)-(?P<key>.+)/$",allauth_views.password_reset_from_key,name="account_reset_password_from_key"), url(r"^accounts/password/reset/key/done/$", allauth_views.password_reset_from_key_done,name="account_reset_password_from_key_done"), # social account path('socialaccount/login/cancelled/', allauth_socialviews.login_cancelled,name='socialaccount_login_cancelled'), path('socialaccount/login/error/', allauth_socialviews.login_error,name='socialaccount_login_error'), path('socialaccount/signup/', allauth_socialviews.signup, name='socialaccount_signup'), path('socialaccount/connections/', allauth_socialviews.connections, name='socialaccount_connections'), However, since I have a Google social login I get an error: Reverse for 'google_login' not found. 'google_login' is not a valid view function or pattern name How can I implement this without causing any errors? -
Cant get objects while testing Django 1.8.4
I have a test class, extending TestCase. I have a setUp() method in it, in which I do some preparations for tests in this suite: I create objects in db (using .objects.create(), so its pretty similar to what we have in Django docs). I create an instance of Client, so that I can perform some .post() and .get() requests. So, I perform a request on address specified in urlpatterns. In this endpoint to which I perform request, underneath the hood some query takes place. And the problem is IT CANNOT FIND THE OBJECTS CREATED IN setUp() In debugger, I see that endpoint is resolved correctly, request comes as it should, but when objects.get() or objects.filter() is called (with proper arguments), it cannot find the entry in testing db. -
IMPORTING CSV DATAS INTO MODEL - DJANGO
I'm implementing a list of clients. I want to give to the user the possibility of importing new clients thought a csv file. The client model has these fields: Client, name, surname, email, phone So I created this model: class CsvClient(models.Model): file_name = models.FileField(upload_to='csv-cliente') uploaded = models.DateTimeField(auto_now_add=True) activated = models.BooleanField(default=False) def __str__(self): return f"File id: {self.id}" and this function in views.py: import csv def importa_csv_clienti(request): form = CVSForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() form = CVSForm() clients = CsvClient.objects.get(activated=False) with open(clienti.file_name.path, 'r') as f: reader = csv.reader(f) for i, row in enumerate(reader): if i==0: pass else: row = "".join(row) row = row(";", " ") row = row.split(" ") client = row[0].capitalize() name = row[1].capitalize() surname = row[2].capitalize() value = Cliente.objects.create( cliente=cliente, nome=nome, cognome=cognome, email=riga[3], telefono=riga[4], ) print('oggetto creato:', value.cliente, value.nome, value.cognome, value.email, value.telefono) clients.activated = True clients.save() context = {'form': form} template = 'importa.html' return render(request, template, context) It works, expect for the fact that if in the csv file I have the row: Nutella Antonio Dello Iudice where nutella is client Antonio is name Dello Iodice is surname and email and phone are blank basically it interprets it as if Dello is the surname and Iudice … -
How to combine two queryset and order them
I have two queryset for two different models. I combined them with chain and ordered them by date. When I want to reverse the order I'm getting an error. Here is my code: def get_queryset(self): query = self.request.GET.get('search') if query: likes = FilmLike.objects.filter(film__title__icontains=query).exclude(users=None) dislikes = FilmDisLike.objects.filter(film__title__icontains=query).exclude(users=None) object_list = sorted(chain(likes, dislikes),key=lambda instance: instance.created_at) else: likes = FilmLike.objects.filter().exclude(users=None) dislikes = FilmDisLike.objects.filter().exclude(users=None) object_list = list(likes) + list(dislikes) object_list = sorted(chain(likes, dislikes),key=lambda instance: instance.created_at) return object_list This code is working but when I change the "instance.created_at" to "-instance.created_at" I'm getting this error: bad operand type for unary -: 'datetime.datetime' -
Django, struggling to make a form
i have a bit of a long question: i really tried and search but i seem to miss a part of the tutorial i watched: i want to make a simple website that allows a user to enter a serial number, and then it redirects the user to a page with a question and a bunch of answers(as buttons perhaps) after a few questions the site will give a page that compares the entered results and the entered serial number with the pre-determined(entered via admin) values and shows a page accordingly. i cant seem to make any progress other than take the serial number and display the number if its on the database... thank you for reading i hope you can help me out. -
Django Internationalization integrating html with js
I'm trying to change the page layout when language redirect form is submitted but it doesn't seem to work this is django's set_language redirect view {% load i18n %} <form action="{% url 'set_language' %}" method="post">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <select name="language"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected{% endif %}> {{ language.name_local }} ({{ language.code }}) </option> {% endfor %} </select> <input type="submit" value="Go"> </form> and this is how i want it to work <form id="myform" action="{% url 'set_language' %}" method="post"> {% csrf_token %} <input type="hidden" name="next" value="{{ redirect_to}}"> <select name="language" id=""> {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <option value="{{ language.code }}" {% if language.code == LANGUAGE_CODE %} selected {% endif %}> {{ language.name_local }} </option> {% endfor %} </select> {% if language.code == "ar" %} <input type="submit" onclick='changeDirection("rtl")' value="GO"> {% endif %} {% if language.code == "en" %} <input type="submit" onclick='changeDirection("ltr")' value="GO"> {% endif %} changeDirection function is working perfectly but i'm trying to integrate it with … -
Registering multiple admin classes with a model in Django admin
I've two Admin classes for a single model: from django.contrib import admin from django_summernote.admin import SummernoteModelAdmin from .models import * class ProductSummernoteAdmin(SummernoteModelAdmin): summernote_fields = ('description',) class ProductAdmin(admin.ModelAdmin): ... admin.site.register(Product, ProductSummernoteAdmin) I want to register both ProductSummernoteAdmin and ProductAdmin with Product model. How to do that? As, i can't register same model twice. -
How to search for the mode of a field in a one to many relationship in django's ORM?
I have this one to Many relationship between dish and restaurant. SPICINESS_CHOICES = ( ("M", "Mild") ("H", "Hot") ("SH", "Super hot") ) class Restaurant(Model): name = models.CharField(max_length=50) class Dish(Model): restaurant = models.ForeignKey(Restaurent) name = models.CharFiedl(null=True, max_length=50) price = models.IntegerField(max_length=10, null= False) spicy = models.CharField(null= True, choices=SPICINESS_CHOICES) I would like to be able to search Restaurants for the most occurring spiciness of their dishes or the mode of the spiciness of their dishes https://en.wikipedia.org/wiki/Mode_(statistics). Django does not seem to have functionality to implement this easily. So let's say we have three restaurants, Anny's, Domino and Verspucie. Anny's has different 8 dishes of which 2 dishes are labeled as being Hot, all other dishes are labeled as Mild, since the owner wants to be able to have a varied menu for children Domino has 9 different dishes of which 5 dishes are labeled as being Hot, 2 as being Super Hot and 2 as being mild. Verspucie has 10 different dishes of which 8 are labeled as being Super Hot, one 1 labeled as Mild and 1 is labeled as Hot. Because I want to find the correct restaurant from a whole list of restaurants, I would like to be able to … -
python manage.py runserver not working pls solve
Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/devyanisharma/.local/share/virtualenvs/todoapp-ydZfewgi/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Users/devyanisharma/.local/share/virtualenvs/todoapp-ydZfewgi/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/Users/devyanisharma/.local/share/virtualenvs/todoapp-ydZfewgi/lib/python3.8/site-packages/django/core/management/base.py", line 442, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (corsheaders.E013) Origin '/' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin '0' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin '0' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin '0' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin '3' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin ':' in CORS_ORIGIN_WHITELIST is missing scheme or netloc HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). ?: (corsheaders.E013) Origin 'a' in CORS_ORIGIN_WHITELIST is missing scheme or … -
Django | The id of the records of more than 1000 have a period
when I use the id of an object that is greater than 1000 on my django template I get a period. For example: {{item.id}} should be 1200 but the ouput is 1.200 How can I solve this? -
How to use aws boto library to test Django website?
I want to test my Django application before deploying using django.test module. Since I'm using DynamoDB for storing my data and all the URL endpoints are programmed using boto3 library to GET and POST data at DynamoDB. How can I test my Django views/url endpoints using boto3? Please comment for any extra information. Thank you!! -
Django - How can test models.ManyToManyField spanning multiple databases?
Now I have to integrate a set of apps spanning multiple databases. One database is 'default' which I can do migrations freely and many models are routed to it. Another is, for example, 'another_db' to which only Author model is routed, and I have no rights to change. I ran into a problem when I tested like: # one_app/tests.py ... class AuthorTest(TestCase): databases = '__all__' multi_db = True @classmethod def setUpTestData(cls): super().setUpTestData() cls.post_1 = Post(title="post_1_title") cls.post_1.save() cls.author_1 = Author(name="author_1_title") cls.author_1.save() def test_can_add(self): self.assertEqual(self.post_1.authors.count(), 0) self.post_1.authors.add(self.author_1) self.assertEqual(self.post_1.authors.count(), 1) # Here, the test fails. Test message shows: Creating test database for alias 'default'... Creating test database for alias 'another_db'... System check identified no issues (0 silenced). FE ====================================================================== ERROR: test_can_add (one_app.tests.AuthorTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/hiroyuki/PycharmProjects/some_app/venv/lib/python3.6/site-packages/django/test/testcases.py", line 274, in __call__ self._post_teardown() File "/Users/hiroyuki/PycharmProjects/some_app/venv/lib/python3.6/site-packages/django/test/testcases.py", line 1009, in _post_teardown self._fixture_teardown() File "/Users/hiroyuki/PycharmProjects/some_app/venv/lib/python3.6/site-packages/django/test/testcases.py", line 1177, in _fixture_teardown connections[db_name].check_constraints() File "/Users/hiroyuki/PycharmProjects/some_app/venv/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 331, in check_constraints bad_value, referenced_table_name, referenced_column_name django.db.utils.IntegrityError: The row in table 'one_app_post_authors' with primary key '1' has an invalid foreign key: one_app_post_authors.author_id contains a value '1' that does not have a corresponding value in another_app_author.id. ====================================================================== FAIL: test_can_add (one_app.tests.AuthorTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/hiroyuki/PycharmProjects/some_app/one_app/tests.py", line 23, in test_can_add … -
Django admin panel has a weird look after upgrade
Right after upgrade to Django 3.1.2 I went to my admin panel. Main page has a standard look with no bugs. But as soon as I click on any object, I see this picture. Logs also look OK. [28/Oct/2020 15:04:52] "GET /static/admin/css/base.css HTTP/1.1" 200 16378 [28/Oct/2020 15:04:52] "GET /static/admin/css/nav_sidebar.css HTTP/1.1" 200 1789 [28/Oct/2020 15:04:52] "GET /static/admin/js/core.js HTTP/1.1" 200 5723 [28/Oct/2020 15:04:52] "GET /static/admin/js/jquery.init.js HTTP/1.1" 200 363 [28/Oct/2020 15:04:52] "GET /static/admin/js/actions.js HTTP/1.1" 200 6766 [28/Oct/2020 15:04:52] "GET /static/admin/js/admin/RelatedObjectLookups.js HTTP/1.1" 200 6918 [28/Oct/2020 15:04:52] "GET /static/admin/js/urlify.js HTTP/1.1" 200 8941 [28/Oct/2020 15:04:52] "GET /static/admin/js/nav_sidebar.js HTTP/1.1" 200 1360 [28/Oct/2020 15:04:52] "GET /static/admin/js/prepopulate.js HTTP/1.1" 200 1530 [28/Oct/2020 15:04:52] "GET /static/admin/css/responsive.css HTTP/1.1" 200 18052 [28/Oct/2020 15:04:52] "GET /static/admin/css/changelists.css HTTP/1.1" 200 6190 [28/Oct/2020 15:04:52] "GET /static/admin/js/vendor/jquery/jquery.js HTTP/1.1" 200 280364 [28/Oct/2020 15:04:52] "GET /admin-extended/jsi18n/ HTTP/1.1" 200 14892 [28/Oct/2020 15:04:52] "GET /static/admin/js/vendor/xregexp/xregexp.js HTTP/1.1" 200 128820 [28/Oct/2020 15:04:52] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423 [28/Oct/2020 15:04:52] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 86184 [28/Oct/2020 15:04:52] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 85876 [28/Oct/2020 15:04:52] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 85692 [28/Oct/2020 15:04:52] "GET /static/admin/img/tooltag-add.svg HTTP/1.1" 200 331 [28/Oct/2020 15:04:52] "GET /static/admin/img/icon-addlink.svg HTTP/1.1" 200 331 So I consider I don't have any problems with getting needed CSS files. What's the problem? Is it my mistake? EDIT1: When … -
Password recovery problem. Says the field is not filled in
Faced with the problem that the form is not validated. I want to make a password recovery form and use the built-in one, but for some reason it fails to validate. I printed out the request, form, form.errors. <QueryDict: {'csrfmiddlewaretoken': ['WHHpcIDpzHkV6NuCwhCcMHPdMLe7kiiF0q3zjRulXIgevmpTartl3T2lScowrUaA'], 'email': ['test.gmail.com', '']}>. <tr><th><label for="id_email">Email:</label></th><td><ul class="errorlist"><li> Negative field.</li></ul><input type="email" name="email" maxlength="254" required id="id_email"></td></tr>. <ul class="errorlist"><li>email<ul class="errorlist"><li>Mandatory field.</li></ul></ul>. file forms.py: from django.contrib.auth.forms import PasswordResetForm class UserForgotPasswordForm(PasswordResetForm): email = forms.EmailField(required=True,max_length=254) class Meta: model = User fields = ("email") file views.py: def UserResetPassword(request): if request.method == 'POST': form = UserForgotPasswordForm(request.POST) if form.is_valid(): form.save(from_email='blah@blah.com', email_template_name='market/email_template.html') -
Django Rest Framework: Rest-auth email verification - Server Error 500
I'm trying to enable email verification on Django Rest Framework with rest-auth. It works when I use console.Backend, however when I enable real emails via smtp, it gives me a Server Error 500 after registration. I'm using the same smtp settings as my node.js mail server which works perfectly, so I'm positive the smtp settings are correct. Does anyone have an idea what could cause this? I'm not sure what other code is responsible for this, please let me know if I need to provide something else. Here are the relevant settings: REST_SESSION_LOGIN = False ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = 'mandatory'#'none' #mandatory if enabled ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 3 ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USER_MODEL_USERNAME_FIELD = None LOGOUT_ON_PASSWORD_CHANGE = False OLD_PASSWORD_FIELD_ENABLED = False AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': { 'min_length': 6, } }, ] EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'mail.zxcs.nl' EMAIL_PORT = 465 EMAIL_HOST_USER = 'info@xxxxx.nl' EMAIL_HOST_PASSWORD = 'xxxxxxxxxxxxxx' EMAIL_USE_TLS = True EMAIL_USE_SSL = False AUTH_USER_MODEL = 'users.CustomUser' REST_AUTH_REGISTER_SERIALIZERS = { 'REGISTER_SERIALIZER': 'users.serializers.CustomRegisterSerializer', } -
How can I filter a queryset inside a django form?
I'm trying to add chat functionality to my app and right now I can add users to existing chats but what I need to do is filter users that are not already in the chat in the form. I'm using django form with passed arguments to filter my users but I'm not getting any results. My Chat model has a m2m field to user called 'users' and my User has a m2m field called 'friends' forms.py class AddUserToChatForm(forms.ModelForm): class Meta: model = Chat fields = ('users', ) def __init__(self, chat, friends, request, *args, **kwargs): self.request = request self.chat = chat self.friends = friends super(AddUserToChatForm, self).__init__(*args, **kwargs) self.fields['users'] = forms.ModelMultipleChoiceField(queryset=self.request.user.friends.exclude(user__in=chat.users.all()), widget=forms.CheckboxSelectMultiple (attrs={'class': 'add-people-to-chat-form'}), label='Friends:') views.py def add_users_to_chat(request, pk): chat = Chat.objects.get(pk=pk) friends = request.user.friends.all() if request.method == 'POST': form = AddUserToChatForm(chat, friends, request, request.POST) if form.is_valid(): users_to_add = form.cleaned_data['users'] chat.users.add(*users_to_add) chat.save() return redirect('messages') else: form = AddUserToChatForm(chat, friends, request, instance=None) return render(request, 'add_users_to_chat.html', {'form': form, 'chat': chat, 'friends': friends}) P.S. Using filter inside form queryset returns the entire list of user friends when using exclude returns an empty set. -
AppleOAuth2() is giving error __init__() takes at least 2 arguments (1 given). What is the argument which needs to be passed here?
class AppleOAuth2(BaseOAuth2): """apple authentication backend""" name = 'apple' ACCESS_TOKEN_URL = 'https://appleid.apple.com/auth/token' SCOPE_SEPARATOR = ',' ID_KEY = 'uid' -
How to add the result of a custom query to the Django Admin Site change_form template?
My web application manages hospitalizations and specialist examinations. Some of these exams may have been performed during a hospitalization, but I have no connection between the hospitalizations and the specialist exams. When the user modifies the data of an exam, I would like him to see at the bottom of the page all the admissions started before the exam and finished after the exam, because one of them could be the admissions where the exam was taken. How can I show the result of the query described above at the bottom of the "change_form" template of the Django Admin Site? Thanks in advance. -
Serialize dictionary to JSON in DRF
I have a method associated with the Statistic model returning the dictionary: def get_user_statistics(self, user): ... return { 'week_right: week_right, 'week_wrong': week_wrong, 'week_near' : week_near, 'days': days, 'day_right': day_right, 'day_wrong': day_wrong, 'day_near': day_near } where day_right, day_wrong, day_near and days are lists. I would like to send the result of this method in the form of JSON to the application written in Rect. However, when method get in generics.RetrieveAPIView looks like below: def get(self, request, *args, **kwargs): user = self.request.user user_stats = Statistic.objects.get_user_statistics(user) serializer = json.dumps(user_stats, cls=DjangoJSONEncoder) return Response(serializer) This Response is a simple string and I have to use JSON.parse JavaScript to process it. Is there any other way to serialize my dictionary to avoid using JSON.parse? -
Python Crash Course new_entry.save() causing me errors
So I'm following a book called Python Crash Course. And I'm currently working on its Django project, and I am encountering a problem that's apparently in the views.py. Here is the entire code for views.py: from django.shortcuts import render from django.http import HttpResponseRedirect, Http404 from django.http import HttpResponseRedirect from django.urls import reverse from django.contrib.auth.decorators import login_required from .models import Topic, Entry from .forms import TopicForm, EntryForm def index(request): return render(request, 'learning_logs/index.html') @login_required def topics(request): topics = Topic.objects.filter(owner=request.user).order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) @login_required def topic(request, topic_id): topic = Topic.objects.get(id=topic_id) if topic.owner != request.user: raise Http404 entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) @login_required def new_topic(request): if request.method != 'POST': form = TopicForm() else: form = TopicForm(data=request.POST) if form.is_valid(): new_topic = form.save(commit=False) new_topic.owner = request.user new_topic.save() form.save() return HttpResponseRedirect(reverse('learning_logs:topics')) context = {'form': form} return render(request, 'learning_logs/new_topic.html', context) @login_required def new_entry(request, topic_id): topic = Topic.objects.get(id=topic_id) if request.method != 'POST': form = EntryForm() else: form = EntryForm(data=request.POST) if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.save() return HttpResponseRedirect(reverse('learning_logs:topic', args=[topic_id])) context = {'topic': topic, 'form': form} return render(request, 'learning_logs/new_entry.html', context) @login_required def edit_entry(request, entry_id): entry = Entry.objects.get(id=entry_id) topic = entry.topic if topic.owner != request.user: raise … -
How to run a function in Django after a certain time passed by
Having the model of Station with the below fields: class Station(models.Model): is_available = models.BooleanField(default=True) unavailable_until = models.DateTimeField(null=True,blank=True) I can define until when my station is unavailable by giving a DateTime value , so when that action happens the is_available value turns to False. I want to turn the is_available value to True every time the unavailable_until value passed by(comparing with the current time based on the timezone). How can I achieve an automation like this? Imagine that I have a lot of Station records which belong to station owners which can update the availability (assign new unavailable_until value if passed by) whenever they want. I think the logic could be something like: def turn_availability_to_true(station): if (station.unavailable_until < current_time): station.is_available = True But how can I implement a function like this to be called by its own when the unavailable_until value passed by? -
Two forms on the same model, pb save
I'm a beginner in django, and my code is not yet factorized I have a problem during registration or update, delivery address overwrites billing address ? forms.py ------------------------------------------------------- class AddressForm(ModelForm): class Meta: model = Address fields = ( 'address', 'address2', 'zipcode', 'city', 'country', 'phone1', 'phone2', ) class AddressDeliveryForm(ModelForm): class Meta: model = Address fields = ( 'address', 'address2', 'zipcode', 'city', 'country', 'phone1', 'phone2', )' views.py--------------------------------------------------------------- @login_required(login_url="index") def updateCustomer(request, pk): customer = Account.objects.get(id=pk) addressbilling = address.objects.get(users_id=pk,delivery_address=False) addressdelivery = address.objects.get(users_id=pk,delivery_address=True) account_form = AccountForm(instance=customer) address_form = AddressForm(instance=addressbilling) addressdelivery_form = AddressDeliveryForm(instance=addressdelivery) if request.method == "POST": account_form = AccountForm(request.POST, request.FILES, instance=customer) address_form = AddressForm(request.POST, request.FILES, instance=address) addressdelivery_form = AddressDeliveryForm(request.POST, request.FILES, instance=addressdelivery) if account_form.is_valid() and address_form.is_valid() and addressdelivery_form.is_valid(): account_form.save() address_form.save() addressdelivery.save() return redirect('console_admin:list_customer') context = { 'account_form': account_form, 'address_form': address_form, 'addressdelivery_form': addressdelivery_form, 'customer' : customer.id } return render(request, 'console_admin/customer_form.html',context)