Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Calculate number of days of periods in year using Django (queryset) - postgres
I am trying to figure out how to calculation a total number of period in a year in the database. Take for example, calculating total leaves in a year. I am using: Django - 1.11.7 Postgres - 9.4 Here is my models.py: class Leave(models.Model): leavedatefrom = models.DateField() leavedateto = models.DateField() An Example to illustrate the issue: leaves taken in 1 year (01/01/2019 - 31/12/2019) record 1: 01/02/2019 - 05/02/2019 ===> 5 days record 2: 10/05/2019 - 12/05/2019 ===> 3 days Total days = 5 + 3 = 8 days How can calculate in Django of the number of days of periods in the database in a year ? Basically I want to get 8 days in the example above. -
'itertools._grouper' object has no attribute 'user'
Why I can't convert the loop group in groupby as list? Currently, I working on Django==2.2.1 and when I try this data = [...] below into python console, it working fine. data = [{'total_order': 1, 'agent_name': 'agentbeli', 'total_pcs': 1, 'total_kg': 5.0}, {'total_order': 1, 'agent_name': 'agent123', 'total_pcs': 1, 'total_kg': 5.0}, {'total_order': 1, 'agent_name': 'agent123', 'total_pcs': 1, 'to tal_kg': 6.0}, {'total_order': 1, 'agent_name': 'agentbeli', 'total_pcs': 1, 'total_kg': 6.0}, {'total_order': 1, 'agent_name': 'agentbeli', 'total_pcs': 1, 'total_kg': 6.0}, {'total_order': 1, 'agent_name': 'agent123', 'total_pcs': 1, 'total_kg': 7.0}] print(type(data)) # a list from itertools import groupby from operator import itemgetter sorted_totals = sorted(data, key=itemgetter('total_order')) for key, group in groupby(sorted_totals, key=lambda x: x['agent_name']): print(key, list(group)) # I stopped here when converting the `group` as list. But, I getting an error look like this when I try it at views in Django. -
Django gives a long error after trying to runserver with crispy-forms added in the project
I used pipenv to install crispy forms into my project, and also added it into my settings.py file under my list of installed apps. When I try to run the server after adding this in, I get a long error message from Django. If I take out crispy-forms in the installed app, the server will run. ... 'crispy_forms', )``` I get a long error message with the "LookUp error: No installed app with label 'admin' at the bottom. Due to the excessive amount of errors, stackoverflow will not allow me to post the full error list. -
How to use JavaScript in Django html file for error messages?
in my html template have error messages for form validation like below {% for field in form %} <span class="text-danger small">{{ field.errors }}</span> {% endfor %} if i want to use sweet alert for that how can I do it if i use like below it will give a empty alert when page loads but when the error happens it will give an empty alert like the when pages loading how can i pass those data into sweet alert what did i do wrong? {% for field in form %} <span class="text-danger small">{{ field.errors }}</span> <script> var a = "{{ field.errors }}" swal(a) </script> {% endfor %} -
Question installing Django-Heroku via pip
I was installing Django-Heroku via pip3 install django-heroku but was getting ERROR: Complete output from command python setup.py egg_info: ERROR: running egg_info creating pip-egg-info/psycopg2.egg-info writing pip-egg-info/psycopg2.egg-info/PKG-INFO writing dependency_links to pip-egg-info/psycopg2.egg-info/dependency_links.txt writing top-level names to pip-egg-info/psycopg2.egg-info/top_level.txt writing manifest file 'pip-egg-info/psycopg2.egg-info/SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <http://initd.org/psycopg/docs/install.html>). ---------------------------------------- ERROR: Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/k5/c368rkc52zd160lhtxqy4s5h0000gn/T/pip-install-7rdtd9f1/psycopg2/` I tried installing pip3 install psycopg2 and pip3 install python-psycopg2 but was also getting the same error as above. I tried upgrading my pip but my pip is up to date. I tried pip3 install --upgrade setuptools but everything is up to date. I have a runtime.txt, requirements.txt & a Procfile and basically just followed what heroku said on its website on how to deploy a django app. my DEBUG = False and ALLOWED_HOST = ['https://myapp.heroku.com/']. … -
find div class by the element text inside it
I am crawling a game website and I want to get the div object that contains a certain text. In this case I want to get the div class "GameItemWrap" that contains a href with the text "SANDBOX Ghost". There are many GameItemWrap classes in the whole code and I don't want to get the "SummonerName"class div because there are some other classes inside "GameItemWrap" that I need. This is what I have tried : duo_name='SANDBOX Ghost' gamelist=soup.find('div',"GameItemList")# "GameItemList" is a div that contains "GameItemWrap" games=gamelist.find_all('GameItemWrap',{('a'):duo_name }) <div class="GameItemWrap> #some other div classes that i will need in the future <div class="SummonerName"> <a href="//www.op.gg/summoner/userName=SANDBOX+Ghost" class="Link" target="_blank">SANDBOX Ghost</a> </div> </div> But when I print print(len(games)) the output is 0. This does not work. -
Django won't connect to postgresql after SSL certificate from let's encrypt
I recently ran certbot --apache to create a ssl certificate for my site. however my site went down immediatley after I did so and the apache error log shows I am not connecting to postgresql. apache error log: [Tue May 21 03:25:22.400677 2019] [wsgi:error] connection = Database.connect(**conn_params) [Tue May 21 03:25:22.400679 2019] [wsgi:error File "/home/kmostafa89/MK_SITE/venv/lib/python3.6/site-packages/psycopg2/__init__.py", line 130, in connect [Tue May 21 03:25:22.400682 2019] [wsgi:error] conn = _connect(dsn, connection_factory=connection_factory, **kwasync) [Tue May 21 03:25:22.400684 2019] [wsgi:error][remote 81.103.75.183:56590] django.db.utils.OperationalError: could not connect to server: Connection refused [Tue May 21 03:25:22.400686 2019] [wsgi:error] \tIs the server running on host "localhost" (::1) and accepting [Tue May 21 03:25:22.400689 2019] [wsgi:error] \tTCP/IP connections on port 5432? I tried re configuring postgresql.conf file towards the key and cert produced by the certbot but that did not resolve the issue. any suggestion to get my site back up again would mean a lot. -
Cannot save data in database from queryset in django
I have following models class Diploma(models.Model): razred_id=models.IntegerField(null=False, blank=False) razred_naziv=models.CharField(max_length=64) predmeti=models.ManyToManyField(Predmet) ucenik_id=models.IntegerField(default='0',blank=False) class Meta: verbose_name_plural = "Diplome" def __str__(self): return f"{self.razred_naziv}" class Predmet(models.Model): kod=models.CharField(max_length=2, default='MM', blank=False) naziv=models.CharField(max_length=64) ocjena=models.IntegerField(null=True, blank=True) and the view which on python level is doing exactly what is needed,as well as from manage.py shell -same code, update is done, but when dealing with POST request it simply cannot update/save data in database (sqlite, django=2.0). def details(request, ucenik_id): if request.method == "POST": try: razredi_ocjene=request.POST.getlist('razredi_ocjene') #return HttpResponse(razredi_ocjene) OK diplome_qs=Diploma.objects.filter(ucenik_id=ucenik_id) # query_set -> not working diplome_list=list(diplome_qs) #converting to list -> not working (according to SO question) i=0 for razred in diplome_list: # or diplome_qs not working predmeti_list= list(razred.predmeti.all()) # predmeti is a list -> not working, also query_set for predmet in predmeti_list: #Predmet query_set predmet.ocjena=razredi_ocjene[i] i=i+1 predmet.save() razred.save() What is the problem and how to solve saving data in database ? Thanks As a reference best answer I could find is this and I have tried combinations of using/not using query_set/list (see comments in view). -
GitHub oragnization based login?
I'm creating a login system for a website. The contributors that are a part of a specific organization can only login on website while anonymous users cannot. Is there any way I can achieve this in a single step using Django-alluth or I've to specify an explicit check whether a logged in user is a part of an GitHub organization or not after the Django-allauth return the success 200 after user gets logged-in? -
How to use SweetAlert in Django error message?
{% for field in form %} <span class="text-danger small">{{ field.errors }}</span> {% endfor %} error message like above if i want to use sweet alert for that ho can I do it if i use like below it will give a empty alert when page loads but when the error happens it will give an empty alert like the when pages loading how can i pass those data into sweet alert what did i do wrong? {% for field in form %} <span class="text-danger small">{{ field.errors }}</span> <script> var a = "{{ field.errors }}" swal(a) </script> {% endfor %} -
Front-end alphanumeric validation in django form
I have created a form in django and there's a single field that I need to make sure only uses alphanumeric characters (seed). I took some code from here that I believe may be working on the backend, but I'd also like to implement that client-side to avoid errors by typing and submitting those characters in the first place. forms.py from django import forms from django.core.validators import RegexValidator THEME_CHOICES = [ ("original", "Original") ] MAX_SIZE = [ (140, "Huge"), (80, "Large"), (40, "Medium"), (20, "Small"), (10, "Tiny"), (5, "Mini") ] alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', 'Only alphanumeric characters are allowed.') class DungenForm(forms.Form): seed = forms.CharField(required=False, max_length=12, validators=[alphanumeric], help_text="Leave blank for a random dungeon.") theme = forms.ChoiceField(required=True, choices=THEME_CHOICES) max_size = forms.ChoiceField(required=True, choices=MAX_SIZE, initial=40) max_length works just fine in the browser and stops at 12, but the RegexValidator doesn't seem to be doing anything there. html ... <div class="row"> <div class="col-9" id="img-container"></div> <div class="col-3"> {% bootstrap_field form.seed %} {% bootstrap_field form.theme %} {% bootstrap_field form.max_size %} <button type="submit" class="btn btn-primary" id="generate">Generate</button> <div id="img-download"></div> <div id="tile-size" class="p-0 m-0"></div> <div id="file-size" class="p-0 m-0"></div> </div> </div> ... js $("#generate").click(function () { let button = $(this); button.attr("disabled", true); let data = { "seed": $("#{{ form.seed.auto_id }}").val(), "theme": $("#{{ … -
Cannot resolve "wsgi.py cannot be loaded as a Python module" error, even when making a fresh project in django
I am currently using windows, trying to deploy a django project to elastic beanstalk. I am following this tutorial: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html, and even after following it step by step, for a fresh project, I encounter a 500 error, detailing that my wsgi file cannot be imported. I read online some solutions used chmod, but because I am using windows, I believe that command doesn't exist. How can I solve this problem? Here are the logs. [Tue May 21 02:24:21.288362 2019] [:error] [pid 4423] [remote 127.0.0.1:140] apps.populate(settings.INSTALLED_APPS) [Tue May 21 02:24:21.288367 2019] [:error] [pid 4423] [remote 127.0.0.1:140] File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/apps/registry.py", line 83, in populate [Tue May 21 02:24:21.288370 2019] [:error] [pid 4423] [remote 127.0.0.1:140] raise RuntimeError("populate() isn't reentrant") [Tue May 21 02:24:21.288384 2019] [:error] [pid 4423] [remote 127.0.0.1:140] RuntimeError: populate() isn't reentrant [Tue May 21 02:24:46.028052 2019] [:error] [pid 4423] [remote 172.31.20.41:140] mod_wsgi (pid=4423): Target WSGI script '/opt/python/current/app/test/wsgi.py' cannot be loaded as Python module. [Tue May 21 02:24:46.028101 2019] [:error] [pid 4423] [remote 172.31.20.41:140] mod_wsgi (pid=4423): Exception occurred processing WSGI script '/opt/python/current/app/test/wsgi.py'. [Tue May 21 02:24:46.028208 2019] [:error] [pid 4423] [remote 172.31.20.41:140] Traceback (most recent call last): -
How to modify serialized attributes of objects in Django?
I need to change the field product to name because of how Google Enhanced Ecommerce requiers the data to be processed. https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#product-data https://developers.google.com/tag-manager/enhanced-ecommerce#purchases But my model has this field as product, is it possible to change it in the view? Or do I need to change it somehow in HTML using Javascript? view from django.core.serializers import serialize order_items = OrderItem.objects.filter(order=Order.objects.latest('id')) order_items = serialize('json', order_items, fields=['id', 'product', 'price']) # the fields needed for products template: <script> window.dataLayer = window.dataLayer || []; window.dataLayer.push({ event: 'eec.purchase', ecommerce: { currencyCode: 'PEN', purchase: { actionField: { id: {{ order_number }}, affiliation: 'Stickers Gallito E-Commerce', revenue: {{ total }}, shipping: {{ costo_despacho }}, coupon: '' }, products: JSON.parse('{{ order_items | safe }}') }, } }); </script> models.py class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) product = models.CharField(max_length= 200) sku = models.CharField(max_length=20) quantity = models.CharField(max_length= 200) size = models.CharField(max_length=200) price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name= 'PEN Price') file = models.FileField(upload_to='files', blank=True, null=True) comment = models.CharField(max_length=200, blank=True, null=True, default='') uploaded_at = models.DateTimeField(auto_now_add=True) -
Why do I receive DEBUG=True error when trying to connect to server?
Originally I was having issues with building a functioning login page and it led to errors due to import login and changed it to LoginView so it can find login and led to my next error. I am trying to load my login html online however I keep getting an error relating to settings.py and using Django for this. The error is relating to DEBUG=True and potentially changing it to false. Tried to change it to false but terminal refuses to connect and it shows that I must set settings.ALLOWED_HOSTS if DEBUG is False. I have no idea what this mean results online shows iep address etc. SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] I expected no errors and allow server to start running so I can access login html document via the site. -
Django - Change UserCreationForm - language
I made a UserCreationForm in views.py and calling it in my register.html file in templates of that app as {{ form.as_p }} It works fine, but I would like to change the lables of UserCreationForm to different language- as <label for="id_username">Username:</label> I would like to change that "Username" to "ユーザー名" Is it possible? What file should I change and how please? -
Django CharField accepting empty values when it shouldn't
I have the following model: class ClientDebt(models.Model): client_id = models.CharField(max_length=255) ... I was expecting this model to prevent records without a client_id, but I quite don't understand why I can create a ClientDebt without a client_id using a django shell (python manage.py shell_plus). Changing it to CharField(max_length=255, null=False, blank=False) and trying to create+execute new migrations also didn't work, as Django did not detected any changes. There is no default value from what I could see in previous migrations, but it seems to be recording "" (empty string) in the field. Can anybody tell me what is going on? Why is my model accepting null/blank values? Can this be a bug in Django? I'm using Django version 2.2.1 -
How to find user's patreon pledge tier using django-allauth for authentication
I’m using django-allauth to authenticate users (uses Patreon's API v1), which adds a json to the database with the info below. I would like to show extra content on the site if the user's pledge matches a particular tier (or is above one). { "attributes": { "about": null, "can_see_nsfw": true, "created": "2019-05-20T20:29:02.000+00:00", "default_country_code": null, "discord_id": null, "email": "admin@email.com", "facebook": null, "facebook_id": null, "first_name": "Adm", "full_name": "Adm Nsm", "gender": 0, "has_password": true, "image_url": "https://c8.patreon.com/2/200/21383296", "is_deleted": false, "is_email_verified": false, "is_nuked": false, "is_suspended": false, "last_name": "Nsm", "social_connections": { "deviantart": null, "discord": null, "facebook": null, "instagram": null, "reddit": null, "spotify": null, "twitch": null, "twitter": null, "youtube": null }, "thumb_url": "https://c8.patreon.com/2/200/21383296", "twitch": null, "twitter": null, "url": "https://www.patreon.com/user?u=21383296", "vanity": null, "youtube": null }, "id": "21383296", "relationships": { "pledges": { "data": [ { "id": "24461189", "type": "pledge" } ] } }, "type": "user" } At first I though relationships.pledges.data.id would have the ID of the current tier and with that I managed to add an extra block of content for a specific user, but apparently that was only wishful thinking; after testing with a second account the ID that I though was the pledge level seems to differ each time. I imagine I might need to request … -
Deployed Django project in heroku environment and the translation is not working
182/5000 I'm having problems with Django's default translate, in the development environment it works fine, when deploy is done on Heroku does not work. Here are the steps I did: My Environment URL: https://portalbigidea.herokuapp.com/ In my heroku environment this is the django .mo as the command lines below: You set up the buildpack below in the Heroku environment: heroku buildpacks:set https://github.com/piotras/heroku-buildpack-gettext.git $ heroku run ls locale/en/LC_MESSAGES Running ls locale/en/LC_MESSAGES on portalbigidea... up, run.3990 (Free) django.mo django.po Running ls locale/pt_BR/LC_MESSAGES on portalbigidea... up, run.8258 (Free) django.mo django.po settings/base.py ALLOWED_HOSTS = ["localhost", "127.0.0.1", ".herokuapp.com"] INSTALLED_APPS = 'django_adminlte', 'django_adminlte_theme', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] DATABASES = {'default': dj_database_url.config(conn_max_age=500, ssl_require=True)} CORS_REPLACE_HTTPS_REFERER = True HOST_SCHEME = "https://" SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", 'https') SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_SECONDS = 1000000 SECURE_FRAME_DENY = True STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATICFILES_DIRS = [os.path.join(BASE_DIR, "staticfiles")] STATICFILES_STORAGE = whitenoise.storage.CompressedManifestStaticFilesStorage' from django.utils.translation import ugettext_lazy as _ LOCALE_PATHS = (BASE_DIR + '\locale',) USE_I18N = True USE_L10N = True USE_TZ = True TIME_ZONE = 'UTC' LANGUAGE_CODE = 'pt-br' LANGUAGES = ( ('en', _('English')), ('pt-br', _('Brazilian Portuguese')), ) I am grateful for … -
How to slide down one list from a group of lists and close others with one click?
I have 4 un-ordered lists. Each one of them has many list items (li's). I want when I clicked on one list header all list items are displayed while close all other un-ordered lists' items. I have made one un-ordered list has 4 list items. Each one list has another un-ordered list and each one of them has many list item (nested lists). each list has one category for cities, provinces, and other link. once I click on "for example on first list header" ( cities in the same province), dropdown list is displayed. In the same time with the same click, All other lists' items all colssed "hidden". I have done the following code: <ul class="menu city_list"> <li classs="extend"> <a href=""> <h5 id="accordionItemHeading" class="category">cities in the same province </h5> </a> {% for city in citie_in_province %} <div class=" sss sss_close"> <ul class='category'> <li > <a href="">{{city.city_name}}</a> </li> </ul> </div> {% endfor %} </li> <li classs="extend"> <a href=""> <h5 id="accordionItemHeading" class="category">country cities </h5> </a> {% for city in citie_in_province %} <div class=" sss sss_close"> <ul class='category'> <li > <a href="">{{city.city_name}}</a> </li> </ul> </div> {% endfor %} </li> <li classs="extend"> <a href=""> <h5 id="accordionItemHeading" class="category">provinces </h5> </a> {% for city in … -
Relate models via Foreign Key using a string field (CharField)
I have an API which has two models. These models I would like to relate with a Foreign Key. Then, I want to send data, more specifically I want to send a string. If this string matches the name of the foreign key I want to create an instance. Like so: class Simulation(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1) project = models.ForeignKey(Project, on_delete=models.CASCADE,default=1, related_name="projects") class Project(models.Model): project_name = models.CharField(max_length=120) def __str__(self): return self.project_name I send data like so: def test_api_local(method='get', data={}): r = requests.request(method, ENDPOINT , data=data, headers=headers) return r test_api_local(method="post", data={"user":2, "project":1 }) Ok so that works. Like that I create an instance with the data. But what I would like to do, is to send the name of my project as a string and create a simulation object that has the name of my project in it. But right now I can only send integers. I tried setting the name of the project as a primary key, but I get a multiple key error. I tried setting it to unique, but it is also not working. I read that it is not advisable to use strings as foreign key, since it breaks generic foreign keys. But then, is there … -
Django ModelForm widget and non-widget field ordering
I have a django (1.11.9) ModelForm for events with times (start and end). When I display it to the user in a template I want last_field to be the last field in the form at the bottom: class EventForm(forms.ModelForm): dt = '%Y-%m-%d %H:%M' start = forms.DateTimeField( label="Start time (in event's local time)", required=False, input_formats=[dt] ) end = forms.DateTimeField( label="End time (in event's local time)", required=False, input_formats=[dt] ) class Meta: model = Event fields = [ 'name', 'flexibility', 'timezone', 'date_start', 'date_end', 'last_field', ] def __init__(self, *args, **kwargs): super(EventForm, self).__init__(*args, **kwargs) self.fields['date_start'].widget = forms.HiddenInput() self.fields['date_end'].widget = forms.HiddenInput() i = kwargs.get('instance') tz = pytz.timezone(i.timezone) if i and i.timezone else None if i and i.flexibility == Event.FLEXIBILITY_ONTIME and tz: self.fields['start'].initial = i.date_start.astimezone(tz).strftime(self.dt) if i.date_start else None self.fields['end'].initial = i.date_end.astimezone(tz).strftime(self.dt) if i.date_end else None else: self.fields['start'].initial = None self.fields['end'].initial = None however, even explicitly setting 'last_field' at the end of the fields = [] array (per docs https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/#changing-the-order-of-fields), the start and end widget fields in the form render below it out of the set field order. is there a way to override the widgets to force the ordering of the fields? thanks -
Problem to load Django application, errors in wsgi?
I don't understand error log, Django application not run on Python 3.6 and Django 2.2 Modules: astroid 2.2.5 certifi 2019.3.9 colorama 0.4.1 cymysql 0.9.13 Django 2.2 django-cymysql 2.2.0 isort 4.3.20 lazy-object-proxy 1.4.1 mccabe 0.6.1 mysql-connector-python 8.0.16 mysqlclient 1.4.2 Pillow 6.0.0 protobuf 3.7.1 pylint 2.3.1 pylint-django 2.0.9 pylint-plugin-utils 0.5 PyMySQL 0.9.3 pytz 2019.1 six 1.12.0 sqlparse 0.3.0 typed-ast 1.3.5 wheel 0.29.0 wincertstore 0.2 rapt 1.11.1 Traceback (most recent call last): File "/opt/passenger-5.3.7-3.el7.cloudlinux/src/helper-scripts/wsgi-loader.py", line 369, in <module> app_module = load_app() File "/opt/passenger-5.3.7-3.el7.cloudlinux/src/helper-scripts/wsgi-loader.py", line 76, in load_app return imp.load_source('passenger_wsgi', startup_file) File "/home/user/virtualenv/my_app/3.6/lib64/python3.6/imp.py", line 172, in load_source module = _load(spec) File "<frozen importlib._bootstrap>", line 684, in _load 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 "/home/user/my_app/passenger_wsgi.py", line 8, in <module> wsgi = imp.load_source('wsgi', 'passenger_wsgi.py') File "/home/user/virtualenv/my_app/3.6/lib64/python3.6/imp.py", line 172, in load_source module = _load(spec) File "<frozen importlib._bootstrap>", line 684, in _load 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 "passenger_wsgi.py", line 8, in <module> wsgi = imp.load_source('wsgi', 'passenger_wsgi.py') File "/home/user/virtualenv/my_app/3.6/lib64/python3.6/imp.py", line 170, in load_source module = _exec(spec, sys.modules[name]) File "<frozen importlib._bootstrap>", line 618, in _exec File "<frozen … -
How to retrieve current logged in user for dynamic file name use in model
I'm trying to set the current 'upload_to=' directory equal to the current logged-in user's username so that each file uploaded is saved into the user's own directory. I have tried to follow the django documentation which looks similar to this... from django.db import models def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user.id, filename) class UploadReports(models.Model): upload = models.FileField(upload_to=user_directory_path, null=True) I have also tried to add RequestMiddleware to achieve this but it felt wrong as I was implementing it. I want it to grab the current logged in user and use it in the directory path. The error that comes up is: AttributeError at /stylist/ 'UploadReports' object has no attribute 'user' -
How can i make a 'view_count' in django-rest-framework?
Thank you all the time. I will ask. (I'm sorry for not good at English very well) I'm using react as a front end, so I just started the Django rest framework. but The django-rest-framework is confusing for me, so I ask. As a simple example, I want to automatically increment view_count when I click show page in crud. What function should I write in app_name/api/views.py ? here is my code .. # notice/models.py from django.db import models # Create your models here. class Notice(models.Model): title = models.CharField(max_length=120) description = models.TextField() view_count = models.IntegerField(default=0) def __str__(self): return self.title # notice/api/views.py from rest_framework import viewsets from notice.models import Notice from .serializers import NoticeSerializer from django.http import JsonResponse class NoticeViewSet(viewsets.ModelViewSet): serializer_class = NoticeSerializer queryset = Notice.objects.order_by('title') # notice/api/serializers.py from rest_framework import serializers from notice.models import Notice class NoticeSerializer(serializers.ModelSerializer): class Meta: model = Notice fields = ('id','title','description','view_count') -
Need to iterate over queryset of student answers and provide individual "feedback" form field for each one
I am building a homework database application that will make answering, grading and correcting homework simpler than it is now. To do this I have forms for students to fill in an answer to a question that has been assigned to them, the question is then marked as ready to be graded and the teacher's view can then see all the questions that are ready to be graded per assignment. The trouble that I am having is inserting a form field into each answer where feedback could be given; I suppose the simplest way would be to load one question and its answer per page and have a feedback form field there, but what I would like to do is to iterate over all the questions that have been answered on a given assignment and display them all on one page so that they can be graded quickly. I have tried to insert just a form field into the for loop, and had some success, but when I submit I can't pull the question id out of the loop to populate the (required) foreign key pointing from the feedback model to the original question-answer. I've toyed with multiple forms on …