Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
operator does not exist: character varying + character varying
I changed the db from sqlite to postgresql for production for my website and I'm getting this error. It didn't get this error when i was working locally with sqlite. ProgrammingError at /boards/1/companies/1/ operator does not exist: character varying + character varying LINE 1: ...Col1, (AVG(((("boards_review"."move_in_condition" + "boards_... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. Request Method: GET Request URL: http://www.flythecoop.io/boards/1/companies/1/ Django Version: 2.2.6 Exception Type: ProgrammingError Exception Value: operator does not exist: character varying + character varying LINE 1: ...Col1, (AVG(((("boards_review"."move_in_condition" + "boards_... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. Exception Location: /home/reviews/venv/lib/python3.8/site-packages/django/db/backends/utils.py in _execute, line 84 Python Executable: /home/reviews/venv/bin/python3.8 Python Version: 3.8.0 Python Path: ['/home/reviews/venv/bin', '/home/reviews/reviews', '/home/reviews/venv/lib/python38.zip', '/home/reviews/venv/lib/python3.8', '/home/reviews/venv/lib/python3.8/lib-dynload', '/usr/lib/python3.8', '/home/reviews/venv/lib/python3.8/site-packages'] Server time: Sun, 24 Nov 2019 05:52:27 +0000 Error during template rendering In template /home/reviews/reviews/templates/baseb.html, error at line 0 operator does not exist: character varying + character varying LINE 1: ...Col1, (AVG(((("boards_review"."move_in_condition" + "boards_... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. Looking at the error, it said something about the snippet … -
Django return response without go through views.py
I'm from php, Laravel. I just start learn python and Django In Laravel, route can return response without go through controller '/home', function(){ return 'hello world'; } I'm wondering can Django do this too? without go through views.py? Something like below urlpatterns = [ path('home/', function(): return 'hello world'; ), ] -
How do I share post data with friends in django?
My views.py is : def home_view(request): """Display all the post of friends and own posts on the dashboard""" if request.user.is_authenticated: context = { 'posts': Posts.objects.filter(author=request.user).order_by('-date_posted'), 'media': MEDIA_URL, } return render(request, 'blog/home.html', context) else: return render(request, 'users/login.html') Thanking you in advance, -
Django "settings are not configured" error and cannot define environment variable DJANGO_SETTINGS_MODULE
This error is easy to reproduce. Read many StackOverflow posts and tried multiple methods but did not work. Created new directory named testproject pipenv install django Started new project named test with the django start project script pipenv shell django-admin runserver Error: "django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings." Typed this in ubuntu as suggested in the official django docs: export DJANGO_SETTINGS_MODULE=test.settings django-admin runserver Got a giant line of error followed by ModuleNotFoundError: No module named 'test'. However, if i do django-admin runserver --pythonpath=. --settings="test.settings" the server successfully ran. I know I can just use python manage.py to start the server but my project uses Django cache framework and when I try to access the cache the same settings are not configured error is thrown. Trying to understand what is going on, any help would be greatly appreciated. -
Rest Password using django rest framework
How can i reset user password (in case user forgot password) using django rest framework and send the reset password email to user -
Got AttributeError when attempting to get a value for field `user_type_data` on serializer `CustomUserSerializerWithToken`
views.py class CustomUserCreateView(APIView): permission_classes = (permissions.AllowAny,) def post(self, request, format=None): serializer = CustomUserSerializerWithToken(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) models.py class UserAdditionalDataModel(models.Model): ACCOUNT_CHOICE = [ ('1', "Employee"), ('2', "Employer"), ] user_type = models.OneToOneField(User, on_delete=models.CASCADE) account_type = models.CharField(choices=ACCOUNT_CHOICE, max_length=255) resume = models.FileField(upload_to='resume/%y/%m/%d/', blank=True, null=True) website = models.URLField(max_length=255, blank=True, null=True) def __str__(self): return self.user_type.mobile serializers.py class CustomUserSerializerWithToken(serializers.ModelSerializer): token = serializers.SerializerMethodField() password = serializers.CharField(write_only=True) user_type_data = UserAdditionalDataSerializer(many=True) def get_token(self, obj): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(obj) token = jwt_encode_handler(payload) return token def create(self, validated_data): user_type_data = validated_data.pop('user_type_data') password = validated_data.pop('password', None) user_data = self.Meta.model(**validated_data) if password is not None: user_data.set_password(password) user_data.save() for user_type_data in user_type_data: UserAdditionalDataModel.objects.create(user_type=user_data, **user_type_data) return user_data class Meta: model = User fields = ('token', 'mobile', 'password', 'first_name', 'last_name', 'email', 'user_type_data') I am following this tutorial Nested Serializers and I couldn't able to find what's wrong going on here.... when ever I call Post request on this it shows me this error... AttributeError at /core/custom_users/new/ Got AttributeError when attempting to get a value for field `user_type_data` on serializer `CustomUserSerializerWithToken`. The serializer field might be named incorrectly and not match any attribute or key on the `User` instance. Original exception text was: 'User' object has no … -
Django: How to mark an option in form from forms.py as selected
Here's my forms.py: from django import forms from users.models import EnglishInterest, UserPlans class CLSelectionForm(forms.Form): plan_choices = UserPlans().get_plan_choices_active() englishInterest_choices = EnglishInterest().get_english_interest_active() useremail = forms.EmailField(widget=forms.HiddenInput(attrs={ 'type': 'email'})) coupon = forms.CharField(widget=forms.HiddenInput(attrs={ 'type': 'email'})) plans = forms.CharField(label='Plan Choice', widget=forms.Select(choices=plan_choices, attrs={'id': 'plan_choice', 'class': 'fs-anim-lower fs-select-box', 'name': 'plan_choice'})) englishInterest = forms.CharField( label='English Interest', widget=forms.Select(choices=englishInterest_choices, attrs={'id': 'english_choice', 'class': 'fs-anim-lower fs-select-box', 'name': 'english_choice'})) submitButton = forms.CharField(widget=forms.TextInput( attrs={'type': 'submit', 'name': 'submit', 'id': 'fs-submit-button', 'class': 'fs-submit', 'value': 'Submit'})) class Meta: fields = ['useremail', 'coupon', 'plans', 'englishInterest'] How would I go about rendering the plans and englishInterest form elements, with options that include a selected attribute? -
Django - AJAX POST to API not working but no errors
I am trying to post data to my Django Rest Framework API, I have a GET request which works. The POST request does not work and the error function of the AJAX call is fired. I cant seem to see why it wont work, perhaps my CSRF or CORS headers are incorrect? main.js $(function () { var $items = $('#items'); var $description = $('#description'); var $price = $('#price'); $.ajax({ type: 'GET', url: '/api', success: function(items) { console.log(items) $.each(items,function(i, item){ $items.append('<li> '+ item.pk +', '+ item.Description +', '+ item.Price +'</li>'); }); }, error: function() { alert('Error Loading Items'); } }); $('#add-item').on('click', function() { var order = { description: $description.val(), price: $price.val(), }; $.ajax({ type: 'POST', csrfmiddlewaretoken: "{{ csrf_token }}", url: '127.0.0.1:8000/api/', data: order, success: function(newItem) { $items.append('<li> '+ newItem.Description +', '+ newItem.Price +'</li>'); }, error: function() { console.log(order) } }); }); }); models.py class Item(models.Model): Description = models.CharField(max_length=20) Price = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return self.Description Serializers Views.py class ItemListAPIView(generics.ListCreateAPIView): lookup_field = 'pk' queryset = Item.objects.all() serializer_class = ItemSerializer permission_classes = (AllowAny,) -
Getting error when I am trying to fetch my main url patterns
I am a beginner in Django I have created a Django project in that I have included two more application when I did add urls.py file in both Applications both are working well but when I am fetching my main admin URL it is giving an error Page not found (404) Request Method: GET URL: http://127.0.0.1:8000/ the URLconf defined in mac.urls, Django tried these URL patterns, in this order: admin/ shop/ blog/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. when I am fetching this URL in http://127.0.0.1:8000/ i am getting an error it is working for http://127.0.0.1:8000/shop/ here is my main urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('shop/', include('shop.urls')), path('blog/', include('blog.urls')), ] Please suggest me I would appreciate every response in StackOverflow -
AttributeError 'RegisterDetailView' object has no attribute 'get_object'
I'm attempting to submit a PATCH for an existing record via curl. I want to change my Boolean field from true to false. The primary key is not the default id, but a CharField defined in my models.py I did this hoping to make the url path easier to manipulate; /api/register/serial number vs id number. models.py from django.db import models class Register(models.Model): system_type = models.CharField(max_length=255) serial_number = models.CharField(max_length=255, unique=True, primary_key=True) mac_address = models.CharField(max_length=17, unique=True) ip_address = models.CharField(max_length=15) request = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.serial_number views.py class RegisterDetailView(APIView): serializer_class = serializers.RegisterSerializer def get(self, pk): return Register.objects.get(pk=pk) def patch(self, request, pk): registermodel_object = self.get_object(pk) serializer = serializers.RegisterSerializer(registermodel_object, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response( serializer.errors, status=status.HTTP_400_BAD_REQUEST ) urls.py from django.urls import path, include, re_path from register import views urlpatterns = [ re_path(r'^register/(?P<pk>\w+)/$', views.RegisterDetailView.as_view()), ] curl command curl -d "system_type=switch&serial_number=SAL1834ZDSY&ip_address=f8c2.8887.d480&mac_address=172.16.24.11&request=false" -X PATCH http://192.168.1.100/api/register/SAL1834ZDSY/ When I run my curl command using patch I get this error: AttributeError at /api/register/SAL1834ZDSY/ 'RegisterDetailView' object has no attribute 'get_object' Request Method: PATCH Request URL: http://192.168.1.100/api/register/SAL1834ZDSY/ Django Version: 2.2.6 Python Executable: /usr/local/bin/uwsgi Python Version: 3.6.8 Python Path: ['.', '', '/usr/lib64/python36.zip', '/usr/lib64/python3.6', '/usr/lib64/python3.6/lib-dynload', '/opt/django/lib64/python3.6/site-packages', '/opt/django/lib/python3.6/site-packages'] Server time: Sun, 24 Nov 2019 … -
how to check if token was expired in models?
I am trying to expire tokens from forgot password requests, but token from PasswordReset becomes NULL after the user updates their password, however, I was thinking on some kind of solution, but I want to expire the token usage after 1 minute or max 5 minutes to meet security requirements, but I also got created_at . how can I set up an is_expire function to invalid the token? if self.token == None: return False do_expire models.py class PasswordReset(models.Model): email = models.ForeignKey(User, on_delete=models.CASCADE) token = models.CharField(max_length=100, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True, blank=True) updated_at = models.DateTimeField(auto_now=True, blank=True) -
Creating modelform to exclude a field loses "nice" handling of unique contraint
I have a model which includes a 'customer' (fk to User), that I have excluded from a custom form (because the logged in user is already known). The issue I'm having is that I lose the 'nice' form handling for unique constraints once I override the form_valid method to accomodate the excluded field. models.py: class RequestedData(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) station = models.ForeignKey(Station, on_delete=models.CASCADE, verbose_name = 'Measurement Station') measurement = models.ForeignKey(Measurement, on_delete=models.CASCADE) class Meta: verbose_name_plural = "Requested Data" constraints = [ models.UniqueConstraint( fields=["customer", "station", "measurement"], name="station-measurement-unique",)] The class view is: class RequestedDataCreate(LoginRequiredMixin, CreateView): model = RequestedData # use overriden form to remove customer from selection form_class = RequestedDataForm success_url = reverse_lazy("requesteddata_list") # overwrite form_valid function to add back in user. def form_valid(self, form): form.instance.customer = Customer.objects.get(user__username=self.request.user) return super().form_valid(form) where you can see I've created a RequestedDataForm to exclude the customer from the form. class RequestedDataForm(ModelForm): class Meta: model = RequestedData exclude = ("customer",) All works well, except when the user enters data in the form that violates the unique constraint. Before I created the custom form to exclude user (i.e. just using the CreateView form), upon violation of the unique constraint a message would appear as shown below, namely, a … -
ImportError: cannot import name 'Topic' from 'first_app'
**this is my models.py** from django.db import models # Create your models here. class Topic(models.Model): top_name = models.CharField(max_length=264,unique=True) def __str__(self): return self.top_name class Webpage(models.Model): topic = models.ForeignKey('Topic',on_delete=models.PROTECT) name = models.CharField(max_length=264,unique=True) url = models.URLField(unique=True) def __str__(self): return self.name class AccessRecord(models.Model): name = models.ForeignKey('Webpage',on_delete=models.PROTECT) date = models.DateField() def __str__(self): return self.date and this is my populate.py import os os.environ.setdefault('DJANGO_SETTINGS_MODULE','first_project.settings') import django django.setup() ##fake pop script import random from first_app import Topic,Webpage,AccessRecord from faker import faker fakegen = faker() topics = ['Search','Social','Marketplace','News','Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(N=5): #get the topic for the entry top = add_topic() #create the fake data for that entry fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.name() #create a fake new Webpage entry webpg = Webpage.objects.get_or_create(Topic=top,url=fake_url,name=fake_name)[0] #create a fake access record for that Webpage acc_rec = AccessRecord.objects.get_or_create(name=webpg,date=fake_date)[0] if __name__ == '__main__': print("population script") populate(20) print("populate complete") im trying run populate.py but i have error Traceback (most recent call last): File "populate_first_app.py", line 9, in from first_app import Topic,Webpage,AccessRecord ImportError: cannot import name 'Topic' from 'first_app' (/home/hamid/Desktop/my_django_stuff/first _project/first_app/__init__.py) -
DJango FilterSet - Issue with date input in template and other question
I'm currently working with the FilterSet from django but I'm stuck trying to achieve the following things To get the FilterSet in the views.py to bring no items when there is no filter entered by the user To make the field inicio both lte and gte a required field in the web page in order to click the search button. To make the input of the field inicio a Date type or at least something like this where the user doesnt have to write the datetime field in the format dd-mm-yyyy hh:mm:ss I'm also using bootstrap. view.py def reportes(request): audios = Audio.objects.filter(inicio__gte=datetime.datetime.now()-datetime.timedelta(days=1)) reporte_filter = ReporteFilter(request.GET, queryset=audios) return render(request, 'buscar.html',{'filter': reporte_filter}) models.py class Audio(models.Model): file = models.FileField(upload_to='audios/files/',default=None) inicio = models.DateTimeField(default=None) filters.py class ReporteFilter(django_filters.FilterSet): class Meta: model = Audio fields = {'inicio':['lte','gte']} template.html <div class="form-group col-sm-4 col-md-3" id="idInicioMenor"> {{ filter.form.inicio__lte.label_tag }} {% render_field filter.form.inicio__lte class="form-control" %} </div> <div class="form-group col-sm-4 col-md-3" id="idInicioMayor"> {{ filter.form.inicio__gte.label_tag }} {% render_field filter.form.inicio__gte class="form-control" %} </div> Thanks in advance. -
Filter by distance from coordinates (Django over MariaDB)?
I have a collection of records with latitude & longitude coordinates in my database. Is there a straightforward way to filter for other objects within some specified radius of a given object? Use would be for a method place.get_nearby(rad_km=1.3) -> "QuerySet[Place]" or a function find_nearby(place: Place, rad_km: float) -> "QuerySet[Place]" is fine. If there is a heavily involved solution (lots of new libraries & refactoring necessary), I'll declare this to be out of scope. I currently have a method on my Places to calculate distances between them (both in radians and km), but no way to filter for nearby places. The final use case would be to generate informational tables such as the following: +-------------------------+-----------------------+-----------------------------+ | Northwest Plaza (1.1km) | | NE Corner (0.04km) | +-------------------------+-----------------------+-----------------------------+ | West Street (0.789km) | You are here™ | | +-------------------------+-----------------------+-----------------------------+ | | South Avenue (1.17km) | SW Sunset Building (0.43km) | +-------------------------+-----------------------+-----------------------------+ Additionally, would the best way to determine which square to put an object in be arctan((lat2-lat1)/(lon2-lon1)) (assuming they're reasonably close)? -
Pass JSON data from API to Template in Django
im new to Django and im trying to get a template filled with data comming from an API. The data looks like this: {'incident': {'collection_in': {'@COUNT': '2', '@START': '1', '@TOTAL_COUNT': '9', 'in': [{'@COMMON_NAME': '1', '@REL_ATTR': 'cr:0.1', '@id': '1' **SOME EXTRA DATA** }], 'in':['@COMMON_NAME': '2', '@REL_ATTR': 'cr:0.2', '@id': '2' **SOME EXTRA DATA** }] } } } This is my views.py def index(request): access_key = '#' rest = "/in?WC=group.id%3DU'F909D6A3414DC34BBD39A4D7BA4A663D'" get_headers = { "X-AccessKey":access_key, 'Accept':"application/json", "X-Obj-Attrs": "*" } proxys = { # } response2 = requests.get("http://XXXXXXXX/caisd-rest/"+rest, headers=get_headers,proxies=proxys) return render(request,'incident/index.html',context={'incident':json.loads(response2.content)}) And my template: <ul> {% for key in incident.collection_in.in %} <li>{{key.@id}}</li> {% endfor %} </ul> I have tried multiple ways, but i cant access the values or i get this error: Could not parse the remainder: '@id' from 'key.@id' if i remove the @id, from key.@id, i get all the data, but im only interested in this case at the ids How do i do this or what im missing? -
How do I access my SQLite database from my webpage using Django?
I'm using Django to host a localhost webserver for a webpage. I have the page and everything working on Django, and so far it's working and is accessible through localhost. I also set up a SQLite table through the Models of Django, which I would like to take data in from and send data to the webpage. I don't presently have any extra Python code interacting with the webpage itself. How do I link the webpage to my database? -
How to add Procfile in pycharm for Heroku deplyment?
Trying to add a Procfile to my pycharm django project but it just asking me for the file extention. Any idea?? -
How to deal with Hyphen and Django rest ModelSerializer
I am trying to implement an endpoint to receive email from the mailgun.com API. Basically, when an email is sent to the mailing list, they call your endpoint https://host/messages/ with a POST request. The problem is that they do not use standard REST and some of the keys contain hyphens. This is an example of the request I receive: { 'Date': [ 'Fri, 26 Apr 2013 11:50:29 -0700' ], 'From': [ 'Bob <bob@sandbox9cbe4c2829ed44e98c8ebd0c26129004.mailgun.org>' ], 'Sender': [ 'bob@sandbox9cbe4c2829ed44e98c8ebd0c26129004.mailgun.org' ], 'Subject': [ 'Re: Sample POST request' ], 'To': [ 'Alice <alice@sandbox9cbe4c2829ed44e98c8ebd0c26129004.mailgun.org>' ], 'body-plain': [ 'Hi Alice,\n\nThis is Bob.\n\nI also attached a file.\n\nThanks,\nBob\n\nOn 04/26/2013 11:29 AM, Alice wrote:\n> Hi Bob,\n>\n> This is Alice. How are you doing?\n>\n> Thanks,\n> Alice\n\n' ], I write a serialize and manage to get all fields without hyphens such as From, To, etc. But after hours of trials I cannot manage to get the body-plain. I tried this: class MessageSerializer(serializers.ModelSerializer): Text = serializers.CharField(source='body-plain') class Meta: model = Message fields = ['From', 'To', 'Subject', 'Text'] but I get the error {"Text":["This field is required."]} It seems to me that Django rest is perhaps modifying the keys. Does someone know how to deal with this problem? -
Django TestCase Client Returns URL Without Language Prefix
I have the following unit-test for user password change in my Django app. class LoginRequiredPasswordChangeTests(TestCase): def test_redirection(self): url = reverse('user_accounts:password_change') login_url = reverse('user_accounts:login') print(url) print(login_url) response = self.client.get(url) print(response) self.assertRedirects(response, f'{login_url}?next={url}') Prior to enabling internationalization and switching to i18n patterns in the project's urls.py, the test succeeded. After that it started failing. At the same time, the actual reset functionality works. As you can see, I have inserted a few prints into the test. Here is what they produce. /en/user/password/ /en/user/login/ <HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/user/login/?next=/en/user/password/"> The pertinent url patterns for these are # paths for password change path('password/', auth_views.PasswordChangeView.as_view(template_name='user_accounts/password_change.html', success_url = reverse_lazy('user_accounts:password_change_done')), name='password_change'), path('password/done/', auth_views.PasswordChangeDoneView.as_view(template_name='user_accounts/password_change_done.html'), name='password_change_done'), It appears to me that test.client returns a URL without the language prefix. Am I right to think so? Is that expected? How can I fix this? -
Setup React and Django-rest-framework in nginx
My project have react-js in front-end and Django-Rest-framework. I have set up my Nginx location '/' to serve the static files from /project/build and '/api' to the Django server listening to 8000 port but it is not behaving as aspected. Nginx is not making calls to my Django API even I am hitting the right URL. This is working fine as my react app is http://127.0.0.1/app and api is http://127.0.0.1/api. I want my nginx setup to serve '/' as my react app and '/api' as Django. Maybe '/api' is searching in my react app and giving a NOT FOUND error. Please suggest something in Nginx to make this work. -
Change values to lowercase before importing to Django
I am using Django Import-Export to import data from an excel(xlsx) file to my Django Models. What I have works but I want it to consider strings with characters that have different cases to be the same. Currently if I have 'Black Sabbath' and 'black sabbath' in a column, the import considers them to be different artists. Is it possible to change all string values to lowercase during the import process? Or somehow configure Django to consider them the same? resources.py class ArtistResource(resources.ModelResource): class Meta: model = Artist import_id_fields = ('artist',) skip_unchanged = True models.py class Artist(models.Model): artist = models.CharField(primary_key=True, unique=True, max_length=30) def __str__(self): return self.artist admin.py class ArtistAdmin(ImportExportActionModelAdmin): resource_class = ArtistResource -
Django Bootstrap Modal Form Doesn't Function
I'm creating a todo website that has users adding a new event, which I want to be a modal form. I used django-bootstrap-modal-forms, but when I click the new event button nothing pops up. I think it has something to do with the button not binding correctly to a view, but I made sure to follow the docs again and it still doesn't work. I also made sure I had bootstrap, jquery, and the custom script on the website. Any help would be appreciated! forms.py from bootstrap_modal_forms.forms import BSModalForm from .widgets import BootstrapDateTimePickerInput from bootstrap_datepicker_plus import DateTimePickerInput from .models import ToDoItem class NewEventForm(BSModalForm): class Meta: model = ToDoItem fields = ['title', 'description', 'start_time', 'end_time', 'remind_time'] widgets = { 'start_time': DateTimePickerInput( options={"format": "MM/DD/YYYY hh:mm"} ), 'end_time': DateTimePickerInput( options={"format": "MM/DD/YYYY hh:mm"} ), 'remind_time': DateTimePickerInput( options={"format": "MM/DD/YYYY hh:mm"} ), } Views.py from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.urls import reverse_lazy from .models import ToDoItem from .forms import NewEventForm from bootstrap_modal_forms.generic import BSModalCreateView @login_required(login_url='/login') def home(request): user = get_object_or_404(User, username=request.user.username) context = { 'events': ToDoItem.objects.filter(parent_user=user) } return render(request, 'main/home.html', context) # @login_required(login_url='/login') # def new_event(request): # if request.method == 'POST': # form = NewEventForm(request.POST) # … -
Django project-apps: What's your approach about implementing a real database scheme?
I've read articles and posts about what a project and an app is for Django, and basically end up using the typical example of Pool and Users, however a real program generally use a complex relational database, therefore its design gravitates around this RDB; and the eternal conflict raises once again about: which ones to consider an application and which one to consider components of that application? Let's take as an example this RDB (courtesy of Visual Paradigm): I could consider the whole set as an application or to consider every entity as an application, the outlook looks gray. The only thing I'm sure is about this: $ django-admin startproject movie_rental So I wish to learn from the expertise of all of you: What approach would you use to create applications based on this RDB for a Django project? Thanks in advance. -
Django admin automatic reload when foreign key is registered
Does anyone know how does Django notice when a registration tab is closed? For example, when you are creating a certain entry in the database, and it has a Foreign Key (or ManyToMayField and so on) and you click on the plus sing to add an object in another table, and it opens a tab to register this element, and when you save it, it has already been popped up on the options to select on the object you were creating on the first place. I want to know how to do something similar in a regular Django project, but in the template html files. Please, help me.