Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When deploy on Heroku, report TypeError: expected str, bytes or os.PathLike object, not tuple
I disable collectstatic with command heroku config:set DISABLE_COLLECTSTATIC=1 After successfully push my project to heroku, manually collectstatic as below: $ heroku run python manage.py collectstatic Unfortunately, Heroku report errors referring to 'manage.py` Running python manage.py collectstatic on ⬢ fierce-cove-94300... up, run.6296 (Free) /app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py:144: UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: <http://initd.org/psycopg/docs/install.html#binary-install-from-pypi>. """) Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 173, in handle if self.is_local_storage() and self.storage.location: File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/functional.py", line 239, in inner return func(self._wrapped, *args) File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/files/storage.py", line 283, in location return abspathu(self.base_location) File "/app/.heroku/python/lib/python3.6/posixpath.py", line 371, in abspath path = os.fspath(path) TypeError: expected str, bytes or os.PathLike object, not tuple How to solve such a problem? -
Django 2.0: NoReverseMatch at /url/ (/pledges/group/7/)
I just have upgraded from Django 1.11 to 2.0. These are the urls I have for one Django application: urlpatterns = [ url(r'^logout/$', views.logout, name='logout'), url(r'^$', views.home, name='home'), url(r'^pledge/(?P<group_id>[0-9]+)/$', views.pledge, name='pledge_by_group'), # I have more urls, but I have omitted them since they are not relevant url(r'^404/$', views.bad_request, name='404') ] After upgrading, I checked everything was fine. Then, I changed: url(r'^pledge/(?P<group_id>[0-9]+)/$', views.pledge, name='pledge_by_group') to: url('pledge/<int:group_id>/', views.pledge, name='pledge_by_group'), in order to take advantage of simplified URL routing syntax in Django 2.0. However, I am getting getting the following error when I try to access http://localhost:8000/pledges/group/7/: NoReverseMatch at /pledges/group/7/ Reverse for 'pledge_by_group' with keyword arguments '{'group_id': '7'}' not found. 1 pattern(s) tried: ['pledge//'] This is my view: @login_required(redirect_field_name='') def group_pledge(request, group_id): """Updates selected_pledge key and loads group pledge information.""" def get_total_by_group(group_id): group = Group.objects.get(id=group_id) pledges = Pledge.objects.filter(group=group) return sum_of_pledges(pledges).amount request.session['selected_pledge'] = group_id user = request.user if redirect_to_personal_pledge_page(user, group_id): try: del request.session['selected_pledge'] except KeyError: pass return redirect('pledges:home') total = get_pledge_total(user, group_id=group_id) pledge_settings = get_pledge_settings(user, group_id) chosen_pledge_message = Group.objects.get(id=group_id).name maximum = user.pledge_settings.maximum amount = pledge_settings.amount context = { 'pledge_url': reverse('pledges:pledge_by_group', kwargs={'group_id': group_id}), } # context has more values, but for practical reasons I don't include them return render(request, 'pledges/home.html', context) According to the error, … -
Using Django as GUI for long running python process
This a question about architecture. Say I have a long running process on a server such as machine learning in a middle of a training. Now as this run on external machine I would like to have a tool to quickly see from time to time the results. So I thought the best way would be to have a website which quickly connects to the process for example using RPC to display the results as this allows me to always check in. Now the question is how should Django view gather the information from the server process: 1) Using RPC calls such as rpyc directly in the views? 2) Using some kind of messaging queue such as celery ? 3) Or in a completely different way I am not seeing ? -
Render text in submitted form as SO's body form
I wrote a form in Django's template as: {% block content %} <form action="{% url "learning_logs:new_entry" topic.id %}" method="POST" class='form'> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button name="button" class='btn btn-primary'>add entry</button> {% endbuttons%} </form> {% endblock content %} It returns a plain Textarea interactive form on the browser. How could enable my form rendering rich text and perform multiple functions as stackoverflow's question'body form. -
how to create a autocomplete input field in a form using Django
I am pretty new to django and its ways. I am trying to create an autocomplete field for a form. My code is as below forms.py from django import forms class LeaveForm(forms.Form): leave_list = ( ('Casual Leave', 'Casual Leave'), ('Sick Leave', 'Sick Leave') ) from_email = forms.EmailField(required=True, widget=forms.TextInput(attrs={'style': 'width: 400px'})) start_date = end_date = forms.CharField(widget=forms.TextInput(attrs={'type': 'date', 'style': 'width: 175px'})) leave_type = forms.ChoiceField(choices=leave_list, widget=forms.Select(attrs={'style': 'width: 400px'})) comments = forms.CharField(required=True, widget=forms.Textarea(attrs={'style': 'width: 400px; height: 247px'})) def clean_from_email(self): data = self.cleaned_data['from_email'] if "@testdomain.com" not in data: raise forms.ValidationError("Must be @testdomain.com") return data What I want to achieve is that when an user types words into the "From Email" field the list of emails I have stored in an external DB should appear in the autocomplete list option. models.py from django.db import models class ListOfUsers(models.Model): emp_number = models.CharField(db_column='Emp_Number', primary_key=True, max_length=50, unique=True) # Field name made lowercase. name = models.CharField(db_column='Name', max_length=40) # Field name made lowercase. supervisor = models.CharField(db_column='Supervisor', max_length=40) # Field name made lowercase. email = models.CharField(db_column='Email', max_length=50, blank=False, null=False, unique=True) # Field name made lowercase. class Meta: managed = False db_table = 'List of users' Any idea how this can be done ? -
Django - How to send auto_now=True DateFields with values()?
I have the following field: date_created = models.DateField(auto_now=True) When I do MyModel.objects.values(), all the fields other than the date_created field is included. I'm guessing this field is not included because of the auto_now=True attribute. How do I include this field when doing .values()? -
How to use admin Form in a custom page Django
I'm trying to use the same form for date and time used in admin page but in a custom page. I've created a form class like this: from django import forms from django.contrib.admin import widgets as adminWidget class RequestData(forms.Form): data = forms.DateField(widget=adminWidget.AdminDateWidget()) When I show this form in a template it doesn't look like in the admin page -
How to align Materialize form labels for select menus and text fields with the 'active' class?
I'm working on a project which includes a filter form in which the fields are arranged side-by-side: Notice that the 'Does Virtual' label is ever so slightly vertically misaligned with the other ones. This is because each label is 'moved up' in a different way. The 'Market' label, for example, has the "active" class added in Materialize: This comes with a top of 0.8rem and a translateY of -140%. The 'Does Virtual' label, on the other hand, comes after a div with the select-wrapper class, which was added by Materialize's Javascript as described in https://materializecss.com/forms.html. It has a top property of -14px: I've tried to make the 'Does Virtual' label vertically align with the ones with the 'active' class by adding the following to my CSS: .select-wrapper + label { // The Materialize default is top: -14px, which makes the labels slightly misaligned // with regular .input-field labels with the "active" class position: absolute; top: 0.8rem; font-size: 0.8rem; -webkit-transform: translateY(-140%); transform: translateY(-140%); } This works, but now whenever I refresh the page I can for an instant see the 'Does virtual' label moving upwards, which is arguably more annoying than the slight misalignment I was trying to solve in the … -
How to pass html form variable to python function with django
I know this might be a very stupid question, but i'm new to django and try to solve this problem for several houres now. I want to pass a variable from a html form to the backend an then use the variable there to make an api request. Then i want to pass the result of the api-request back to the index.html page. For example: index.html <form action="#" method="post"> {% csrf_token %} <input type="text" class="form-control" id="city" placeholder="" value=""> <input type="submit" value="Submit"> </form> forms.py import requests api_address='http://api.openweathermap.org/data/2.5/weather? appid=KEY&q=' city = FORM-VARIABLE url = api_address + city json_data = requests.get(url).json() kelvin = json_data['main']['temp'] temperature = round(kelvin - 273.15,0) And then show the temperature in the index.html -
Django Can't Find Template in App
So i'm trying to build a basic blog in Django (am currently using the latest version of Django) and i'm running into a really annoying problem. When I try and set up my html templates, I keep on getting a templatedoesnotexisterror. Here's the rub--if I set up my html templates in the root app of the project ("blogcode"), they run perfectly. But then, once I start running another app ("articles") and then I set up a templates folder using articles/templates/articles/homepage.html, all of the sudden, it doesn't work. I can't get django to look anywhere but in the root app directory to find and ultimately render templates. In my settings.py file, i've the DIRS list set to 'templates'. When I tried changing it to os.path.join(BASE_DIR, 'templates') I get the same "templatedoesnot exist" error. Also, my app IS properly installed in the INSTALLED_APPS list in settings. I've tried looking in other documentation, but the only hints I can find are really outdated. On the views.py, if I chop off the articles/, and just leave it as 'homepage.html' django renders it from the root app just fine and ignores the template in the articles app, but if I try and get it to … -
ugettext_lazy/pgettext_lazy not working in Django sub-application
I am translating a Django site with a sub-application. Let's say the top level site is called 'main_site' and the sub application is called 'sub_app'. In main_site, I am using only trans and blocktrans tags for translation (with context markers). After farting around for a day or two, I can now mark text with the same strings using the 'context' keyword. For example, contact.html <input type="text" class="form-control" placeholder="{% trans "Name" context "ContactForm" %}"> register.html <h5 class="text-center">{% trans "Name" context "RegisterForm" %}</h5> makemessages correctly creates these entries in the top level PO file and I can update them with different translations and Django renders them correctly. I do not use u/pgettext_lazy at all in the top-level application. With that working, I moved on to the I18N of sub_app. In forms.py I have: class UserRegistration(forms.Form): email = forms.CharField(widget=forms.TextInput(attrs={'readonly': 'readonly'}), label=ugettext_lazy('Email')) makemessages again creates the entry correctly in sub_app's PO file. I use that form in register.html from the top-level application like this: <div class="row"> <div class="col-md-5 col-md-offset-1"> {% bootstrap_field form.email form_group_class="form-group" label_class="control-label" %} </div> </div> So the problem is when this form gets rendered, the translated text is not fetched for the form label. I don't know if this is because Django … -
DRF update a row
im trying to update a existing row in db in client side i send request with put method to server i used updatemodelmixin also id is comming to server in data by this view server response is maximum recursion depth exceeded what is correct way to update my data? class ProductOwnserSingleViewAPIView(APIView,mixins.UpdateModelMixin): queryset = Product.objects.all() serializer_class = ProductSerializer def put(self, request, *args, **kwargs): return self.put(self,request,*kwargs,**kwargs) def get(self, request): id = request.GET.get("id") try: product = Product.objects.get( author_id=request.user.id, product_id=id ) if not product: return Response(status.HTTP_400_BAD_REQUEST) serializer = ProductSerializer(instance=product, context={"request": request}) return Response(serializer.data) except Product.DoesNotExist: return Response(status.HTTP_400_BAD_REQUEST) -
django / Apache2 Server
I'm trying to set up an Apache2/Django server on Ubuntu 18.04 x64 Digital Ocean droplet. I've went through the tutorials but still get an error. I've searched Stackoverflow and other sources for the solution, but still nothing works. Would someone be able to help? The project is placed in /root/myproject. I use virtualenv that I named myprojectenv. So the python path is correct with /root/myproject/myprojectenv. I'm using Python 3.6 and the version of /root/myproject/myprojectenv/bin/python is indeed 3.6. I'm using libapache2-mod-wsgi-py3. I have chown'ed the whole /root/myproject folder to 'www-data' and chmod'ed to 664 the sqlite.db file in accordance with DigitalOcean's tutorial. The content of my /etc/apache2/sites-available/000-default.conf file is (comments deleted): <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /root/myproject ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static/ /root/myproject/static/ <Directory /root/myproject/static> Require all granted </Directory> <Directory /root/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-home=/root/myproject/myprojectenv python-path=/root/myproject WSGIProcessGroup myproject WSGIScriptAlias / /root/myproject/myproject/wsgi.py process-group=myproject </VirtualHost> The content of /root/myproject/myproject/settings.py is: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '[SOME STRING]' DEBUG = True ALLOWED_HOSTS = ['[IP Address as a string]'] ... The error I get by trying to access the page via browser: Forbidden You don't have permission to access / on this server. Apache/2.4.29 (Ubuntu) … -
Django manage.py migrate error
So I am currently in a virtual environment, and when I typed the command line: python manage.py migrate and I encounter this problem: > Traceback (most recent call last): > File "manage.py", line 24, in <module> > execute_from_command_line(sys.argv) > File "C:\Users\DUCNGU~1\Desktop\HAULER~1\api\vnenv\lib\site-packages\django\core\management\__init__.py", > line 371, in execute_from_command_line > utility.execute() > File "C:\Users\DUCNGU~1\Desktop\HAULER~1\api\vnenv\lib\site-packages\django\core\management\__init__.py", > line 317, in execute > settings.INSTALLED_APPS > File "C:\Users\DUCNGU~1\Desktop\HAULER~1\api\vnenv\lib\site-packages\django\conf\__init__.py", > line 56, in __getattr__ > self._setup(name) > File "C:\Users\DUCNGU~1\Desktop\HAULER~1\api\vnenv\lib\site-packages\django\conf\__init__.py", > line 43, in _setup > self._wrapped = Settings(settings_module) > File "C:\Users\DUCNGU~1\Desktop\HAULER~1\api\vnenv\lib\site-packages\django\conf\__init__.py", > line 106, in __init__ > mod = importlib.import_module(self.SETTINGS_MODULE) > File "C:\Users\DUCNGU~1\Desktop\HAULER~1\api\vnenv\lib\importlib\__init__.py", > line 126, in import_module > return _bootstrap._gcd_import(name[level:], package, level) > File "<frozen importlib._bootstrap>", line 994, in _gcd_import > File "<frozen importlib._bootstrap>", line 971, in _find_and_load > File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked > File "<frozen importlib._bootstrap>", line 665, in _load_unlocked > File "<frozen importlib._bootstrap_external>", line 678, in exec_module > File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed > File "C:\Users\Duc Nguyen\Desktop\HaulerAds\api\settings.py", line 104, in <module> > 'PORT': int(os.getenv('POSTGRES_PORT')), > TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' My current Django version 2.0.3. I checked the python pass and I have the proper path. Please help, thank you! -
Django - LDAP authentication in clear text
I created a website using django and recently added ldap authentication pointing towards our active directory on LDAP tcp/389. The problem is the django auth-ldap sends this ldap password data in clear text, and the AD i'm trying to authenticate with is not setup for LDAPs tcp/636 (I don't have control of that) so i cant use the command AUTH_LDAP_START_TLS = True Please see my script below is there any enhancements/script I can add easily, to continue using ldap/389 but with added security (like kerberos or ntlm?) to stop passwords sending in clear text - from django_auth_ldap.config import LDAPSearch, GroupOfNamesType,LDAPGroupQuery AUTH_LDAP_GLOBAL_OPTIONS = { ldap.OPT_X_TLS_REQUIRE_CERT: False, ldap.OPT_REFERRALS: False, } AUTH_LDAP_SERVER_URI = "ldap://x.x.x.x" AUTH_LDAP_BIND_DN = "CN=xxx,OU=xxx,OU=xxx,OU=xxxx,OU=xxxx,OU=xxxx,DC=xxx,DC=xxx,DC=xxx" AUTH_LDAP_BIND_PASSWORD = credentials.adlogin['pass'] AUTH_LDAP_USER_SEARCH = LDAPSearch("OU=xxx,DC=xxx,DC=xxx,DC=coxxm", ldap.SCOPE_SUBTREE, "(sAMAccountName=%(user)s)") AUTH_LDAP_GROUP_SEARCH = LDAPSearch("ou=groups,dc=example,dc=com", ldap.SCOPE_SUBTREE, "(objectClass=groupOfNames)" ) AUTH_LDAP_GROUP_TYPE = GroupOfNamesType() AUTH_LDAP_REQUIRE_GROUP = ( ( LDAPGroupQuery("CN=xx-xx,OU=xx,OU=xxx,,DC=xx,DC=xxx,DC=xx") | LDAPGroupQuery("CN=xx-xx,OU=xx,OU=xxx,,DC=xx,DC=xxx,DC=xx") ) ) AUTH_LDAP_USER_ATTR_MAP = { "first_name": "givenName", "last_name": "sn", "email": "mail" } SESSION_COOKIE_AGE = 15*60 AUTHENTICATION_BACKENDS = [ 'django_auth_ldap.backend.LDAPBackend', 'django.contrib.auth.backends.ModelBackend', ] -
Passing cookies along with URLs
We are building a patent based application that accesses all pages using a selenium node from our selenium grid. We download the PDF of the patent application via Google patents and the latest claims PDF from Global Dossier (https://globaldossier.uspto.gov/). To download the patents’ pdf, we build the URL and then send it back to the Django server for it to download it locally. However, since the Global Dossier website protects URLs by cookies, we need to pass back the URL as well as the cookies so that we can pass them to WGET (or any file downloader that we can pass cookies too). This is where we are stuck. We do not know enough about cookies, but cookies need to be passed back so that the file can be downloaded. Any help on this is appreciated. -
Upload images to google cloud storage using django views
I am creating a django application in hosted in google cloud. I am able to send and save data in the backend mysql database but not able to upload and save images using django's ImageField. Please help. Any ideas Thanks in advance for the help -
Multiple db tables from a single Django model
Let's say there's some kind of car rent/sell aggregator. It works with many service providers (that provide cars to the customers) and the customers themselves. Django way to do models for this kind of system would be something like this: class Vendor(models.Model): name = models.CharField() class Car(models.Model): vendor = models.ForeignKey(Vendor, blank=False, null=False, related_name='cars', on_delete=models.CASCADE) license_plate = models.CharField(max_length=10, blank=False, null=False) Now, we would proceed to add customer model, probably with m2m field pointing to Cars through the table with dates of rent or whatever. All Vendors would have access only to their Cars even though all the cars are in one table, they would share one table for customers, etc. Assuming hypothetical scenario of there being a few vendors, say, a dozen, but each of them having a lot of cars - in the millions, my questions are: Would there be any benefit in attempting to split the Cars model into multiple tables (despite django's principle one table - one model, maybe there are benefits on the DB side)? I kinda think that if each car had some description, like desc = models.CharField(max_length=500, blank=True) then splitting could maybe simplify indexing? Dunno. Would be grateful if someone could clarify this. Anyway, even … -
django.core.exceptions.ImproperlyConfigured: "^(?$" is not a valid regular expression: unexpected end of pattern
Please help I am over my head and very very inexperienced. Every time I try to run my site, I receive the titled error. The full thing is as follows: Performing system checks... Unhandled exception in thread started by <function wrapper at 0x101c5bcf8> Traceback (most recent call last): File "/Users/student/ENV/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Users/student/ENV/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "/Users/student/ENV/lib/python2.7/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/Users/student/ENV/lib/python2.7/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/Users/student/ENV/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/Users/student/ENV/lib/python2.7/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/Users/student/ENV/lib/python2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/Users/student/ENV/lib/python2.7/site-packages/django/urls/resolvers.py", line 255, in check warnings.extend(check_resolver(pattern)) File "/Users/student/ENV/lib/python2.7/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/Users/student/ENV/lib/python2.7/site-packages/django/urls/resolvers.py", line 172, in check warnings = self._check_pattern_startswith_slash() File "/Users/student/ENV/lib/python2.7/site-packages/django/urls/resolvers.py", line 140, in _check_pattern_startswith_slash regex_pattern = self.regex.pattern File "/Users/student/ENV/lib/python2.7/site-packages/django/urls/resolvers.py", line 93, in __get__ instance.__dict__['regex'] = self._compile(instance._regex) File "/Users/student/ENV/lib/python2.7/site-packages/django/urls/resolvers.py", line 109, in _compile (regex, six.text_type(e)) django.core.exceptions.ImproperlyConfigured: "^(?$" is not a valid regular expression: unexpected end of pattern I've double checked my urls.py, but the source of the error doesnt seem to be there from django.conf.urls import url from . import views #these are the urls. Observe and about are for the future, … -
Django Coverage ModuleNotFoundError: No module named 'django_extensions'
I've dug through SO posts, I've dug through random obscure blogs and I can't seem to fix my issue here. This is how I went about all this: I created a nice fresh new virtual environment: virtualenv venv I installed all my requirements: pip install -r requirements.txt Per the LocalFlavor Documentation I pip installed django-localflavor But when I try to run coverage on my application per the django docs: coverage run --source='.' manage.py test visitor_check_in I get the error 'No module named 'localflavor'... My installed apps looks like this: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admindocs', 'localflavor', 'visitor_check_in', 'django_extensions', ] Just last week I had this running, but I must have goofed something up during a conference recently when I was running through some tutorials or something - but I was in other virtual environments for those tutorials - so I'm stumped. If I move the order of my installed apps like this: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admindocs', 'visitor_check_in', 'django_extensions', 'localflavor', ] It gives me the same no module found error - except it says it cannot find the module django_extensions The traceback looks like this: Traceback (most recent call last): File … -
Django add objects to Related Manager during creation
Consider a simple ForeignKey relationship: class A(Model): pass class B(Model): a = ForeignKey(A) I have an API view that creates an A and a set of B's based on outside data (data NOT passed from the user), then serializes the created objects and returns the serialized data. My object creation code looks something like: a = A() a.b_set.bulk_create(B(a=a) for b in [...]) My issue is that this does not add the B objects to a's b_set, so that if I were to run print(a.b_set.all()) afterwards, it would re-query the DB to get b_set. This is unnecessary though, because I already have a's entire b_set as I just created it. I'm doing this with a series of nested objects so it results in a LOT of unnecessary queries. My current workaround is to, after creation, run a query like A.objects.prefetch_related('b_set').get(a=a.id) then serializer that fetched object. This limits serializtion to just one unnecessary query, but I'd like to eliminate that one as well. It seems to me like there should be a way to cache the created B objects on a, and eliminate any need to hit the DB again during serialization. -
Django - Extend User model on Two Difrent Models
I want to extend User Model in django with two different models. I mean, I want to have two registration panels for Vacancy and second one for Company. So I am going to have two different forms for User django class extended on attributes of Company. And User class extended on Vacancy class. How should I correlate this models to have my goal? Im open for new ideas. Thanks for any help Guys! class Company(models.Model): name_company = models.CharField(max_length=100) city = models.CharField(max_length=100) street = models.CharField(max_length=100) phone = models.CharField(max_length=9) email = models.EmailField(max_length=50) class Vacancy(models.Model): fullname = models.CharField(max_length=100) age = models.IntegerField(blank=True, default=0) education = models.CharField(max_length=100,blank=True, default='') origin = models.CharField(max_length=100,blank=True, default='') miasto = models.CharField(max_length=100, blank=True,default='') panstwo = models.CharField(max_length=100,blank=True,default='') -
How to show delete/edit link for the logged in user and not everyone?
I know how I can delete and edit posts in different views, but in one page where there is one post and several answer to this post, how would i link to edit and delete views for all these different users? -
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. when I import model
I am new python also Django. I know the same issue is posted in this forum. but still, can't figure it out. created a model and need to import in my views.py file so I can render my data. this is my views.py from first_app.models import Topic, webpage, AccessRecord from django.shortcuts import render from django.http import HttpResponse # from django.apps import AppConfig # Create your views here. def index(request): webpage_list = AccessRecord.objects.order_by('date') date_dict = {'acess_records': webpage_list} return render(request, 'first_app/index.html') and it showed me this error PS E:\python\firstp\first_project> python manage.py runserver Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0000024518AB58C8> Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\ProgramData\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "C:\ProgramData\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\ProgramData\Anaconda3\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\ProgramData\Anaconda3\lib\site-packages\django\apps\registry.py", line 89, in populate app_config = AppConfig.create(entry) File "C:\ProgramData\Anaconda3\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\ProgramData\Anaconda3\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File … -
Django set default value with include
I have my base html: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>default value</title> <meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'> </head> <body > {% block content %}{% endblock %} </body> </html> And I have my template: {% extends "base.html" %} {% block content %} I want to be able to rewrite contents of <head> tag . And use default head tag if no head content is present. How do I do this? For example on some pages I want to use additional meta tags and different title. But I need default title and meta tags if no <head> tag is specified