Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to remove all connections from a group in channel layer | Django Channels
I want to use the channels groups as a lobby system for a game and when the game ends, remove everyone from the lobby but I'm unsure how to 1) iterate through users in the group, 2) remove all users or delete the group in total. -
File sharing and editing between users (google drive) in Django
How can I create a Django app where a user can create a document which the user can share with other users to read/write just like google docs. I found that WYSIWYG editors in Django where it enables the user to write content in the web browser. -
How to enable the users delete and edit comments they create in Django?
I am currently working on a blog app in django. I have almost done with it, but it is hard to deal with comments. Comments are posted but I do not know how to delete or edit it by the creators. models.py class BlogPost(models.Model): title = models.CharField(max_length=50, null=False, blank=False) body = HTMLField() date_published = models.DateTimeField(auto_now_add=True, verbose_name="date published") date_updated = models.DateTimeField(auto_now=True, verbose_name="date updated") author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) #featured = models.BooleanField() #categories = models.ManyToManyField(Category) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:detail', kwargs={ 'id': self.id, 'title': self.title }) @property def get_comments(self): return self.comments.all().order_by('date_updated') @property def comment_count(self): return Comment.objects.filter(blogpost=self).count() @property def view_count(self): return PostView.objects.filter(blogpost=self).count() class Comment(models.Model): content = models.TextField(max_length=5000, null=False, blank=False) date_published = models.DateTimeField(auto_now_add=True, verbose_name="date published") date_updated = models.DateTimeField(auto_now=True, verbose_name="date updated") author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) blogpost = models.ForeignKey('BlogPost', related_name='comments', on_delete=models.CASCADE) def __str__(self): return self.author.username class PostView(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey('BlogPost', on_delete=models.CASCADE) def __str__(self): return self.user.username The model above goes to the html below. detail_blog.html {% extends 'base.html' %} {% block content %} <style type="text/css"> .card{ max-width: 700px; } .card-body{ padding: 20px; } </style> <div class="container"> <div class="row"> <!-- Blog Post --> <div class="card m-auto"> <div class="card-body mt-2 mb-2"> <h2 class="card-title">{{blog_post.title}}</h2> <p class="card-text">{{blog_post.body|safe}}</p> {% if blog_post.author == request.user %} <a href="{% … -
Is there a way for logged in user to store the database in their own account in django?
I am working on a django project to store my daily expenses. models.py: class BudgetInfo(models.Model): items= models.CharField(max_length=20) cost= models.FloatField(blank=False, null=True) date_added= models.DateField() user= models.ForeignKey(User, on_delete= models.CASCADE) view.py: def login_view(request): if request.method == 'POST': form= AuthenticationForm(data=request.POST) if form.is_valid(): user=form.get_user() login(request,user) return render (request, 'tasks_notes/index.html') def additem_view(request): name = request.POST['expense_name'] expense_cost = request.POST['cost'] expense_date = request.POST['expense_date'] create=BudgetInfo.objects.create(user= request.user,items=name,cost=expense_cost,date_added=expense_date) create.save() return redirect('app') def signup_view(request): if request.method == 'POST': form= RegisterationForm(request.POST) if form.is_valid(): user=form.save() login(request,user) return redirect('login') else: form=RegisterationForm() return render(request, 'tasks_notes/signup.html',{'form':form}) forms.py: class RegisterationForm(UserCreationForm): email=forms.EmailField(required=True) class Meta: model=User fields=( 'username', 'first_name', 'last_name', 'email', 'password1', 'password2' ) def save(self, commit=True): user=super(RegisterationForm, self).save(commit=False) user.first_name=self.cleaned_data['first_name'] user.last_name=self.cleaned_data['last_name'] user.email=self.cleaned_data['email'] if commit: user.save() return user I want to store the daily expense of each user in its own model. But every instance (even with the same user) is created whenever I am trying to save the data. I want a single instance of the model for each user. How can I achieve it? -
django: How can display in the same url form and table?
I'm learning to programming in django. For the moment I'm building a simple app that utilizing a form update the referenced table. All works untill I assign two different urls for table and forms, but If I try to merge them togheter in the same url (utilizing so the same html file) django give me the following error: ValueError at / Expected table or queryset, not str Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.1.5 Exception Type: ValueError Exception Value: Expected table or queryset, not str Above my code in each file of my project: urls from django.urls import path from app import views urlpatterns = [ path('', views.homepage, name='homepage'), path('', views.PersonListView.as_view(), name='algo'), ] forms from django import forms from .models import Income class IncomeModelForm(forms.ModelForm): class Meta: model = Income fields = "__all__" tables import django_tables2 as tables from .models import Income class PersonTable(tables.Table): class Meta: model = Income template_name = "django_tables2/bootstrap.html" views from django.shortcuts import render from django.http import HttpResponse from django.views.generic import ListView from .models import Income from .tables import PersonTable from django_tables2 import SingleTableView from .forms import IncomeModelForm def homepage(request): if request.method == 'POST': form = IncomeModelForm(request.POST) if form.is_valid(): print("Il form è valido") new_post = form.save() … -
Python Django Linking problems
I am working on an online school project, I just linked subjects, with classes so when you click on a class you get it's subjects page, and in the subject page there are lessons playlist(playlist use IDs not slugs),in the playlist you will get a list of lessons My problem is at linking the lesson URL in the HTML page so my question is How to link lessons to lessons to the playlist in the HTML page? My codes: HTML PAGE: <!DOCTYPE html> <html> {% load static %} <head> <meta charset="utf-8"> <title>Name</title> <link rel="stylesheet" href="/static/css/style.css"> </head> <body> <div> <nav> <div class="logo"><img src="/static/images/Logo.png" width=50px></div> <ul class="navul"> <li class="navli"><a class="nava" href="404.html">حول الموقع</a></li> <li class="navli"><a class="nava" href="404.html">المكتبة</a></li> <li class="navli"><a class="nava" href="404.html">الدورات</a></li> <li class="navli"><a class="nava" href="/classes">الصفوف</a></li> <li class="navli"><a class="nava" href="/">الصفحة الرئيسية</a></li> <button class="bt1"><a href="/signup">انشاء حساب</a></button> </ul> </nav> {% for list in list.all %} <div class="div1"> <img src="/static/images/Logo.png" width="90" class="logo2"> <h1 class="t1">{{list.title}}</h1> </div> <li><a href="#"> HelloWorld </a></li> {%endfor%} {% for lesson in lesson._set.all %} <li><a href="{% url 'lessons' classes.id list.id lesson.id %}">World1</a></li> {% endfor %} </div> </body> </html> MODELS.py: from django.db import models from users.models import * # Create your models here. class Class(models.Model): image= models.ImageField(upload_to="images") name= models.CharField(max_length=200, default=1) title= models.CharField(max_length=200) def __str__(self): return self.title … -
How to raise exceptions in Django view based in ORM exceptions
Instead of doing, for example this: views.py: my_noob_way(request): object = Object.objects.filter(name=request.POST.get('name', None)) if not object: Object.objects.create(name=request.POST.get('name', None)) data = {'success': True, 'message': 'Object successfully created.'} else: data = {'success': False, 'message': 'Object already exists.'} return JsonResponse(data) Instead of doing this, I want to avoid the filter line (extra garbage query) and just performing a create inside a try and catch the possible duplication exception with except. How can I make this? I don't know what to put after except: (Too broad exception clause). -
Nginx try_files not working with domain that appends trailing slash
I have a dockerised Django app where nginx uses proxy_pass to send requests to the Django backend. I am looking to pre-publish certain pages that dont change often so Django doesnt have to deal with them. I am trying to use try_files to check if that page exists locally and pass to Django if not. Our URL structure requires that all URLs end with a forward slash and we dont use file type suffixes e.g. a page might be www.example.com/hello/. This means the $uri param in nginx in this instance is /hello/ and when try_files looks at that it is expecting a directory due to the trailing slash. If I have a directory with a list of files how do I get try_files to look at them without re-writing the URL to remove the slash as Django requires it? My nginx conf is below. server { listen 443 ssl http2 default_server; listen [::]:443 ssl http2 default_server; server_name example.com; root /home/testuser/example; location / { try_files $uri uri/ @site_root; } location @site_root { proxy_pass http://127.0.0.1:12345; } } If I have a file "hello" at /home/testuser/example/hello and call https://www.example.com/hello/ how can I get it to load the file correctly? P.S. the permissions on … -
Error in Channel library OSError: [WinError 123]
when i am installed "channels"library in settings.py at installed app i get this error plz anyone find my resolve error File "c:\program files (x86)\python38-32\Lib\pathlib.py", line 200, in resolve return self._ext_to_normal(_getfinalpathname(s)) OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: '' -
How to resolve a ManyRelatedManager error
While working with django 3.0, passing a context from the view to a template became confusing to me. I don't know whether there has been a change in the method. I did this in models.py from tinymce import HTMLField from django.db import models from django.contrib.auth import get_user_model from django.urls import reverse user = get_user_model() class Author(models.Model): user = models.OneToOneField(user, on_delete=models.CASCADE) thumbnail = models.ImageField() def __str__(self): return "%s %s" % (self.user.username) class Category(models.Model): title = models.CharField(max_length=250) def __str__(self): return (self.title) class Post(models.Model): title = models.CharField(max_length=250) overview = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) content = HTMLField() comment_count = models.IntegerField(default=0) view_count = models.IntegerField(default=0) author = models.ForeignKey(Author, on_delete=models.CASCADE) thumbnail = models.ImageField() categories = models.ManyToManyField(Category) featured = models.BooleanField() def __str__(self): return self.title class Meta: verbose_name ='The post' verbose_name_plural = 'posts' def get_absolute_url(self): return reverse('post-detail', kwargs={ 'id':self.id }) and this is the view.py file def post(request, id): post = get_object_or_404(Post, id=id) context = { 'post':post } return render(request, 'post.html', context ) and am getting this error TypeError at /post/1/ 'ManyRelatedManager' object is not iterable Request Method: GET Request URL: http://127.0.0.1:8000/post/1/ Django Version: 3.0.4 Exception Type: TypeError Exception Value: 'ManyRelatedManager' object is not iterable what should i do -
How I can set frontend of html to Django CMS login page that can redirect to login page of Django CMS?
I want to redirect my user from my html frontend and there after they must see dajngo CMS login page. Please anyone tell how to do? My html code contains admin panel How to do? -
Issue in starting Django server
I followed the instructions given on Django docs and did the following: django-admin startproject mysite cd mysite python3 manage.py runserver I get the following error : File "/home/dox/.local/lib/python3.6/site-packages/django/template/utils.py", line 66, in __getitem__ return self._engines[alias] KeyError: 'django' My Django version is 3.0.4 -
my template is broken and cannot get static files
my template didn't work and can't get static files but I did everything. my static folder is in the Base directory but when I'm trying to reach static files, for example, CSS or js I'm getting file not found error and template is broken. my file Tree for project this is an image of my folder and project tree Settings for Static and media. STATIC_URL = '/temfiles/' MEDIA_URL = '/mediafiles/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'static/uploads/') X_FRAME_OPTIONS = 'SAMEORIGIN' my project URL file urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), path('froala_editor/', include('froala_editor.urls')) ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my app URL file urlpatterns = [ path('', views.index, name = 'index'), path('<slug:slug>/', views.post_detail, name='Post Detail') ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my Views File def index(request): Post_list = BlogPost.objects.all() template_name = 'front/index.html' return render(request, template_name,{"Post_list":Post_list}) def post_detail(request): return render(request, 'front/post_detail.html') my base template CSS example {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'front/css/style.css' %}"> -
ModuleNotFoundError: No module named 'posts.urls'
I'm starting with Django by seeing a tutorial, when I start editing urls.py, I start giving these errors: Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\salva\appdata\local\programs\python\python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "c:\users\salva\appdata\local\programs\python\python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Salva\mydjangoblog\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\Salva\mydjangoblog\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\Salva\mydjangoblog\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = self._run_checks( File "C:\Users\Salva\mydjangoblog\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\Salva\mydjangoblog\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\Salva\mydjangoblog\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Salva\mydjangoblog\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Salva\mydjangoblog\lib\site-packages\django\urls\resolvers.py", line 407, in check for pattern in self.url_patterns: File "C:\Users\Salva\mydjangoblog\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Salva\mydjangoblog\lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Salva\mydjangoblog\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Salva\mydjangoblog\lib\site-packages\django\urls\resolvers.py", line 581, in urlconf_module return import_module(self.urlconf_name) File "c:\users\salva\appdata\local\programs\python\python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, … -
Update form creates new object in Django
I have a Trip model and created a form so it updates existing trips. models.py: class Trip(models.Model): trip_id = models.CharField(max_length=20, verbose_name="Ref. Viagem") destination = models.CharField(max_length=200, null=True, verbose_name='Destino') client = models.ForeignKey(Clients, null=True, on_delete=models.CASCADE, verbose_name="Cliente") out_flight = models.ForeignKey(Flight, related_name="outbound_flight" ,null=True, on_delete=models.SET_NULL, verbose_name="Voo Ida") hotel = models.ForeignKey(Hotels, null=True, on_delete=models.SET_NULL, verbose_name="Hotel") in_flight = models.ForeignKey (Flight, related_name="inbound_flight", null=True, on_delete=models.SET_NULL, verbose_name="Voo Regresso") forms.py: class UpdateTrip(ModelForm): def __init__(self, *args, **kwargs): super(UpdateTrip, self).__init__(*args, **kwargs) self.fields['trip_id'].widget = TextInput(attrs={'class': 'form-control'}) self.fields['destination'].widget = TextInput(attrs={'class': 'form-control'}) self.fields['client'].queryset = Clients.objects.all() class Meta: model = Trip fields = ('trip_id', 'destination', 'client', 'out_flight', 'hotel', 'in_flight') And this is the views.py for it: def trip_upd(request, trip_id): if request.method == 'POST': form = UpdateTrip(request.POST) if form.is_valid(): form.save() return redirect('trips') else: form = UpdateTrip() return render(request, 'backend/trip_update.html', {'form': form}) I am using a barebones form while testing: <form method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> Now, this doesn't update the objects but creates a new one. -
Django application using matlab.engine in python script failing when deploying on aws using elastic beanstalk
I am deploying my django application on aws using elastic beanstalk. I have setup virtual python environment and its using matlab.engine inside python script. Its running perfectly on my ec2 but when I use eb deploy coomand it shows below error. I have put error logs below. [2020-03-07T18:51:26.604Z] INFO [10873] - [Application update app-200307_185106@172/AppDeployStage0/AppDeployPreHook/03deploy.py] : Starting activity... [2020-03-07T18:51:27.509Z] INFO [10873] - [Application update app-200307_185106@172/AppDeployStage0/AppDeployPreHook/03deploy.py] : Activity execution failed, because: Requirement already satisfied: certifi==2019.11.28 in /opt/python/run/venv/lib/python3.6/site-packages (from -r /opt/python/ondeck/app/requirements.txt (line 1)) Requirement already satisfied: chardet==3.0.4 in /opt/python/run/venv/lib/python3.6/site-packages (from -r /opt/python/ondeck/app/requirements.txt (line 2)) Requirement already satisfied: defusedxml==0.6.0 in /opt/python/run/venv/lib/python3.6/site-packages (from -r /opt/python/ondeck/app/requirements.txt (line 3)) Requirement already satisfied: Django==2.1.1 in /opt/python/run/venv/lib/python3.6/site-packages (from -r /opt/python/ondeck/app/requirements.txt (line 4)) Requirement already satisfied: django-paypal==1.0.0 in /opt/python/run/venv/lib/python3.6/site-packages (from -r /opt/python/ondeck/app/requirements.txt (line 5)) Requirement already satisfied: idna==2.8 in /opt/python/run/venv/lib/python3.6/site-packages (from -r /opt/python/ondeck/app/requirements.txt (line 6)) Collecting matlabengineforpython===R2018b (from -r /opt/python/ondeck/app/requirements.txt (line 7)) Could not find a version that satisfies the requirement matlabengineforpython===R2018b (from -r /opt/python/ondeck/app/requirements.txt (line 7)) (from versions: ) No matching distribution found for matlabengineforpython===R2018b (from -r /opt/python/ondeck/app/requirements.txt (line 7)) You are using pip version 9.0.1, however version 20.0.2 is available. You should consider upgrading via the 'pip install --upgrade pip' command. 2020-03-07 18:51:27,502 ERROR Error installing dependencies: Command … -
DRF ModelViewSet queryset return results that their date is greater than or equal to today
I am using Django Rest Framework. In the queryset I'm trying to filter my objects based on IF their Date is greater than or equal to today. Like so: class DateViewSet(viewsets.ModelViewSet): """ API Endpoint to retrieve all dates after today. """ serializer_class = DateSerializer today = datetime.date.today() queryset = EventDate.objects.filter(end_date__gte=today) But this ends up showing the past dates as well. my serializer: class DateSerializer(serializers.ModelSerializer): class Meta: model = EventDate fields = ('start_date', 'end_date') And then I pass it on to the Event Serializer: class EventSerializer(serializers.HyperlinkedModelSerializer): id = serializers.StringRelatedField() dates = DateSerializer(many=True, read_only=True) class Meta: model = Event fields = '__all__' extra_kwargs = { 'url': {'lookup_field': 'slug'}, } My goal is when my API returns all events it should not return all dates that have been in the past. What am I doing wrong? -
31/5000 connecting django with postgresql
how to connect postgres to the django project? when trying to connect I get the error "django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2" When installing psycopg2 you get the error "Command" python setup.py egg_info "failed with error code 1 in / tmp / pip-install-xntnhxcd / psycopg2 /" Error: You need to install postgresql-server-dev-NN for building a server-side extension or libpq-dev for building a client-side applicati when installing "sudo apt install libpg-dev" Reading package lists ... Done Building a dependency tree Reading status information ... Ready E: The libpg-dev package could not be found -
python django only the first statement statement can be accessed
i can acccess only the first statement in my name app javascript: <script type="text/javascript"> function searched(){ {% for names in name %} nameSearched = document.getElementById('name').value; document.getElementById('dis').innerHTML = nameSearched; if (nameSearched == "{{ names.First }}" ){ document.getElementById('dis').innerHTML = "{{ names.Last }}"; } else { document.getElementById('dis').innerHTML = "none"; } {% endfor %} } </script> -
hashtag signal is not working properly in the update view
I have successfully take the @username hashtagging part in the new post form whenever i update that with another content of @username its not giving the user any signals. And i'm using django-notifications to notify the user. i'm using django claassbased update view. my models.py: class post(models.Model): parent = models.ForeignKey("self", on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(max_length=100) image = models.ImageField(upload_to='post_pics', null=True, blank=True) video = models.FileField(upload_to='post_videos', null=True, blank=True) content = models.TextField() likes = models.ManyToManyField(User, related_name='likes', blank=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) objects = postManager() def __str__(self): return self.title class Meta: ordering = ['-date_posted', 'title'] def get_absolute_url(self): return reverse ('blog-home') def total_likes(self): return self.likes.count() def post_save_receiver(sender, instance, created, *args,**kwargs): if created and not instance.parent: user_regex = r'@(?P<username>[\w.@+-]+)' m = re.search(user_regex, instance.content) if m: try: recipient = User.objects.get(username=m.group('username')) except (User.DoesNotExist, User.MultipleObjectsReturned): pass else: notify.send(instance.author, recipient=recipient, actor=instance.author, verb='mention you in a post', target=instance, nf_type='tagged_by_one_user') post_save.connect(post_save_receiver, sender=post) and my updateview in views.py: class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = post fields = ['content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False def update_save_receiver(sender, post, created, *args,**kwargs): if created and not post.parent: user_regex = r'@(?P<username>[\w.@+-]+)' m = re.search(user_regex, post.content) if m: try: recipient … -
Session variable set before request is not accessible in Django view during tests
I need to store a kind of state between HTTP requests. Because I don't use the JS frontend, I decided to use session variables stored in cookies. My session settings look like below: SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies" SESSION_COOKIE_HTTPONLY = False I need a function to easily manipulate one session variable. Because this functionality is quite simple, I decided to exceptionally use function-based view: def set_category_filter(request, pk): if pk == 0: if 'filter_category_id' in request.session: # this is False during unit testing, but it's ok in a normal app run del request.session['filter_category_id'] else: get_object_or_404(Category, pk=pk, user=request.user) request.session['filter_category_id'] = pk return redirect('index') The problem is I cannot test case when I want to unset this session variable. Suppose the session variable filter_category_id is set and I want to reset it. When I do this in my browser, everything works okay. When I try to do this via Django TestCase, it fails, because this session variable is not passed to request! class SetCategoryFilterTest(TestCase): def setUp(self) -> None: super().setUp() self.fake = Faker() self.user = User.objects.create_user(username="testuser", password="12345") self.client.force_login(self.user) def tearDown(self): self.client.logout() # ... def test_unset_successfully(self): """Werify unsetting "filter_category_id" session field. Expected: Delete "filter_category_id" when url called with parameter 0 """ # GIVEN session = self.client.session session['filter_category_id'] … -
How import everything from designated module without get error of flake8
I want to split my settings.py in django project so I do: # within __init__py from .app import * try: from .app.local_settings import * except ImportError: pass But I get this error from flake8: 'from .app import *' used; unable to detect undefined namesflake8(F403) '.app.*' imported but unusedflake8(F401) How can I solve it? When I used of importlib.import_module I got The SECRET_KEY setting must not be empty error because the 'SECRET_KEY` inserted into the object that returned from importlib.import_module. -
Django form not submitting on post
I have django form that is not submitting upon clicking Submit. I try to click on the button to submit the information nothing happens. No errors or messages of any kind show up in terminal or in developer in Chrome. There is no JS on this page just straight html: I used the same approach on the a different project but for this it doesn't work. What could be the issue with my code. models.py class Department(models.Model): depart_code = models.CharField(max_length=20,unique=True) depart_name = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return self.depart_name views.py class DepartmentAddView(CreateView): model = Department form_class = DeptAddForm template_name = 'hrms/department_form.html' def form_valid(self, form): form.save() return redirect('/') forms.py class DeptAddForm(forms.ModelForm): depart_name = forms.CharField( max_length=100, widget=forms.TextInput( attrs={ 'class': 'span8', } ), label = "*Department Name", ) departt_code = forms.CharField( max_length=100, widget=forms.TextInput( attrs={ 'class': 'span8', } ), label = "*Department Code", ) class Meta: model = Department fields = ['depart_code', 'depart_name'] hrms/department_form.html <form class="form-horizontal row-fluid" method="POST">{% csrf_token %} <div class="control-group"> <label class="control-label" for="basicinput">Department Code</label> <div class="controls"> {{ form.depart_code }} </div> </div> <div class="control-group"> <label class="control-label" for="basicinput">Department Name</label> <div class="controls"> {{ form.depart_name }} </div> </div> <div class="control-group"> <div class="controls"> <button type="submit" class="btn-success">Submit Form</button> </div> </div> </form> -
How to get Django models data in python script variables?
I want to get the data stored in django models dynamically into my python script. But so far I have not found any solution. I'm new to django so would appreciate the help. -
Make a ForiegnKey to an unknown model in django
I'll illustrate by example I have class Stone(models.Model): # name, color, whatever class Member(models.Model): # whatever class Image(models.Model): stone = models.ForiegnKey(Stone, on_delete=...) # this should have the model that needs images image = models.ImageField() I'm using a foriegnKey to the Image model to make multiple images, But This forces me to create an Image model for each Model, In my example, Stone can has multiple images right? I want Member and all my models that need images to use the same class, I want to make only one images table. I've been searching for a while but I don't think I know what should be the search text, I read about ContentType but I don't think I understand what it does and I don't even know if it's the what I'm asking for.