Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does heroku say no module found on profile read
I am tryning to deploy a app. But I am getting the following error.I think this might have something to do with wsgi file path location. I am getting this error: 2018-12-22T13:31:42.980813+00:00 app[web.1]: Traceback (most recent call last): 2018-12-22T13:31:42.980815+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2018-12-22T13:31:42.980817+00:00 app[web.1]: worker.init_process() 2018-12-22T13:31:42.980818+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 129, in init_process 2018-12-22T13:31:42.980820+00:00 app[web.1]: self.load_wsgi() 2018-12-22T13:31:42.980821+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi 2018-12-22T13:31:42.980823+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2018-12-22T13:31:42.980824+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi 2018-12-22T13:31:42.980826+00:00 app[web.1]: self.callable = self.load() 2018-12-22T13:31:42.980827+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load 2018-12-22T13:31:42.980829+00:00 app[web.1]: return self.load_wsgiapp() 2018-12-22T13:31:42.980830+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp 2018-12-22T13:31:42.980832+00:00 app[web.1]: return util.import_app(self.app_uri) 2018-12-22T13:31:42.980834+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 350, in import_app 2018-12-22T13:31:42.980835+00:00 app[web.1]: __import__(module) 2018-12-22T13:31:42.980841+00:00 app[web.1]: ModuleNotFoundError: No module named 'EIIIFeedback' enter image description here My pr0ject structure is: my Procfile is : web: gunicorn EIIIFeedback.wsgi:application -
objects = MyCustomManager() TypeError: 'module' object is not callable
I am customizing User class of my django project. I've write a User class inherits from AbstractBaseUser, and UserManager class inherits from BaseUserManager. the problem is when i try o assign objects of User Class to UserManager(), i get this error: (actually error happens when I try to make migrations, or create super user) objects = UserManager() TypeError: 'module' object is not callable any help is appreciated. This is my User Class: from __future__ import unicode_literals from django.db import models from django.core.mail import send_mail from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.base_user import AbstractBaseUser from django.utils.translation import ugettext_lazy as _ from django.core.validators import RegexValidator from .managers import UserManager class User(AbstractBaseUser, PermissionsMixin): phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="") phone_number = models.CharField(validators=[phone_regex], unique=True) email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) is_active = models.BooleanField(_('active'), default=True) avatar = models.ImageField(upload_to='avatars/', null=True, blank=True) objects = UserManager() USERNAME_FIELD = 'phone_number' REQUIRED_FIELDS = [] class Meta: verbose_name = _('user') verbose_name_plural = _('users') def get_full_name(self): ''' Returns the first_name plus the last_name, with a space in between. ''' full_name = '%s %s' % (self.first_name, self.last_name) return full_name.strip() def get_short_name(self): ''' Returns the short name for the user. ''' … -
access DB when i use LOGOUT_REDIRECT_URL tp load a template's HTML
im noob in django, javascript and ... . i know how access to DB information when i'm using render with Views.py but now i using LOGIN_REDIRECT_URL = 'home' and now in home.html i need to use DB information for continue.i can't access to models.Blog.address to use for action="blogregisd/<!--models.Blog.address -->/".i try with jquery and python code in HTML but it doesnt work. sry if my english language is week. tnx try to found how i can access to dynamic action's url in from attribute when i dont come from app's Views. in URL i have: urlpatterns = [ path('', TemplateView.as_view(template_name='home.html'), name='home'), path('admin/', admin.site.urls), path('users/', include('app.urls')), path('accounts/', include('django.contrib.auth.urls')), path('blogregisd/<str:blog_id>/', views.blogRegistered, name='blogRegister'), ] models: class Blog(models.Model): address = models.CharField(max_length=100, verbose_name="ادرس سایت", null=True) password = models.CharField(max_length=100, verbose_name="پسورد" , null=True) owner = models.OneToOneField(AUTH_USER_MODEL, on_delete=models.CASCADE , null=True ,verbose_name="صاحب بلاگ") def __str__(self): return self.address class Post(models.Model): title = models.CharField(max_length=50, verbose_name="عنوان") text = models.TextField(verbose_name="متن") author = models.ForeignKey(AUTH_USER_MODEL, verbose_name="مولف", null=True, blank=True, on_delete=models.CASCADE) blog = models.ForeignKey(Blog, on_delete=models.CASCADE , verbose_name="در بلاگ") def __str__(self): return self.title HTML home.html: {% block content %} {% if user.is_authenticated %} welcome{{ user.username }}! <form method="post" id="registerform" action="/blogregisd/{{ Blog.address }}/"> {% csrf_token %} <input type="text" id="blogRegisterValue" name="BlogRegister"> <button type="submit" id="blogRegistereButton">ثبت بلاگ</button> </form> <p><a href="{% url 'logout' %}">logout</a></p> … -
Booleans as checkboxes and saving the form
I have created a OnetoOne model for some user preference checkboxes. This is mapped to the User, and using signals I create it when the user is created. Here is what I have so far: Model: `class DateRegexes(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) prefix_1 = models.NullBooleanField() prefix_2 = models.NullBooleanField() prefix_3 = models.NullBooleanField() prefix_4 = models.NullBooleanField() prefix_5 = models.NullBooleanField() prefix_6 = models.NullBooleanField() prefix_7 = models.NullBooleanField() prefix_8 = models.NullBooleanField() prefix_9 = models.NullBooleanField() @receiver(post_save, sender=User) def create_date_regexes(sender, instance, created, **kwargs): if created: DateRegexes.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_date_regexes(sender, instance, **kwargs): instance.date_prefs.save()` Form: `class DatePreferenceForm(forms.ModelForm): class Meta: model = DateRegexes` View: `@login_required def set_date_preferences(request): if request.method == 'POST': form = DatePreferenceForm(request.POST) if form.is_valid(): form.save() else: date_prefs = get_object_or_404(DateRegexes, user=request.user) form = DatePreferenceForm(instance = request.user.date_prefs) return render(request, 'set_date.html', {'form': form})` Template: `{% extends 'base.html' %} {% block title %}Date Preferences{% endblock %} {% block content %} {% if user.is_authenticated %} <p><a href="{% url 'logout' %}">logout</a></p> <form method="post"> {% csrf_token %} {% for field in form.visible_fields %} <div>here {{ field }}</div> {% endfor %} <button type="submit">Set</button> </form> </div> {% else %} <p>You are not logged in</p> <a href="{% url 'login' %}">login</a> {% endif %} {% endblock %}` When I execute this, the first thing that happens is that … -
Django won't connect to MySQL
After spending hours finding the correct connectors to hook up MySQL with Django, I can't create a super user. error: django.db.utils.OperationalError: (2059, "Authentication plugin 'caching_sha2_password' cannot be loaded: The specified module could not be found.\r\n") I tried setting environment variables, settings.configure() which said the settings were already configured. db info is all correctly entered in settings.py. Pycharm is able to connect to the db though, this is inside my django project and the db title in pycharm says Django default. I don't know if this means my Django project is connected to it but I just can't create a super user or that the pycharm connection is not related. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dbname', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': 3306 } } When i try django-admin dbshell I get this error: django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Both solutions provided in the error have had no positive result. My last question got marked as duplicate although the solution didn't work, the question was also different in some ways.. anyway below is what happened when I tried using … -
Django Channels producer consumer problem not working properly
I wrote django channels code to send api data from two different sources asynchronously. The different sources takes few seconds to 1 minute to compute and send back the data. I managed to call them asynchronously using asyncio event loop. But the issue is that they are not sending the resposne back asynchronously. The code just waits for the all the data to arrive and sends everything at the same time. Channels Code: class SearchHotelConsumer(AsyncWebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.source1 = Source1() self.source2 = Source2() async def connect(self): await self.accept() def disconnect(self, close_code): pass async def _source1_handler(self, request, queue): source1_response = await self.source1.async_post(request) await queue.put(source1_response.data) async def _source2_handler(self, request, queue): source2_response = await self.source2.async_post(request) await queue.put(source2_response.data) async def _send_msg(self, queue): while True: message = await queue.get() if message is None: break print('got the message') self.send(text_data=json.dumps({ 'message': message }, cls=DjangoJSONEncoder)) queue.task_done() def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] request = HttpRequest() request.method = 'POST' request.session = self.scope["session"] request = Request(request) for key, val in message.items(): request.data[key] = val queue = asyncio.Queue() sender = asyncio.ensure_future(self._send_msg(queue)) await self._source1_handler(request, queue) await self._source2_handler(request, queue) await queue.join() sender.cancel() How can I make the message sending part truly asynchronous? -
Is it good practice to call model methods inside other model methods in Django?
I'm trying to write my code as "Pythonic" as possible in Django. Consider the following model: class MyRequest(models.Model): ... def get_prices(self): ... def set_costs(self): ... def get_details(self): self.set_costs() x = self.get_prices() return x % 10 Is it good practice to call model methods inside each other? -
Using angular js post to django back end yields a 414 error
var reader = new FileReader(); reader.onload = function(){ var fileData = reader.result; $http({ url: 'rs/submit', method: 'POST', data: { 'img': fileData, 'query': query, 'limit': limit } }) .then(function successCallback(response) { }, function errorCallback(response) { }); }; reader.readAsDataURL(document.getElementById('submitFileInput').files[0]); I'm trying to send a image to my django back end using angular js as you can see above, but I get a error in the back end that says: [22/Dec/2018 12:59:34] "POST /dynamic-mosaic/rs/submit HTTP/1.1" 200 4 [22/Dec/2018 12:59:34] code 414, message Request-URI Too Long [22/Dec/2018 12:59:34] "" 414 - I thought POST can send requests of almost any size, the image isnt even that big like 1-2MB Anyone knows the cause? Maybe I'm not using angular js $http service properly. -
AttributeError at /pro/bill/8/pdf/ 'decimal.Decimal' object has no attribute 'get'
i want to print the details from the data of a model object in to pdf i have googled a lot to make sure if someone has faced this issue earlier but most of the answers i have found aren't a solution for my issue class Direct(models.Model): type=models.CharField(max_length=128,null=True,blank=True) name=models.CharField(max_length=128) price=models.IntegerField() meters=models.DecimalField(null=True,blank=True,max_digits=5, decimal_places=2) discount=models.IntegerField(null=True) phone_number=models.BigIntegerField(null=True) type2=models.CharField(max_length=128,null=True,blank=True) meters2=models.DecimalField(null=True,blank=True,max_digits=5, decimal_places=2) price2=models.IntegerField(null=True,blank=True) discount2=models.IntegerField(null=True,blank=True) views.py def admin_order_pdf(request, order_id, *args, **kwargs): queryset=D.objects.all() # serializer= # order=D.objects.get(order_id) order = get_object_or_404(queryset, id=order_id) type=order.type price=order.price meters =order.meters price=price*meters discount=order.discount total=price-discount type2=order.type2 price2=order.price2 meters2=order.meters2 if price2 != None: price2=price2*meters2 return price2 else: price2=None discount2=order.discount2 if discount2 != None: total2=price2-discount2 return total2 else: discount2=None total2=None # print() template=get_template('bill/b.html') data={ 'order': order,'total':total,'type':type,'price':price,'meters':meters,'discount':discount,'type2':type2,'price2':price2,'discount2':discount2,'total2':total2,'meters2':meters2 } html = render_to_pdf('bill/b.html', data) return HttpResponse(html, content_type='application/pdf') whenever i there are two products then the type2 product will retur the value to the context and lateron can be used in templates but if there is only product then the type2 should return None so that i can ignore this type 2 in my html using django template filters -
what are the attributes(?) of user.username?
Where can I find the documentation on the attributes(is that what it's called?) of the user model fields? I'm using the UserPassesTestMixin, and I want to include 3 different usernames to pass the test. I'm also doing a {% if user.username %} code in the HTML that includes the same 3 usernames. But I don't know how to do it class StaffAutho(UserPassesTestMixin): def test_func(self): return self.request.user.username.includes('staff1', 'staff2', 'staff3') this is the html: {% if user.username == 'tim' %} <li class="nav-item pl-3"> <a class="btn btn-primary" role="button" href="/productadmin">Admin</a> </li> {% endif %} -
Django reset password return 127.0.0.1:800 instead domain name
In my django project i implement forgot password link: path('accounts/', include('django.contrib.auth.urls')), I have an nginx server configured like this (in location part): location /static/ { alias /var/www/web/core/frontend/static/; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; #add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; proxy_set_header X-DTS-SCHEMA $subdomain; proxy_redirect http:// https://; } i run my app using runserver with nohup (gunicorn and uWsgi does not work for my purposes) nohup python manage.py runserver & Now, when i call the reset password page (/accounts/password_reset/) and insert my email address, i get the email with link for reset password but the domain part of the link is 127.0.0.1:8000 instead the domain name. How can i ask to django using currend domain instead 127.0.0.1:8000? So many thanks in advance -
Django messages not showing after Jquery redirect
i have a view def approval(request, id): if request.method == "POST": messages.add_message(request, messages.INFO, 'You have activity was recorded') return HttpResponse({"success": "ok"}) else: return HttpResponse(request.method + " not allowed") An ajax call to the view above looks like $.ajax({ url: url, type: "POST", data: {"comment": comment, csrfmiddlewaretoken: '{{ csrf_token }}'}, success: function (data) { location.href = "/redirect_url/"; } }); However, the message is not visible on the jquery url /redirect_url. -
Saving data fails because of null constraint when data is not null
I have the following python code in django which is deployed on heroku: def newimportdb(request): import xlrd loc = ("./CGHS Rates 2014- Trivandrum.xlsx") wb = xlrd.open_workbook(loc) sheet = wb.sheet_by_index(0) for i in range(sheet.nrows): try: sl = int(sheet.cell_value(i, 0)) except: title = sheet.cell_value(i, 1) hd = CGHSSection(title = title) try: hd.save() heading = CGHSSection.objects.get(title = title) print(f"Saved new heading: {title}") continue except: print(f"Could not save new section: {title}. Maybe it existing. Reading it.") heading = CGHSSection.objects.get(title = title) continue test = sheet.cell_value(i, 1) nonnabh = int(sheet.cell_value(i, 2)) nabh = int(sheet.cell_value(i, 3)) print(f'{i} Test:{test} NonNABH:{nonnabh} NABH:{nabh} Under:{heading}') it = CGHSRates(serial = sl, name =test, NABHrate = nabh, NonNrate=nonnabh, section=heading) print(f"Value of section heading is {heading.title}") print(f'it = CGHSRates(serial = {sl}, name ={test}, NABHrate = {nabh}, NonNrate={nonnabh}, section={heading}') it.save() print("Saved") In my models, I have: from django.db import models class CGHSRates(models.Model): rid = models.AutoField(primary_key=True) serial = models.IntegerField(default=0) name = models.CharField(max_length=100) NonNrate = models.FloatField(blank=True) NABHrate = models.FloatField(blank=True) section = models.ForeignKey('CGHSSection', on_delete=models.SET_NULL, null=True, blank=True) class Meta: unique_together = ('name', 'NonNrate', 'NABHrate') class CGHSSection(models.Model): num = models.AutoField(primary_key=True) title = models.CharField(max_length=150, unique=True) On running the above, I get: [22/Dec/2018 09:07:55] "GET /favicon.ico/ HTTP/1.1" 404 3346 Could not save new section: UNCLASSIFIED. Maybe it existing. Reading it. 1 … -
Django Rest Framework File Upload Says Document Not Submitted
When I upload a file through requests module it says no document submitted models.py class Apidocument(models.Model): iden = models.CharField(max_length=255) document = models.FileField(upload_to='media/documents') uploaded_at = models.DateTimeField(auto_now_add=True) serializer.py class DataSerializer(serializers.ModelSerializer): document = serializers.FileField(max_length=None,use_url =True) class Meta(): model = Apidocument fields = ('uploaded_at','document') views.py class ApiViewSet(viewsets.ModelViewSet): queryset = Apidocument.objects.all().order_by('-uploaded_at') serializer_class = DataSerializer files = {"file": ('b839', open('/home/user/b839.jpeg', 'rb'), 'multipart/form-data')} resp = requests.post('http://localhost:8000/api/upload/', files=files) -
How to add URL to a Generic ListView
I was trying to add a link to my ListView so it can display the detail view when user click on it but it is telling me My Object is not iterable -
Django extends only one template
I have an app called exercise_tracker and want to extend my base.html with two templates: exercise_list.html and footer.html. For exercise_list.htmlI have set a view for footer.html not. It doesn't render the content of footer.html. Can you give me a hint what I'm doing wrong? views.py from django.shortcuts import render from django.utils import timezone from .models import Exercise def exercise_list(request): exercises = Exercise.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'exercise_tracker/exercise_list.html', {"exercises": exercises}) base.html <html> <body> {% block content %} {% endblock %} {% block footer %} <p>Footer placeholder</p> {% endblock %} </body> </html> exercise_list.html {% extends 'exercise_tracker/base.html' %} {% block content %} <table> {% for exercise in exercises %} <tr> <td>{{ exercise.date_learned }}</td> <td>{{ exercise.time_studied }}</td> <td>{{ exercise.language_learned }}</td> <td>{{ exercise.description|linebreaksbr }}</td> </tr> {% endfor %} </table> {% endblock %} footer.html {% extends 'exercise_tracker/base.html' %} {% block footer %} <p>Footer</p> {% endblock %} -
Django, How to filter data with 2-layers foreign key
I am confused with how to get the right result... Here is model class StockInForm(models.Model): color = models.ForeignKey(Color, ...) class Color(models.Model): color = models.CharField(...) supplier = models.ForeignKey(Supplier, ...) class Supplier(models.Model): supplier = models.CharField(...) I were given a supplier keyword and what I want to get is the form which match the keyword. I have try many times but don't know how to do it. May I have some tips? Thank you. If I was given a color keyword, I can use StockInForm.objects.filter(**{"color__color" : keyword}) to get all the form with color keyword. But it doesn't working when I use like this StockInForm.objects.filter(**{"color__color__supplier " : keyword}) -
I'm trying to upload image with Generic View but it is not creating image folder on its own "CHECK CARPOSTCREATEVIEW CLASS"
Problem is in CarPostCreateView class, it is not creating an image folder on its own, I have tried everything from django.shortcuts import render, redirect from django.http import HttpResponseRedirect, HttpResponse from .models import CarPost from django.contrib import messages from .forms import CarForm from django.views.generic import DetailView, ListView, CreateView, FormView from django.db.models import Q from django.http import HttpResponseRedirect from django.contrib.auth.models import User from django.urls import reverse_lazy def home(request): return render(request, 'blog/home.html', {'title': 'Home'}) class CarPostListView(ListView): model = CarPost template_name = 'blog/cars.html' # <app>/<model>_<viewtype>.html ordering = ['-date_posted'] context_object_name = 'cars' import json def apiJson(request): emp={ 'name': 'Ramanuj', 'age': 25, 'sal': 60000, 'city': 'Rohtak', } representation = f"Name {emp['name']},<br> age {emp['age']}, <br>sal {emp['sal']}, <br>city {emp['city']}" rd = json.dumps(emp) return HttpResponse(rd) class CarPostDetailView(DetailView): model = CarPost class CarPostCreateView(FormView): form_class = CarForm success_url = reverse_lazy('blog-cars') template_name = 'blog/carpost_form.html' def form_valid(self, form): form.instance.posted_by = self.request.user form.save(commit=True) return super(CarPostCreateView, self).form_valid(form) def search(request): if request.method == 'POST': srch = request.POST.get('q') if srch: match = CarPost.objects.filter(Q(company_name__icontains= srch) | Q(model_name__icontains= srch)) if match: return render(request, 'blog/cars.html', {'cars':match}) else: return messages.error(request, "no result found!") else: return HttpResponseRedirect('/search_post/') return render(request, 'blog/cars.html') from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class … -
Missing data after joined table raw is json serialized
I am trying join two tables in django using raw sql.My code is data=Login.objects.raw("select * from demoapp_login inner join demoapp_reg on demoapp_reg.id=demoapp_login.seid_id;") and when i print(data.columns) i got the columns of two tables.like this ['id', 'usermname', 'password', 'seid_id', 'id', 'fname', 'lname', 'age'] Then a serialized the data as follows. ob=serializers.serialize("json",data) then i print 'ob', i hot a result like this [{"model": "demoapp.login", "pk": 24, "fields": {"seid": 24, "usermname": "xxx","password": "xxx"}}] My full code is: data=Login.objects.raw("select * from demoapp_login inner join demoapp_reg on demoapp_reg.id=demoapp_login.seid_id;") print(data.columns) for i in data: print(i.id) print(i.fname) print(i.lname) print(i.age) print(i.username) print(i.password) ob=serializers.serialize("json",data) print(ob) Output: ['id', 'usermname', 'password', 'seid_id', 'id', 'fname', 'lname', 'age'] 24 abc sbc 456 xxx xxx [{"model": "demoapp.login", "pk": 24, "fields": {"seid": 24, usermname": "xxx","password": "xxx"}}] that is the 'ob' showing only the first model fields not showing the second table data.What is the problem here. I Don't understand what the problem here? -
Integrate Django with Python Script
I am working on a web App with Django, and one of it's functionalities includes running a Python script that interacts with some files in the database. Is there a way to integrate Django with my script so each user of the app can call the script. -
Dynamic Bootstrap Tabs using Django
I have 2 tables in mysql. One is main table which keep title and title will be shown as tab header and there is one content table which will shown as content of each tab. There is foreign key between 2 tables. But i couldn't print related content under correct tab. This is my code that i show tab headers. <ul class="nav nav-tabs"> {% for title in titles %} <li class="nav-item"> <a class="nav-link active" id="{{ title.id }}" data-toggle="tab" href="#{{ title.name }}" role="tab" aria-controls="{{ title.name }}" aria-selected="true">{{ title.name }}</a> </li> {% endfor %} </ul> End this is part for tab content <div class="tab-content" id="SideBarTabContent"> <!-- tab content --> <div class="tab-pane fade show active" id="should print header name" role="tabpanel" aria-labelledby="should print header name"> <ul class="nav flex-column mb-2"> {% for item in contents %} <li class="nav-item"> <a class="nav-link active" href="{{ item.id }}"> {{ item.name }} <span class="sr-only"></span> </a> </li> {% endfor %} </ul> </div> </div> And there is django code: def home(request): titles = Headers.objects.all()[:10] contents = content.objects.select_related('Content') return render_to_response('main.html', {'titles' : titles, 'contents': contents}) -
how to add span in a django form field showed in the image
login form How can i create django forms exactly like showed in the image. how to add html span to forms? -
Using ModelFormMixin (base class of CreatePostView) without the 'fields' attribute is prohibited
I am trying to pass the form to my createview but facing improperly configured file and following suggestion "Using ModelFormMixin (base class of CreatePostView) without the 'fields' attribute is prohibited". Any suggestion on how to tackle this problem?? class CreatePostView(LoginRequiredMixin,CreateView): login_url='/login/' redirect_field_name='blog/post_list.html' from_class=PostForm model=Post PostForm is name of modelform -
having problems with a circular import error
I have been trying to learn how to code using paython and Django and have been having a lot of fun with it but recently I have hit a little snag. I have been working on trying to fix the problem for the last few days but cant seem to figure things out. When I try to start up the development server for Django I get the following error: raise ImproperlyConfigured(msg.format(name-self.urlconf_name)) Django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. Any help would be greatly appreciated. I am trying to set the music app up so that when queried will send an index file. website.urls from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('music/', include('music.urls')) music.urls from django.urls import path from . import views path('', views.index, name="index") music.views from django.http import HttpResponse def index(request): return HttpResponse("<h1> This is my Home Page </h1>") -
Django - Room model needs to have a selection of many room types. One room must have at least one room type from the predefined selection
One property can have one or many rooms. One room must belong to one property. The question is at the end. I start by creating the Room Model class Room(models.Model): property = models.ForeignKey(Property) name = models.CharField(max_length=250) description = models.TextField(max_length=800) image = models.ImageField(upload_to='room_images/', blank=False) bar_rate = models.IntegerField(default=0, blank=False) max_occupancy = models.IntegerField(default=1, blank=False) extra_beds = models.IntegerField(default=0, blank=True) price_per_exra_bed = models.IntegerField(default=0, blank=True) is_breakfast_included = models.BooleanField(default=False) room_type_quantity = models.IntegerField(default=0, blank=False) ROOM_TYPES = ( ('SGL', 'Single'), ('TWN', 'Twin'), ('DBL', 'Double'), ('TRPL', 'Triple'), ('STND', 'Standard'), ('DLX', 'Deluxe'), ('EXET', 'Executive'), ('SPR', 'Superior'), ('JS', 'Junior Suite'), ('ONEBDR', 'One Bedroom'), ('TWOBDR', 'Two Bedroom'), ('THREEBDR', 'Three Bedroom'), ('FOURBDR', 'Four Bedroom'), ('FIVEBDR', 'Five Bedroom'), ('SIXBDR', 'Six Bedroom'), ('SEVENBDR', 'Seven Bedroom'), ) room_type = models.CharField(max_length=1, choices=ROOM_TYPES, default="STND") def __str__(self): return self.name I create a new form to allow the user to fill out the form. Inside forms.py class RoomForm(forms.ModelForm): class Meta: model = Room exclude = ("property",) As you can see above I exclude the property model, I don’t need to add the property info into the RoomForm. In views.py I have modified the property_add_room function to save the room into the database: @login_required(login_url='/property/sign-in/') def property_add_room(request): form = RoomForm() if request.method == "POST": form = RoomForm(request.POST, request.FILES) if form.is_valid(): room = form.save(commit=False) …