Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In Django, how to send context or variables to JQuery?
I have a Model (Persons) which has to be entered using a ModelForm (PersonForm). models.py, GENDER_CHOICES = [ ('Male', 'Male'), ('Female', 'Female'), ] MALE_CATEGORIES = [ ('Male Category 1', 'Male Category 1'), ('Male Category 2', 'Male Category 2'), ('Male Category 3', 'Male Category 3'), ] FEMALE_CATEGORIES = [ ('Female Category 1', 'Female Category 1'), ('Female Category 2', 'Female Category 2'), ('Female Category 3', 'Female Category 3'), ] def get_all_choices(): all_choices = MALE_CATEGORIES all_choices+=FEMALE_CATEGORIES return all_choices class Person(models.Model): name = models.CharField(max_length=50, unique=True) gender = models.CharField(max_length=7, choices=GENDER_CHOICES) category = models.CharField(max_length=20, choices=get_all_choices()) forms.py, class PersonForm(ModelForm): class Meta: model = Person fields = [ 'name', 'gender', 'category', ] views.py, def personform_page(request): context = {} if request.method == 'POST': personform = PersonForm(request.POST) if personform.is_valid(): personform.save() return redirect('personform_page') context['personform'] = personform else: personform = PersonForm() context['personform'] = personform context['male_categories'] = MALE_CATEGORIES context['female_categories'] = FEMALE_CATEGORIES return render(request, 'app1/personform_page.html', context=context) PersonForm has a dependent dropdown list of which the category choices will be dependent on the selected gender. Currently, I am hardcoding the category choices in JQuery as follows: personform_page.html, <form class="form-class" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {% for field in personform %} <p> {{ field.label_tag }} {{ field }} {% if field.help_text %} <small style="color: black;"> … -
Django Import-Export, importing related parent and child models
I'm having trouble following the documentation for django-import-export, I think ive tried every variation of changing the child and parent in the admin to try to make this work. Do you see any glaring issues? This code gives me the error "Line number: 1 - Parent matching query does not exist." models.py class Parent(models.Model): store = models.IntegerField(primary_key=True) state = models.CharField(max_length=250, blank=True) # pylint: disable=R0903 def __str__(self): return '{}'.format(self.store) class Child(models.Model): store = models.ForeignKey('Parent', on_delete=models.CASCADE) company = models.CharField(max_length=250, blank=True) rank = models.IntegerField(blank=True, default='') admin.py class ChildResource(resources.ModelResource): state = fields.Field(attribute='state', column_name='State') company = fields.Field(attribute='company', column_name='Company') rank = fields.Field(attribute='rank', column_name='Rank') store = fields.Field(attribute='store', column_name='Store', widget=ForeignKeyWidget(Parent, 'store')) class Meta: model = Child import_id_fields = ('store',) fields = ('store', 'state', 'company', 'rank') class ParentAdmin(ImportExportModelAdmin): inlines = [Child] resource_class = ChildResource list_display = ('company', 'rank') class Meta: model = Child admin.site.register(Child, ChildAdmin) -
How creat Submenu for mainmenu in django
I am trying to displaying Menu and Sub Menu in table format like. Menu1 Menu2 SubMenu1 SubMenu2 SubMenu3 menu2 but i'm getting wrong. menu1 submenu1 menu2 submenu2 and when I'm adding new submenu it's appearing under both main menu my models.py for menu app from django.db import models class Menu(models.Model): menu_name = models.CharField(max_length=100,blank=True) menu_slug = models.SlugField(max_length=100,unique=True,blank=True) menu_icon = models.ImageField(upload_to="imagemenu",blank=True) def __str__(self): return self.menu_name class Submenu(models.Model): submenu_name = models.CharField(max_length=100,blank=True) submenu_slug = models.SlugField(max_length=100, unique=True,blank=True) submenu_icon = models.ImageField(upload_to="imagemenu",blank=True) parent_menu = models.ManyToManyField(Menu, verbose_name=("Mtavari Menu")) def __str__(self): return self.submenu_name my views.py from django.shortcuts import render from django.http import HttpResponse from menu.models import Menu,Submenu # Create your views here. def HomePage(request): template = "front/Homepage.html" menu_item = Menu.objects.all() menu_submenu = Submenu.objects.all() return render(request,template, {"menu_item":menu_item,}) template file <ul> {% for menu in menu_item %} <li> <a href="#">{{menu.menu_name}}</a> <ul class="sub-menu"> {% for sub in menu_submenu %}<li><a href="index.html">{{sub.submenu_name}}</a></li>{% endfo %} </ul> </li> {% endfor %} </ul> -
Why i can not center div in CSS?
Hei! I am trying to center some div on my website. but nothing moves. Everything stays on left side even now when i haved changed all divs to center. i am checking in many browsers, but still everything is on left side. not i have even changed all divs to center.. still everything on left side. Here is my css code: h1 a, h2 a { color: #DE1FAE; body { padding-left: 15px; text-align: center; } #container { text-align: center; } #gobacktomainback { text-align: center; font-size: 5px; } #searchfield { margin-left: 10px; text-align: center; padding: 30px; background-color: white; } #logo { text-align: center; color: white; background-color: #white; text-align: center; } #login { text-align: center; background-color: #C0C0C0; } #menu { background-color: white; } ul > li { list-style-type: none; float: left; } ul > li > a { padding: 0 20px; } #addrecipe text-align: center; #addingredient text-align: center; HTML: {% load static %} <html> <head> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="{% static 'css/drinks.css' %}"> </head> <body> <div id=container> <div id=menu> {% if user.is_authenticated %} <ul> <li><a href="add_recipe">Add recipe</a></li> <li><a href="add_ingredient">Add ingredient</a></li> <li><a href="">Drink list</a></li> </ul> {% endif %} </div> <div id=login> {% if user.is_authenticated %} Hi {{ user.username }}! … -
`Server Error (500)` when deploying django application to heroku
I don't know what is the problem I am trying to deploy my application to Heroku with DEBUG=False but it's sending me Server Error (500) in the UI. However, If I deploy the application with DEBUG=True it works perfect. Here is my settings.py: """ Django settings for main_tour_folder project. Generated by 'django-admin startproject' using Django 3.0.3. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # To import the env.py secret_keys if os.path.exists('env.py'): import env import dj_database_url # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['<app-name>.herokuapp.com', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_forms_bootstrap', 'accounts', 'tour_store', 'cart', 'checkout', 'search', ] MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'main_tour_folder.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', # … -
Django model creating new migration after change in model choices
I have a model named UserRole and there is a field role, in which choices are present to select the role. The problem is that whenever I am adding a new choice and running makemigrations, django creating a new migration for that. I don't want a new migration everytime I add a choice. I know about ForeignKey, but in my case there will be at most 10 choices. Right now I have 3 predefined choices. How can I add choices without creating a new migrations? models.py class UserRoleModel(BaseModel): ROLE_1, ROLE_2, ROLE_3 = 1, 2, 3, USER = 'user' SUPPORT = 'support' ANALYST = 'analyst' CHOICES = ( (ROLE_1, USER), (ROLE_2, SUPPORT), (ROLE_3, ANALYST), ) user = models.ForeignKey(get_user_model()) role = models.SmallIntegerField(choices=CHOICES) migration file class Migration(migrations.Migration): operations = [ migrations.AlterField( model_name='userrolemodel', name='role', field=models.SmallIntegerField(choices=[(1, 'user'), (2, 'support'), (3, 'analyst'), (4, 'lol')]), ), ] I have removed redundant code. -
Wagtail manually login user
I have a wagtail application that needs to login and authenticate users for the /admin section using OAuth. The interaction with the OAuth provider works fine is just at the end of the authorize view I am getting a Too many redirects error. Here is my gist: SESSION_KEY = 'access_token' oauth = OAuth() oauth_client = oauth.remote_app(#oauth client setup here) Views def login(request): """ This view is redirecting to my oauth provider, log the user and redirect back to /authorize with the data in the request. """ return HttpResponseRedirect(oauth_client.authorize( callback='http://localhost/admin/authorize')) def authorize(request): resp = oauth_client.authorized_response(request.GET) request.session[SESSION_KEY] = (resp['access_token'], '') data = baton.get('/oauth/me') username = json.loads(data.data).get('username') user, _ = User.objects.get_or_create( username=username, defaults={'password': username, 'is_superuser': True} ) auth_user = authenticate(username=username, password=username) login(auth_user) return HttpResponseRedirect('/admin') Urls urlpatterns = [ url(r'^admin/login', login, name='login'), url(r'^admin/authorize', authorize, name='authorize'), url(r'^admin/', include(wagtailadmin_urls)), ] The Too many redirects I see in the browsers happens when the authorize view validates all the logic and tries to redirect to /admin but I think what is happening is that Wagtail then is redirecting again to /login but I though authenticating and login a user should be enough for Wagtail, apparently not. Any ideas how to overcome this issue, or programmatically login a user … -
django queryset related objects to json array
I have two models class Place(models.Model): title = models.CharField(max_length = 255) description = models.TextField() class PlaceImage(models.Model): place = models.ForeignKey(Place, default=None, on_delete=models.CASCADE) photo = models.ImageField(upload_to='places', verbose_name='Photo') title = models.CharField(max_length = 250, default = "tmp") and function in a view def read_place(request, place_id): place = Place.objects.filter(pk=place_id).annotate(photos=F('placeimage__photo')).values("id", 'title', 'photos') return JsonResponse(list(place), safe=False) that returns me json objects [{"id": 1, "title": "title1", "photos": "places_upload_location/memorial1.jpg"}, {"id": 1, "title": "title1", "photos": "places_upload_location/memorial2.jpg"}, {"id": 1, "title": "title1", "photos": "places_upload_location/memorial3.jpg"}] But I'd like to get single Place object with array of photos, something like this: [{"id": 1, "title": "title1", "photos": [{ "photo_id": 1, "photo": "places_upload_location/memorial1.jpg" "title": "photo 1" }, { "photo_id": 2, "photo": "places_upload_location/memorial2.jpg" "title": "photo 2" }, { "photo_id": 3, "photo": "places_upload_location/memorial3.jpg" "title": "photo 3" }] }] How can I do it? -
Using multiple Django forms in single View which are dependent through OnetoOneField/ForeignKey
I have two models:- class User(AbstractUser): is_customer = models.BooleanField('customer status',default=False) is_manager = models.BooleanField('manager status',default=False) def __str__(self): return self.username class Customer(models.Model): user = models.OneToOneField(User,on_delete=models.PROTECT,primary_key=True,related_name="customers") full_name = models.CharField(max_length=264,) roll_no = models.IntegerField() mobile_no = models.IntegerField() hostel = models.CharField(max_length=264) room_no = models.CharField(max_length=264,) Here Customer's user object is dependent on the User model. forms.py:- class UserCreateForm(UserCreationForm): class Meta: fields =('username','email','password1','password2') model = User def __str__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields["username"].label ="Display name" self.fields["email"].label = "Email address" class CustomerForm(forms.ModelForm): class Meta: model = Customer fields = ['full_name','roll_no','hostel'] What I want is to take Customer's details along with User details. So, How can I use these two models in one View (class-based views will be preferred) and create a single form in the Html file? Please explain the code for views.py and for related Html file. -
How to increment variable in Django template?
I was making a grid and need to declare the variable and increment it. {% for new, des, i, link, published, author in mylist %} {% if x == 1 %} <div class="col-md-6"> <div class="h-100 mt-2 row no-gutters border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative"> <div class="col p-4 d-flex flex-column position-static"> <strong class="d-inline-block mb-2 text-primary">World</strong> <h5 class="mb-0">{{new}}</h5> <div class="mb-1 text-muted">{{published}}</div> <p class="card-text mb-auto">{{des}}</p> <a href="{{link}}" class="stretched-link">Continue reading</a> </div> <div class="col-auto d-none d-lg-block"> <img class="bd-placeholder-img" src="{{i}}" width="200" height="250" > </div> </div> </div> {% endif %} {% endfor %} Help me to declare variable x and increment it like x+1 inside the template I was trying {% with x=0 %} but that's not working -
TypeError: Object of type 'DoesNotExist' is not JSON serializable ( Django REST Framework)
Full traceback (heroku): 2020-03-24T16:11:47.624938+00:00 app[web.1]: Internal Server Error: /api/register_domain_name 2020-03-24T16:11:47.624949+00:00 app[web.1]: Traceback (most recent call last): 2020-03-24T16:11:47.624950+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner 2020-03-24T16:11:47.624951+00:00 app[web.1]: response = get_response(request) 2020-03-24T16:11:47.624952+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 158, in _get_response 2020-03-24T16:11:47.624952+00:00 app[web.1]: response = self.process_exception_by_middleware(e, request) 2020-03-24T16:11:47.624953+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py", line 156, in _get_response 2020-03-24T16:11:47.624953+00:00 app[web.1]: response = response.render() 2020-03-24T16:11:47.624953+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/template/response.py", line 106, in render 2020-03-24T16:11:47.624954+00:00 app[web.1]: self.content = self.rendered_content 2020-03-24T16:11:47.624954+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/rest_framework/response.py", line 72, in rendered_content 2020-03-24T16:11:47.624955+00:00 app[web.1]: ret = renderer.render(self.data, accepted_media_type, context) 2020-03-24T16:11:47.624955+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/rest_framework/renderers.py", line 105, in render 2020-03-24T16:11:47.624956+00:00 app[web.1]: allow_nan=not self.strict, separators=separators 2020-03-24T16:11:47.624956+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/rest_framework/utils/json.py", line 28, in dumps 2020-03-24T16:11:47.624957+00:00 app[web.1]: return json.dumps(*args, **kwargs) 2020-03-24T16:11:47.624957+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/json/__init__.py", line 238, in dumps 2020-03-24T16:11:47.624958+00:00 app[web.1]: **kw).encode(obj) 2020-03-24T16:11:47.624959+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/json/encoder.py", line 199, in encode 2020-03-24T16:11:47.624959+00:00 app[web.1]: chunks = self.iterencode(o, _one_shot=True) 2020-03-24T16:11:47.624960+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/json/encoder.py", line 257, in iterencode 2020-03-24T16:11:47.624961+00:00 app[web.1]: return _iterencode(o, 0) 2020-03-24T16:11:47.624961+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/rest_framework/utils/encoders.py", line 68, in default 2020-03-24T16:11:47.624962+00:00 app[web.1]: return super(JSONEncoder, self).default(obj) 2020-03-24T16:11:47.624962+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/json/encoder.py", line 180, in default 2020-03-24T16:11:47.624963+00:00 app[web.1]: o.__class__.__name__) 2020-03-24T16:11:47.624963+00:00 app[web.1]: TypeError: Object of type 'DoesNotExist' is not JSON serializable This happens when I call an api func: @api_view(['POST']) @permission_classes((IsAuthenticated,)) @authentication_classes((TokenAuthentication,)) @ensure_csrf_cookie @renderer_classes((JSONRenderer,)) def register_domain_name(request): if request.method … -
Unable to insert the data into model users group
I have created a custom User model in Django app users_and_auth to use the default authentication of the Django. models.py class Users(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255, blank=False, null=False) last_name = models.CharField(max_length=255, blank=False, null=False) profile_picture = models.ImageField(upload_to='profile_pictures/', max_length=None, null=True, blank=True) is_active = models.BooleanField(default=True) objects = managers.UserManager() USERNAME_FIELD = 'email' I want to categorize registered users in two different user groups say x and y. So, I added two new records in Group model of auth app i.e auth_group which was created when I run the first migration of the app. Then I run the migration of app users_and_auth which created 3 new models users_and_auth_users, users_and_auth_users_groups and users_and_auth_users_user_permissions. Now, these are the tables of database - As, shown in screenshot there is table in database called users_and_auth_users_groups which categorize users in groups listed in table auth_group. The table is described as below - I want to push the user_id and group_id in this database table from an APIView. What I don't understand is which exact app or model I will have to import so that I could use model.object.create(). -
Django - Ajax not sending data correctly
In my project, I set up an AJAX call, which grabs what a user entered inside an input, sends it to the server, and once returned back to AJAX, it should be displayed inside a div. However no text is displayed in the div as expected. Here is my HTML (signup.html): <form id="signup_form" action="{% url 'signup' %}"> {% for field in form %} {{ field }} <br> {% endfor %} <button class="signup-btn btn btn-primary">Sign up</button> </form> <div id="testbox"></div> JS: var delayTimer; $('#signup_form').keyup(function() { clearTimeout(delayTimer); delayTimer = setTimeout(function () { // Username input in my form(created by Django forms) var usernameVal = $("#username_signup").val(); $.ajax({ url: '/users/ajax/signup', data: { 'usernameVal': usernameVal, }, dataType: 'json', success: function(data) { $('#testbox').text(data['usernameVal']); console.log(data['usernameVal']); } }); }, 1000); }); views.py: // Function to handle AJAX request def ajax_signup(request): form = SignupForm(request.GET) if form.is_valid(): print("It works") return JsonResponse({'usernameVal': form.cleaned_data.get("usernameVal")}) else: print(form.errors) return JsonResponse({'hello': 'not working'}) // View that renders the form(template is the html provided above) def signup(request): context ={} form = SignupForm() context['form'] = form return render(request, 'signup.html', context) The Message "It works" is displayed to the console, therefore the form is valid, however when performing print(form.cleaned_data.get("usernameVal")), I get returned None to the console. This means the … -
Filter Only Custom Permission for the model(Django)
I know i can filter list of the permissions for a specific modal using below orm Permission.objects.filter(content_type__app_label=app_name, content_type__model=model_name) but actually i want to filter custom model permissions and default modal permissions for the specific modal separately. for example default_permissions = some_orm custom_permissions = some_orm Here custom permissions means, permission defined by user inside Meta class of any model. -
Django InlineFormSet DeprecationWarning on can_delete = False
I'm trying to remove the Delete checkbox from the inlines. Let's say I have two models with one to one relation: models.py class Users(model.Models): .... class Extra_Fields(models.Models): user = models.OneToOneField(Users, on_delete=models.CASCADE) other_fields = .... I want a form to update both of the related object at once: class CustomInlines(InlineFormSet): model = Extra_Fields fields = ['custom_fields'] can_delete = False class CopywriterProfile(UpdateWithInlinesView): # boring stuff inlines = [CustomInlines] As you can say I'm using UpdateWithInlinesView. When I try to load the form I get the following error: DeprecationWarning at /profile/ Setting `CopywriterInline.can_delete` at the class level is now deprecated. Set `CopywriterInline.factory_kwargs` instead. I suggest to use factory_kwargs to set can_delete = False, but I didn't find any documentation. Someone can help me? -
Failed to add a object in a app in the admin panel of Django
I am just a beginner in Django Web Development.Following a tutorial I tried to add a object on a app by admin in Django. This is a screenshot before adding object. After clicking Save button I got the error. OperationalError at /admin/products/product/add/ no such table: main.auth_user__old Request Method: POST Request URL: http://127.0.0.1:8000/admin/products/product/add/ Django Version: 2.1 Exception Type: OperationalError Exception Value: no such table: main.auth_user__old Exception Location: C:\Users\royal\AppData\Local\Programs\Python\Python38-32\lib\site- packages\django\db\backends\sqlite3\base.py in execute, line 296 Python Executable: C:\Users\royal\AppData\Local\Programs\Python\Python38-32\python.exe Python Version: 3.8.2 Python Path: ['C:\\Users\\royal\\PycharmProjects\\PyShop', 'C:\\Users\\royal\\AppData\\Local\\Programs\\Python\\Python38-32\\python38.zip', 'C:\\Users\\royal\\AppData\\Local\\Programs\\Python\\Python38-32\\DLLs', 'C:\\Users\\royal\\AppData\\Local\\Programs\\Python\\Python38-32\\lib', 'C:\\Users\\royal\\AppData\\Local\\Programs\\Python\\Python38-32', 'C:\\Users\\royal\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages', 'C:\\Users\\royal\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages\\win32', 'C:\\Users\\royal\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages\\win32\\lib', 'C:\\Users\\royal\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\site-packages\\Pythonwin'] Server time: Tue, 24 Mar 2020 15:59:31 +0000 I'm completely new in this sector.Help me to get rid off this error. -
Python: Filter objects by Concat() and order by the same concatenation
In my Python/Django API project I need to get a quesryset from a model filtered by a concatenated combination of two fields and order by the same concatenation. However I only know to filter by one field like shown below. Requirement: TimeTable has two fields "date" and "time". I need to list data where the combination of both these fields are greater than current date time. Code: current_time = datetime.now() timetable = TimeTable.objects.filter(user=user_id, date__gte=current_time.date()).order_by(Concat('date','time')) How can I accomplish this? -
How to create a fillable and savable pop-up form in Django project?
How do I trigger a fillable pop-up when the user clicks on an image, on a Django web app that the winds up sorting the following result ? There many features that come after that as shown in here, that can wind up like that, and resulting on this final result, but so far I couldn't find a solution to that first step (my sole focus) on other websites. Is this something that can be done with HTML, CSS, and JS only, or do I have to use python to then save the data to the SQLite database ? If someone can suggest or hint at the steps that I need to follow to get this done I would really appreciate it. -
Why am I getting 'The requested URL / was not found on this server.' when deploying my django app?
I'm developing a django website and am currently working on deploying. I'm following this tutorial. And im in the last stage of the tutorial (1:08:00 in the video). After he finished configuration th django-project.conf file he saves and everything is working, but me on the other hand, i get an: Not Found The requested URL / was not found on this server. Apache/2.4.34 (Ubuntu) Server at **********.*** Port 80 This is my projects .conf file: <VirtualHost *:80> ServerName _ Redirect 404 / Alias /static /home/user/project/static <Directory /home/user/project/static> Require all granted </Directory> <Directory /home/user/project/project> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/user/project/project/wsgi.py WSGIDaemonProcess project_app python-path=/home/user/project python-home=/home/user/project/venv WSGIProcessGroup project_app </VirtualHost> What could I be doing wrong? Thanks in advance! -
problem with get_object_or_404() in my django views,py
i cant find what is the problem with my django code , when i post sth it returns -->No User matches the given query. this is my token model in db : class token(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) token = models.CharField(max_length = 48) def __str__(self): return "{}".format(self.user) and this is my views.py function: @csrf_exempt def home(request): if request.method == 'POST': token = request.POST['token'] current_user = get_object_or_404(User, token__token=token) return HttpResponse(current_user) else: return render(request, 'add.html') -
Cannot populate database table during Heroku deployment?
I have a django app that runs perfectly well on my local server. Unfortunately, when I deploy it onto Heroku, the behaviour doesn't work as expected. I can see that it's a database related issue as my dropdowns which are supposed to load a list of values from my database are empty in production. I have checked on Heroku in the 'Ressources' section of my application and there is a database; it also contains all my project tables (django default tables + my main table). All the django default tables are properly populated (I compared them with my local postgres tables and it matched). Unfortunately, my main table is empty on Heroku, whereas it is populated as expected locally. I'm not sure to understand what has gone wrong, especially considering that the table itself has been recognized, yet it is empty. I've applied the command heroku run python manage.py migrate but it didn't fix the issue. My guess is that my database settings are correct for local deployment but not for Heroku deployment. Nevertheless, I'm not sure at all. I've tried replacing my db settings by the user/host/password/name provided by Heroku but it didn't work. Any guidance will be much … -
Cannot use AWS SES to send email by Django application sit in AWS EC2
I have a Django application which sit in AWS EC2, i want to connect to AWS SES to send Email, so i followed this tutorial: https://kholinlabs.com/the-easiest-way-to-send-emails-with-django First , i created an EC2 instance in ap-southeast-1a avalibility zone, which the inbound and outbound rules are as following: inbound rule: HTTP TCP 80 0.0.0.0/0 All traffic All All 0.0.0.0/0 All traffic All All ::/0 SSH TCP 22 0.0.0.0/0 SMTPS TCP 465 0.0.0.0/0 SMTPS TCP 465 ::/0 HTTPS TCP 443 0.0.0.0/0 outbound rule: All traffic All All 0.0.0.0/0 All traffic All All ::/0 then i created Django application inside the server: django-admin startproject mysite python3 manage.py makemigrations python3 manage.py migrate add the following lines in setting file: EMAIL_BACKEND = 'django_ses.SESBackend' AWS_ACCESS_KEY_ID = 'secret' AWS_SECRET_ACCESS_KEY = 'secret' AWS_SES_REGION_NAME = 'ap-southeast-2' AWS_SES_REGION_ENDPOINT = 'email-smtp.ap-southeast-2.amazonaws.com' then i created an SES instance in ap-southeast-2 avalibility zone. inside EC2 server, i follow the tutorial and type commands: python3 manage.py shell from django.core.mail import send_mail send_mail( 'Subject here', 'Here is the message.', 'from@example.com', ['to@example.com'] ) but it stuck for very long time (around 10 mins) and then show timeout message. is there any step i missed? other info: for telnet: telnet email-smtp.ap-southeast-2.amazonaws.com 465 Trying 3.24.207.252... Connected to email-smtp.ap-southeast-2.amazonaws.com. Escape … -
Django Reverse Not Found when reversing a url in main app
I can not get my head around why this simple reverse() call for one of my Django-Views is not working. The error occurs in some of my tests: Reverse code snippet: # myapp/tests.py response = self.client.get(reverse('index', args=([element1],))) URL registry: # myapp/urls.py urlpatterns = [ path('', views.index, 'index'), path('configuration/', include('configuration.urls')), path('admin/', admin.site.urls), ] view: #myapp/views.py def index(request): elements_list = DB_ELEMENTS.objects.all() return render(request, "startpage.html", {'elements': elements_list}) The error I keep getting is Reverse for 'index' not found. 'index' is not a valid view function or pattern name. Any help appreciated. -
Integrate CoreUi React Template and python (Flask or Django)
I'm very new to CoreUi and I'm trying to connect CoreUi (Frontend) and Python (Backend) but everything I tried didnt work.. Does anyone of you know a good video or documentation which could help me ? I integrated React and Python (Flask) before in another project a couple of month before where I used this instruction from youtube: https://www.youtube.com/watch?v=YW8VG_U-m48&t=179s . I tried to integrate CoreUi and Flask the exact same way but it didnt work. I dont care if I use Django or Flask, I only want the connection to work... I also deleted the code where I tried to connect the frontend with the backend so I cant give you any code snippets or my webpack.config file. Hopefully anyone can give some instructions to simply connect the coreUi Template to python. I downloaded the coreUi template from GitHub (https://github.com/coreui/coreui-free-react-admin-template) -
Multiple databases using routers
I created an application with three apps account,Product and Post, i want to connect each app to different database but it is just not happening.Please tell me what i am doing wrong.This is the first time i am trying to use multiple databases. setting.py DATABASE_ROUTERS = ['account.router.AccountRouter', 'Post.router.PostRouter','Product.router.ProductRouter'] DATABASES = { 'default': {}, 'auth_db': { 'NAME': 'a_user', 'ENGINE': 'django.db.backends.postgresql', 'USER': 'postgres', 'PASSWORD': '1234', 'HOST':'localhost' }, 'account_db': { 'NAME': 'account', 'ENGINE': 'django.db.backends.postgresql', 'USER': 'postgres', 'PASSWORD': '1234', 'HOST':'localhost' }, 'post_db': { 'NAME': 'post', 'ENGINE': 'django.db.backends.postgresql', 'USER': 'postgres', 'PASSWORD': '1234', 'HOST':'localhost' }, 'product_db': { 'NAME': 'product', 'ENGINE': 'django.db.backends.postgresql', 'USER': 'postgres', 'PASSWORD': '1234', 'HOST':'localhost' } } Product/router.py class ProductRouter: """ A router to control all database operations on models in the auth and contenttypes applications. """ route_app_labels = {'Product',} def db_for_read(self, model): """ Attempts to read auth and contenttypes models go to product_db. """ if model._meta.app_label in self.route_app_labels: return 'product_db' return None def db_for_write(self, model): """ Attempts to write auth and contenttypes models go to product_db. """ if model._meta.app_label in self.route_app_labels: return 'product_db' return None def allow_relation(self, obj1, obj2): """ Allow relations if a model in the auth or contenttypes apps is involved. """ if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): …