Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Cant change audio currenttime
I'm creating an article app where you can add an audio file. I can play the audio but whenever I try to change currenttime of the song it starts from 0. I added static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) to my urls.py. my template (removed some unnecessary parts): var songs = [ {% for audio in article.audio_set.all %} "{{audio.file.url}}", {% endfor %} ], title =[ {% for audio in article.audio_set.all %} "{{audio.name}}", {% endfor %} ] var songTitle = $("#songTitle"), songSlider = $("#songSlider"), currentTime = $("#currentTime"), duration = $("#duration"), volumeSlider = $("#volumeSlider"), nextSongTitle = $("#nextSong"); var song = new Audio(), currentSong = 0, oldvolume = 0.5; var nextSong; $(document).ready(function(){ loadSong(); }); function loadSong(play=false){ nextSong = currentSong + 1; if (nextSong + 1 > songs.length) {nextSong = 0;} nextSongTitle.html("<b>Nächstes Audio: </b>" + title[nextSong]); songTitle.text(title[currentSong]); song.src = songs[currentSong]; song.currentTime = 0; song.playbackRate = 1; song.volume = volumeSlider.val(); if (play) song.play(); song.addEventListener('loadeddata',() => { showDuration(); }); } setInterval(updateSongSlider, 100); songSlider.on("input", function(){ var newValue = parseFloat(songSlider.val()); song.currentTime = newValue; }); When I navigate to the file (in browser) I can play it too but I can't change currenttime. -
Output python script in django dashboard app
Currently I'm learning to work with the Django framework. I'm trying to make a dashboard that can collect some output of scripts I want to make (in Python). I can't really find a conclusive answer to how to pipe the output of a python script through Django in my app. For instance, I want a script that runs a couple of ARP calls and pings in a network and have the output in a dashboard. Of course python is probably not the only language I'm going to use for scripting, maybe I will use some Bash or Golang also. I hope someone is able to help my in the right direction. Thank you in advance! -
Key-value pairs in SQL table
I am building a Django app and I would like to show some statistics on the main page, like total number of transactions, percentage of successful transactions, daily number of active users etc. I don't want to calculate these values in the view every time a user requests the main page for performance reasons. I thought of 2 possible solutions. (1) Create a number of one-record tables Create a table for each of the statistics, e.g.: from django.db import models class LastSuccessfulTransactionDate(models.Model): date = models.DateTimeField() class TotalTransactionAmount(models.Model): total_amount = models.DecimalField(max_digits=8, decimal_places=2) # ... and make sure that only one record exists in each table. (2) Create a table with key-value data class Statistics(models.Model): key = models.CharField(max_length=100) value = models.TextField() and save the data by doing: from datetime import datetime from decimal import Decimal import pickle statistics = { 'last_successful_transaction_date': datetime(2010, 2, 3), 'total_transaction_amount': Decimal('1234.56'), } for k, v in statistics.items(): try: s = Statistics.objects.get(key=k) except Statistics.DoesNotExist: s = Statistics(key=k) s.value = base64.b64encode(pickle.dumps(v, pickle.HIGHEST_PROTOCOL)).decode() s.save() and retrieve by: for s in Statistics.objects.all(): k = s.key v = pickle.loads(base64.b64decode(s.value.encode())) print(k, v) In both cases the data would be updated every now and then by a cron job (they don't have to be … -
Django: NOT NULL constraint failed: Cart.cart_id
I'm trying to create an Ecommerce site. I need to make a 'Cart' app that will generate a Cart object which will hold the items that the user wants to shop. However, when adding an item to the Cart I get: IntegrityError at /cart/add/3/ NOT NULL constraint failed: Cart.cart_id 1.- Cart object will have an ID, that will be the user's sessions ID. This is the function that will get the session ID: def _card_id(request): cart = request.session.session_key if not cart: cart = request.session.create() return cart views.py from django.shortcuts import render, redirect from shop.models import Product from .models import Cart, CartItem from django.core.exceptions import ObjectDoesNotExist # Create your views here. def _card_id(request): cart = request.session.session_key if not cart: cart = request.session.create() return cart def add_cart(request, product_id): product = Product.objects.get(id = product_id) try: cart = Cart.objects.get(cart_id = _card_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create( cart_id = _card_id(request) ) cart.save() try: cart_item = CartItem.objects.get(product = product, cart = cart) cart_item.quantity += 1 cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product = product, quantity= 1, cart = cart, ) cart_item.save() return redirect('cart:cart_detail') def cart_detail(request, total = 0, counter = 0, cart_items = None): try: cart = Cart.objects.get(cart_id = _card_id(request)) cart_items = CartItem.objects.filter(cart = cart, active=True) … -
Get next id from the db table and assign suffix django 2
I am working on this issue for last few hrs and landed no where. Here is my problem. I have a model that will track the shipments and I want to create the shipment number automatically when the form is loaded fro a new shipment. The logic is to get the next available Id from the database and add some test and store. My model is class Shipment(models.Model): id = models.AutoField(primary_key=True) shipmentNumber = models.CharField(max_length=50) shipmentDate = models.DateTimeField() dateCreated = models.DateTimeField(default=timezone.now) dateModified = models.DateTimeField(default=timezone.now) def __str__(self): return self.shipmentNumber and the view is def createshipment(request): if request.method == "POST": form = CreateShipmentForm(request.POST) if form.is_valid(): shipment = form.save(commit=False) shipment.shipmentNumber = request.shipmentNumber shipment.shipmentDate = timezone.now() shipment.save() else: form = CreateShipmentForm() form.shipmentNumber = 'get the next id and assign suffix' context ={'form' : form} return render(request,'../templates/mainSection/createshipment.html',context) I tried to retrieve the data by getting all the shipments in the db and count them and go form there. But I ended up with "didn't return an HttpResponse object. It returned None instead." Any thought on how should I create the shipment number? Thanks -
How to configure subdomain to specific port
I have two projects 1: is wordpress running on apache (main website thespatio.com/45.33.10.149) 2: A Django Application running on Nginx using same IP with 81 port. (45.33.10.149:81). I want to configure above two apps so that when some one hit http://thespatio.com it should show main website and if some hit http://or.thespatio.com it should show my django application. I have seen many fix but none work for me. I tried virtual host like proxypass and proxy_reverse but apache stopped working. below are the two virtual hosts conf file Main Website settings (conf) <VirtualHost *:80> ServerAdmin admin@example.com ServerName thespatio.com ServerAlias www.thespatio.com DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> Django App (conf) <VirtualHost *:80> ServerAdmin admin@test.com ServerName or.thespatio.com ServerAlias www.thespatio.com ProxyPass / http://or.thespatio.com:81/ ProxyPassReverse / http://or.thespatio.com:81/ ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> Any help would be appreciated. Thanks in advance -
Error while Installing mysql-python on CentOS 7
While working through a Pluralsight tutorial, https://app.pluralsight.com/library/courses/docker-ansible-continuous-delivery/exercise-files, I'm having an issue getting mysql to work with django. Running pip install mysql-python produces this output: Collecting mysql-python Using cached https://files.pythonhosted.org/packages/a5/e9/51b544da85a36a68debe7a7091f068d802fc515a3a202652828c73453cad/MySQL-python-1.2.5.zip Building wheels for collected packages: mysql-python Running setup.py bdist_wheel for mysql-python ... error Complete output from command /home/nick/dev/demos/todobackend/venv/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-YYanvu/mysql-python/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d /tmp/pip-wheel-ED_q9B --python-tag cp27: running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-2.7 copying _mysql_exceptions.py -> build/lib.linux-x86_64-2.7 creating build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-2.7/MySQLdb creating build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/REFRESH.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants running build_ext building '_mysql' extension creating build/temp.linux-x86_64-2.7 gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_ SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 -I/usr/include/mysql -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o -m64 _mysql.c:44:23: fatal error: my_config.h: No such file or directory #include "my_config.h" ^ compilation terminated. error: command 'gcc' failed … -
How to unit test Django views when base template has arguments in different, unrelated views/hrefs
For example, I have different views that I am trying to test functionality of, but I can't get past the issue where I have different hrefs that have arguments. For example, in my navbar, which is applied to every view through the base template, I have a link to the user's profile. This looks like: url(r'^(?P<username>[\w.@+-]+)/$', user_profile, name='user-profile'). So this relies on getting the username as an argument: <a class="dropdown-item" href="{% url 'user-profile' request.user.username %}>. I have setup my test like: self.client.force_login(user=self.test_user) request = self.client.get(reverse('home')) request.user = self.test_user It fails at the second line, so I assume it never gets the opportunity to see the request.user. Because I am not directly calling the view in the navbar, but linking to it, how could I go about testing for this without getting a Reverse for 'user-profile' with arguments '('',)' not found -
Django 2.1 reset_password()
I am new in django. In Django version 2.1 has been deleted reset_password() function. How i should add on admin page password reset for admin now? -
Building Django-Projects on GCPs Cloud-Build
Recently, we started working to convert an established Django project from a docker stack to Google App Engine. On the way, Google Cloud Build turned out to come handy. Cloudbuild takes care of a few items in preparation of rolling out, in particular the front end part of the application. Now when it comes to python and Django specific tasks, the obvious choice is to resort to cloudbuild as well. Therefore we tried to follow the pattern Google explains with their official NPM cloud-builder (here) The issue we are facing is the following. When building with the official python image, the buildsteps are set up as followed: steps: [...] 8 - name: 'python:3.7' 9 entrypoint: python3 10 args: ['-m', 'pip', 'install', '-r', 'requirements.txt'] 11 - name: 'python:3.7' 12 entrypoint: python3 13 args: ['./manage.py', 'collectstatic', '--noinput'] This works just fine for the first step, to install all requirements. GAE does that when deploying the application as well, but here it's necessary to collectstatic from the repository and installed django apps, before uploading them. While the first step succeeds with the above, the 2nd step fails with the following error: File "./manage.py", line 14, in <module> ) from exc ImportError: Couldn't import … -
Annotate returning individual elements rather than grouping
Here are my models: class Submission(models.Model): user = models.ForeignKey(to=DefaultUser, on_delete=models.CASCADE) total_score = models.DecimalField() Now I want to get the count of submissions for each user And here is the query that I am trying Submission.objects.values('user').annotate(Count('id')) And the output is: {'user': 1, 'id__count': 1} {'user': 1, 'id__count': 1} {'user': 1, 'id__count': 1} {'user': 1, 'id__count': 1} {'user': 2, 'id__count': 1} {'user': 2, 'id__count': 1} {'user': 3, 'id__count': 1} Whereas the output that I require is: {'user': 1, 'id__count': 4} {'user': 2, 'id__count': 2} {'user': 3, 'id__count': 1} What am I doing wrong? -
Data.append and bulk_create
It is necessary to write the broken data into the sqlite tables, but append takes 1 argument, how to solve the problem? def handle_parameters_upload(request, file): wb = openpyxl.load_workbook(file, read_only=True) first_sheet = wb.get_sheet_names()[0] ws = wb.get_sheet_by_name(first_sheet) data = [] for row in ws.iter_rows(row_offset=1): recipe = Recipe.objects.create(par_recipe=row[1].value) line = Line.objects.create(par_machine=row[2].value) order = Order.objects.create(par_fa=row[3].value) parameter = Parameter.objects.create( par_rollennr=row[5].value, par_definition_id=row[6].value, par_name=row[7].value ) measurements = Measurements.objects.create( par_value=row[8].value, id_line=line, id_recipe=recipe, id_order=order, id_parameter=parameter ) data.append(parameter, order, line, measurements, recipe) ???.objects.bulk_create(data) return True And how to use the following expression ???.objects.bulk_create(data), after append -
Create autocomplete based on a defined field in the forms.py file. Django -Python.
It tries to create the simplest autocomplete field based on a defined field (ChoiceField) in the forms.py file. I was looking at the information forum, but most of all the answers refer to the autocomplete from the models.py file. An example of a field that is trying to create here. How can I do it in the easiest way? Any help will be appreciated. forms.py class BasicForm(forms.Form): trade = forms.ChoiceField(choices=TYPE_WORK_CHOICES) app_choices.py LOCATION_CHOICES = ( (1, 'trade_1'), (2, 'trade_2'), (3, 'trade_3'), ) views.py def home(request): form = BasicForm(request.POST) if form.is_valid(): cd = form.cleaned_data trade = cd['trade'] query_string = urlencode({'trade': trade}) next_url = '{}?{}'.format(reverse('app:search'), query_string) return HttpResponseRedirect(next_url) return render(request, 'home.html', {'form': form}) -
Django: How to save model instances related by foreign key?
Using custom Django's manage.py commands, I want to fill the database with data, extracted from .tsv file. The structure of db models is shown below. The question is how to tell Django to create and save all the objects related to the ClassificationJob from a data: 'Hey, Django, here is a job with identifier=12231 and link=sample.com, and here is data from file for you' -> 'Now, please, save ClassificationJobTask tasks from data[tasks_index], ClassificationJobResult results from data[results_index],ClassificationJobImage from data['images_index] and provide the relation to my ClassificationJob' import uuid from django.db import models from django.core.validators import MinValueValidator class ClassificationJob(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) identifier = models.CharField(default=None, unique=True, max_length=10) link = models.URLField(default=None) class Meta: db_table = 'classification_jobs' class ClassificationJobTask(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) classification_job = models.ForeignKey(to=ClassificationJob, on_delete=models.CASCADE) assignment_id = models.CharField(unique=True, max_length=36) worker_id = models.CharField(unique=True, max_length=32) points = models.PositiveIntegerField(default=0) class Meta: db_table = 'classification_jobs_tasks' class ClassificationJobResult(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) classification_job_task = models.ManyToManyField(to=ClassificationJobTask) classification_job = models.ForeignKey(to=ClassificationJob, on_delete=models.CASCADE) image_name = models.CharField(max_length=50) image_url = models.URLField() init_result = models.IntegerField(default=-1, validators=[MinValueValidator(-1)]) class Meta: db_table = 'classification_jobs_results' class ClassificationJobImage(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) classification_job = models.ForeignKey(to=ClassificationJob, on_delete=models.CASCADE) image_name = models.CharField(max_length=50) image_url = models.URLField(max_length=50) result = models.IntegerField(default=-1, validators=[MinValueValidator(-1)]) class Meta: db_table = 'classification_jobs_images' MANAGE.PY COMMAND from … -
Django Channels Connect to External Websocket
I'm new to Django and Channels and so far I couldn't find any solution to the issue that I face: I need to communicate with an external WebSocket, to process received data and then sent it to some Channels groups or maybe start some Celery tasks based on that output. As I've understood it's not a good practice to put that logic inside Consumer. What is the right way of doing this in Django? Thanks -
Django sockets with redis and Nginx using uwsgi : No module named ws4redis
I am trying to configure my django app on an amazon ec2 instance and my app uses Django channels for websockets. It uses Redis as a channel layer. I was going over this article and it says to launch a separate uwsgi instance using the following code import os import gevent.socket import redis.connection redis.connection.socket = gevent.socket os.environ.update(DJANGO_SETTINGS_MODULE='my_app.settings') from ws4redis.uwsgi_runserver import uWSGIWebsocketServer application = uWSGIWebsocketServer() and then I can launch my uwsgi socket using the following command uwsgi --virtualenv /path/to/virtualenv --http-socket /path/to/web.socket --gevent 1000 --http-websockets --workers=2 --master --module wsgi_websocket however after using that command I get the error *** Operational MODE: preforking+async *** Traceback (most recent call last): File "./main/wsgi_websocket.py", line 6, in <module> from ws4redis.uwsgi_runserver import uWSGIWebsocketServer ImportError: No module named 'ws4redis' Any suggestions on how I can fix this ? -
django mysql connection error inside docker-compose while running
Dockerfile FROM python:3.6 ENV PYTHONUNBUFFERED 1 WORKDIR /usr/src/govtcareer_api COPY ./ /usr/src/govtcareer_api RUN pip install -r requirements.txt CMD ["/bin/bash"] docker-compose.yml version: "3" services: govtcareer_api: container_name: govtcareer build: . command: "bash -c 'python manage.py migrate --no-input && python manage.py runserver 0.0.0.0:8000'" working_dir: /usr/src/govtcareer_api ports: - "8000:8000" volumes: - ./:/usr/src/govtcareer_api links: - mysql #db mysql: image: mysql restart: always ports: - "3306:3306" environment: MYSQL_DATABASE: "freejobalert" MYSQL_USER: "root" MYSQL_PASSWORD: "Thinkonce" MYSQL_ROOT_PASSWORD: "Thinkonce" MYSQL_HOST: "mysql" MYSQL_PORT: "3306" MYSQL_ALLOW_EMPTY_PASSWORD: "yes" django-database: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'freejobalert', 'USER': 'root', 'PASSWORD': 'Thinkonce', 'HOST': 'mysql', 'PORT': '3306', } } errors: govtcareer | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 379, in check govtcareer | include_deployment_checks=include_deployment_checks, govtcareer | File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 59, in _run_checks govtcareer | issues = run_checks(tags=[Tags.database]) govtcareer | File "/usr/local/lib/python3.6/site-packages/django/core/checks/registry.py", line 71, in run_checks govtcareer | new_errors = check(app_configs=app_configs) govtcareer | File "/usr/local/lib/python3.6/site-packages/django/core/checks/database.py", line 10, in check_database_backends govtcareer | issues.extend(conn.validation.check(**kwargs)) govtcareer | File "/usr/local/lib/python3.6/site-packages/django/db/backends/mysql/validation.py", line 9, in check govtcareer | issues.extend(self._check_sql_mode(**kwargs)) govtcareer | File "/usr/local/lib/python3.6/site-packages/django/db/backends/mysql/validation.py", line 13, in _check_sql_mode govtcareer | with self.connection.cursor() as cursor: govtcareer | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 255, in cursor govtcareer | return self._cursor() govtcareer | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 232, in _cursor govtcareer | self.ensure_connection() govtcareer | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection govtcareer … -
Django 2.1: How to import models in a custom .py file?
I'm currently working on a Django project that has the following structure django_project/ django_app/ views.py models.py urls.py src/ myCustomFile.py In this context, I would like to import the models in myCustomFile.py. Usually, to import models in other files I include the following line of code from django_app.models import * but apparently, I do not seem to work. I think that the problem could be due to the fact that myCustomFile.py is in a subfolder. For this reason, I also tried to move myCustomFile.py at the same level of models.py but also, in this case, I get the error ModuleNotFoundError: No module named 'django_app' Do you have any suggestion to solve this problem? Thank you -
Creating records by model
Suppose I have such models: class Recipe (models.Model): par_recipe = models.CharField(max_length=200) class Line (models.Model): par_machine = models.CharField(max_length=200) class Measurements (models.Model): par_value = models.IntegerField(default=0) id_line = models.ForeignKey(Line) id_recipe = models.ForeignKey(Recipe) Do I understand correctly that in this way I have a 1: 1 relationship, and adding entries ids will be automatically created id_line,id_recipe. I will add for example: for row in ws.iter_rows(row_offset=1): recipe =Recipe() line = line() measurements = Measurements() recipe.par_recipe = row[1].value line.par_machine = row[2].value measurements.par_value = row[8].value Do I understand correctly? If not, tell me pls -
Updating django models with multiprocessing pool locks up database
I use Jupyter Notebook to play with the data that I store in django/postgres. I initialize my project this way: sys.path.append('/srv/gr/prg') os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'prg.settings') if 'setup' in dir(django): django.setup() There are many individual processes that update the data and I wanted to multithread it to speed up the process. Everything works well when I do updates in a single thread or use sqlite. def extract_org_description(id): o = models.Organization.objects.get(pk=id) logging.info("Looking for description for %s" % o.symbol) try: content = open('/srv/data/%s.html' % o.symbol) except FileNotFoundError: logging.error("HTML file not found for %s" % o.symbol) return doc = BeautifulSoup(content, 'html.parser') desc = doc.select("#cr_description_mod > div.cr_expandBox > div.cr_description_full.cr_expand") if not desc or not desc[0]: logging.info("Cannot not find description for %s" % o.symbol) return o.description = desc[0].text o.save(update_fields=['description']) logging.info("Description for %s found" % o.symbol) return("done %s" % id) And this will not work: p = Pool(2) result = p.map(extract_org_description, orgs) print(result) Most of the time, it will hang until I've interrupted it, without any particular error, sometimes postgres will have "There is already a transaction in progress", sometimes I see "No Results to fetch" error. Playing with the pool size I could make it work maybe once or twice but it's hard to diagnose what exactly the … -
Django: Get currently logged in user, not user from request
I have an external app - on another server and outside of Django project - calling list API view in my Django app and I need to limit the output of the API only to data owned by currently logged in user. So I cannot user request.user, because the request is coming from outside and the user will always be AnonymousUser. Instead, I would need to get the user that is currently logged in my Django app. How do I do that? -
Django model saving on User login
I have a model like this: class Project (models.Model): ''' Defines a project ''' user = models.ForeignKey( Profile, on_delete = models.CASCADE ) ... name = models.CharField ( verbose_name = _('Project Title'), max_length = 100 ) dt_created = models.DateTimeField(editable = False) dt_lastmod = models.DateTimeField(blank=True, null=True) objects = ProjectManager() tags = TaggableManager() class Meta: ordering = ["-id"] def __str__(self): return u'%s' % (self.name) def save(self, *args, **kwargs): if not self.id: self.dt_created = timezone.now() self.dt_lastmod = timezone.now() super(Project, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('view-project', kwargs={'slug': self.slug}) When the 'User' linked to the model through the user field logs in, the model saves and the dt_lastmod is reset. Why? How do I stop this behaviour? -
Related Model cannot be resolved problem when I create user model
In my models, I created UserManager and User and I added this in my settings: AUTH_USER_MODEL = "myapp.User" but when I migrate it raises error related model cannot be resolved. I searched the internet but I couldn't find the answer which solves my problem -
How to run a javascript function in Django admin after the form has been loaded?
The question is pretty self-explanatory. I tried to follow the docs, as found here, however, it seems the function runs before the form has been loaded, which is not useful to me. Any way to do this? Thanks. -
An error was reported while closing the websocket connection(...failed: Invalid frame header)
I use django and dwebsocket. There is a warning in my browser console. Also it runs well. There is no problem :). But i wondered. enter image description here enter image description here views.py import threading from django.shortcuts import render_to_response from dwebsocket.decorators import accept_websocket def index(request): return render_to_response('index.html', {}) clients = [] @accept_websocket def echo(request): if request.is_websocket: lock = threading.RLock() try: lock.acquire() clients.append(request.websocket) for message in request.websocket: if not message: break for client in clients: client.send(message) finally: clients.remove(request.websocket) lock.release()