Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Postgre: 2 different query but same result
I have problem with my queries in postgre sql. First Query: SELECT first_name, last_name, service_name, max(usluga) FROM ( SELECT first_name, last_name, service_name, count(scheduler_scheduleevents.id) as usluga FROM workers_workers LEFT JOIN scheduler_scheduleevents ON scheduler_scheduleevents.worker_id = workers_workers.id AND is_start_time = True AND is_active = False AND ( scheduler_scheduleevents.date < %s or ( scheduler_scheduleevents.date = %s and time < %s ) ) LEFT JOIN user_settings_userservices ON user_settings_userservices.id =scheduler_scheduleevents.service_type_id WHERE workers_workers.salonid_id= %s AND scheduler_scheduleevents.worker_id = %s GROUP BY workers_workers.id, service_name) as x GROUP BY x.first_name, x.last_name, x.service_name And Second: SELECT first_name, last_name, service_name, min(usluga) FROM ( SELECT first_name, last_name, service_name, count(scheduler_scheduleevents.id) as usluga FROM workers_workers LEFT JOIN scheduler_scheduleevents ON scheduler_scheduleevents.worker_id = workers_workers.id AND is_start_time = True AND is_active = False AND ( scheduler_scheduleevents.date < %s or ( scheduler_scheduleevents.date = %s and time < %s ) ) LEFT JOIN user_settings_userservices ON user_settings_userservices.id =scheduler_scheduleevents.service_type_id WHERE workers_workers.salonid_id= %s and scheduler_scheduleevents.worker_id = %s GROUP BY workers_workers.id, service_name) as x GROUP BY first_name, last_name, service_name First query should give me only 1 service which was made most time and second query should give me too only 1 service which was made least times. Problem is both queries give me same results: list of all services and how many times each … -
Django IllegalMonthError
I have an url: url(r'^costs/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/$', views.day_stats_detail, name='day_stats_detail'), I've created a link to next page, based on: mr = calendar.monthrange(int(year), int(month)) next_year = int(year) next_month = int(month) next_day = int(day)+1 if next_day > mr[1]: next_day = str(1).zfill(2) next_month = str(next_month +1).zfill(2) if int(next_month) > 12: next_month = str(1).zfill(2) next_year += 1 another = "/costs/{}/{}/{}/".format(next_year, next_month, next_day) And everything is fine, but I've receveid error when I try skip to the 01.01.2017: IllegalMonthError at /costs/2017/01/01/ bad month number 0; must be 1-12 What's going on? -
Django on Elastic Beanstalk "requirements.txt" is invalid
I'm trying to deploy a django project with Elastic Beanstalk cli. I followed the Official Amazon Tutorial as well as this Tutorial on realpython.com. The Deploymentprocess works fine as long as I stick to a newly created Django Project with just a view dependencies for pip. When try it with my Django Project The Deployment fails because the requirements.txt is invalid. I created it inside my virutalenv like this: pip freeze > requirements.txt braintree==3.32.0 cffi==1.9.1 cryptography==1.7 Django==1.10.4 django-allauth==0.29.0 django-betterforms==1.1.4 django-contrib-comments==1.7.3 django-formtools==1.0 django-payments==0.9.6 django-tinymce==2.4.0 enum34==1.1.6 idna==2.1 ipaddress==1.0.17 oauthlib==2.0.1 Pillow==3.4.2 pyasn1==0.1.9 pycparser==2.17 PyJWT==1.4.2 python-openid==2.2.5 requests==2.12.3 requests-oauthlib==0.7.0 six==1.10.0 stripe==1.43.0 suds-jurko==0.6 xmltodict==0.10.2 In my despair I tried to activate the dependencies one by one. The Deployment process is so slow that I gave up after a while. But now I know now that Django==1.10.4, django-allauth==0.29.0, django-betterforms==1.1.4, django-contrib-comments==1.7.3, django-formtools==1.0 and django-tinymce==2.4.0 are not the problem. With django-payments==0.9.6 it fails but its not the only dependency that causes the problem. This is in my activity.log: error: command 'gcc' failed with exit status 1 ---------------------------------------- Command "/opt/python/run/venv/bin/python2.7 -c "import setuptools, tokenize; __file__='/tmp/pip-build-BF9Oen/cffi/setup.py'; exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-BsXWzo-record/install-record.txt --single-version-externally-managed --compile --install-headers /opt/python/run/venv/include/site/python2.7/cffi" failed with error code 1 in /tmp/pip-build-BF9Oen/cffi You are using pip version … -
Get latest saved object values in Django admin panel
Many toys have same information(for example description and price) how can i customise my admin.py in order to get last saved object values, everytime when i press add new toy in admin panel and display them in my input fields. models.py class Toy(models.Model): name = models.CharField(max_length=255) description = TextField() quantity = models.FloatField(default=0.0) price = models.FloatField() def __unicode__(self): return self.name admin.py admin.site.register(Toy) -
Jsonify for django [duplicate]
This question already has an answer here: Creating a JSON response using Django and Python 10 answers I'm using jsonify function to return in Flask: return jsonify(results = results_arr) and I'm getting output like this: {"results":[{"image":"103901.jpg","score":"2.51322851309"},{"image":"103401.jpg","score":"5.93861453397"}]} I tried to do this in django by: return json.dumps(results = results_arr) But it doesn't work like on jsonify on Flask, can someone help me with this? -
Django With MSSQL using Pyodbc: Model Forms not being saved
Django version 1.8.16 pyodbc Version: 3.0.11b16 I have been trying to make a view/submit form for an project I've been doing . The basic aim i need to achieve is to view and edit/save the data in the form using stored procedure in mssql 2014. I am able to use stored procedure in the view page but have not been able to do so with the edit item and add new item models.py class Patient(models.Model): patientid = models.AutoField(db_column='PatientID', primary_key=True) pyear = models.DecimalField(db_column='Pyear', max_digits=10, decimal_places=0, blank=True, null=True) dref = models.DecimalField(db_column='DRef', max_digits=10, decimal_places=0, blank=True, null=True) title = models.TextField(db_column='Title', blank=True, null=True) fname = models.TextField(db_column='FName', blank=True, null=True) lname = models.TextField(db_column='LName', blank=True, null=True) dob = models.DateTimeField(db_column='DOB', blank=True, null=True) pamonth = models.TextField(db_column='PAMonth', blank=True, null=True) payear = models.TextField(db_column='PAYear', blank=True, null=True) padays = models.TextField(db_column='PADays', blank=True, null=True) sex = models.TextField(db_column='Sex', blank=True, null=True) views.py def view_patient(request): if request.method == 'POST': form = viewpatientform(request.POST) return render(request, 'lis/view.html', {'form': form}) else: form = viewpatientform() if form.is_valid(): procedure = procedures() ret = procedure.view_patientsp(request.POST['fields']) return render_to_response('lis/view.html', {'form': form}) urls.py urlpatterns = [ url(r'^$', views.pat_list, name='index'), url(r'^view/(?P<patid>\d+/)$', views.view_patient, name='viewpatient'), ] view.html {% block body %} {% load materializecss %} {{ form|materializecss }} <button type="submit" class="btn btn-primary">Submit</button> {% endblock %} -
Django: Count by day, with 0 for days with no records
I want to get the count of records over 14 days I'm currently doing: class Invitation(models.Model): ... start_date = models.DateTimeField(default=timezone.now) all_invitations = Invitation.objects.all() days14 = all_invitations.filter(start_date__range=[today - timedelta(days=7), today + timedelta(days=8)]).annotate(day=TruncDay('start_date')).values('day').annotate(count=Count('id')).values('day', 'count').order_by('day') However, this does not give me the days for which there are 0 invitations. How do I achieve that? -
View Profile page as another user in django
so i have a profile page view you see as a loged in user but i wanted to add a view so loged in users can view the profile page as well ,but i'm not really sure i'm doing it the right way urls.py url(r'^accounts/profile/', main_views.uprofile, name='uprofile'), #the page you see as my profile url(r'^profile/(?P<pk>\d+)/$', main_views.oprofile, name='oprofile'), # the page i use so other users can view the profile page url(r'^accounts/update/(?P<pk>\d+)/', User_Profile_views.edit_user, name='edit_user'), #Custom update profile page main.views.py @login_required(login_url='/accounts/login/') def uprofile (request): context = locals() template = 'profile.html' return render (request, template, context) def oprofile (request, pk): user = User.objects.get(pk=pk) context = locals() template = 'profile.html' return render (request, template, context) -
How can I pass a variable from Django template to javascript
I have a django view and template as shown below: view code: def incTree(request): json_filepath = FileFieldView.json_fpath json_string = FileFieldView.json_string # this is json dump of a nested dictionary return render(request, 'template.html', locals()) I am able to access this "json_filepath" and "json_string" in my template using: <body onload="init()"> <p>{{ json_filepath }} </p> <p>{{ json_string }} </p> <div id="sample"> <div id="myDiagramDiv" style="background-color: white; border: solid 1px black; width: 100%; height: 700px"></div> </div> </body> I want to pass json_string(or the dictionary it contains) to the javascript code that I am writing in the template code itself using tag Would anyone please suggest a feasible way to achieve this? Thank you.. -
Testing performance of container to ensure SLA
There are three responsibilities: Container provider: Provide a computing container with enough performance. In this case virtual machine with full linux root access. Application provider. That's us. We provide a Django app QA: They are testing that the service of our application has enough performance. If QA thinks the performance is not good enough, they blame us, the application provider. How can we ensure that the container is fast enough? Is there a common way to test the performance of a provided container? Background: I don't know (and I don't want to know) if the hypervisor is running VMWare, kvm or different. I would like to have a simple way to test the performance of the container every 15 minutes. The testing should not slow down the service, since it is running in production. -
add_periodic_task doesn't schedule the task with Celery 4.0.1
I'm using Celery 4.0.1 with Django 1.10 and I have troubles scheduling tasks (running a task works fine). Here is the celery configuration: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') app = Celery('myapp') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) app.conf.BROKER_URL = 'amqp://{}:{}@{}'.format(settings.AMQP_USER, settings.AMQP_PASSWORD, settings.AMQP_HOST) app.conf.CELERY_DEFAULT_EXCHANGE = 'myapp.celery' app.conf.CELERY_DEFAULT_QUEUE = 'myapp.celery_default' app.conf.CELERY_TASK_SERIALIZER = 'json' app.conf.CELERY_ACCEPT_CONTENT = ['json'] app.conf.CELERY_IGNORE_RESULT = True app.conf.CELERY_DISABLE_RATE_LIMITS = True app.conf.BROKER_POOL_LIMIT = 2 app.conf.CELERY_QUEUES = ( Queue('myapp.celery_default'), Queue('myapp.queue1'), Queue('myapp.queue2'), Queue('myapp.queue3'), ) Then in tasks.py I have: @app.task(queue='myapp.queue1') def my_task(some_id): print("Doing something with", some_id) In views.py I want to schedule this task: def my_view(request, id): app.add_periodic_task(10, my_task.s(id)) Then I execute the commands: sudo systemctl start rabbitmq.service celery -A myapp.celery_app beat -l debug celery worker -A myapp.celery_app But the task is never scheduled. I don't see anything in the logs. The task is working because if in my view I do: def my_view(request, id): my_task.delay(id) The task is executed. If in my configuration file if I schedule the task manually, like this it works: app.conf.CELERYBEAT_SCHEDULE = { 'add-every-30-seconds': { 'task': 'tasks.my_task', 'schedule': 10.0, 'args': (66,) }, } I just can't schedule the task dynamically. Any idea? -
Add field to AbstractUser admin page
I have an AbstractUser class in models.py file in order to extend the django user default class, class Profile(AbstractUser): address = models.CharField('Address', max_length=255, null=True) In my admin.py, class ProfileAdmin(UserAdmin): pass Everything works fine, but when I try to add my profile field, the address field does not appear in admin: class ProfileAdmin(UserAdmin): fieldsets = ( (None, {'fields': ('username', 'password')}), (_('Personal info'), {'fields': ('first_name', 'last_name', 'email','address')}), (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), I add 'address' field to fieldset variable but when I go to my Profile admin page 'address' field does not appear. Is there anyway to add fields from my Profile class to my Profile admin page? Thanks in advance, -
Django installation error
i have python 3.5.2 installed. i also have pip 9.0.1 installed. the version no shows up when i type in the command python or pip --version. but when i try to install django using the command pip install Django after a certain percentage, it stops downloading and the following error comes up on the command prompt. i have tried to set up the path but still the error shows up Exception: Traceback (most recent call last): File "c:\users\dell\appdata\local\programs\python\python35-32\lib\site-packages\pip\_vendor\requests\packages\urllib3\response.py", line 232, in_error_catcher yield File "c:\users\dell\appdata\local\programs\python\python35-32\lib\site-packages\pip\_vendor\requests\packages\urllib3\response.py", line 314, in read data = self._fp.read(amt) File "c:\users\dell\appdata\local\programs\python\python35-32\lib\site-packages\pip\_vendor\cachecontrol\filewrapper.py", line 60, in read data = self.__fp.read(amt) File "c:\users\dell\appdata\local\programs\python\python35-32\lib\http\client.py", line 448, in read n = self.readinto(b) File "c:\users\dell\appdata\local\programs\python\python35-32\lib\http\client.py", line 488, in readinto n = self.fp.readinto(b) File "c:\users\dell\appdata\local\programs\python\python35-32\lib\socket.py",line 575, in readinto return self._sock.recv_into(b) File "c:\users\dell\appdata\local\programs\python\python35-32\lib\ssl.py", line 929, in recv_into return self.read(nbytes, buffer) File "c:\users\dell\appdata\local\programs\python\python35-32\lib\ssl.py", line 791, in read return self._sslobj.read(len, buffer) File "c:\users\dell\appdata\local\programs\python\python35-32\lib\ssl.py", line 575, in read v = self._sslobj.read(len, buffer) socket.timeout: The read operation timed out During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\users\dell\appdata\local\programs\python\python35-32\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\users\dell\appdata\local\programs\python\python35-32\lib\site-packages\pip\commands\install.py", line 324, in run requirement_set.prepare_files(finder) File "c:\users\dell\appdata\local\programs\python\python35-32\lib\site-packages\pip\req\req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "c:\users\dell\appdata\local\programs\python\python35-32\lib\site-packages\pip\req\req_set.py", line … -
Django: IPv4 only for GenericIPAddressField
Using Django's GenericIPAddressField - https://docs.djangoproject.com/en/1.10/ref/models/fields/#genericipaddressfield for my model like this: group_address = models.GenericIPAddressField() If invalid value is inputted, this returns a message: Enter a valid IPv4 or IPv6 address. Now in my case the field only accepts IPv4 addresses. I would like to remove IPv6 from the message. Is it possible to tune GenericIPAddressField to only handle IPv4 or overwrite the error message? -
How to properly install Open edX e-commerce service?
I am trying to install the e-commerce service on my Ubuntu 14.04 server, where OpenEDX is already running. I am stuck there. I cloned this project (https://github.com/edx/ecommerce) into /opt/bitnami/apps/edx/edx-platform and ran the command "make requirements" in that folder. But then it crashed after 25 minutes. there were like 4-5 WARNINGS npm install npm WARN deprecated minimatch@2.0.10: Please update to ... npm WARN deprecated tough-cookie@2.2.2: ReDoS vulnerability parsing.. ... npm WARN optional dep failed, continuing fsevents@1.0.15 GitHub edx/ecommerce ecommerce - Django application used to manage edX's product catalog and handle orders for those products. I'm totally stuck there and don't even know much about configuring this platform.. as the documentation (http://edx.readthedocs.io/projects/edx-installing-configuring-and-running/en/latest/ecommerce/install_ecommerce.html#switch-from-shoppingcart-to-e-commerce) states i have to run a virtual envirnoment, so i tried the following out of the bitnami documentation: activate the virtual environment (venv) source /opt/bitnami/apps/edx/edx-platform/venv/bin/ Cloning GitHub Repo and executing "make requirements" cd /opt/bitnami/apps/edx sudo git clone https://github.com/edx/ecommerce cd ecommerce sudo make requirements now it shows me (venv)user@OpenEdxDev:/opt/bitnami/apps/edx/ecommerce$ sudo make requirements npm install npm WARN package.json edx-ecommerce@ No license field. npm WARN deprecated minimatch@2.0.10: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS iss ue npm WARN deprecated tough-cookie@2.2.2: ReDoS vulnerability parsing Set-Cookie https://nodesecurity.io/adv isories/130 npm WARN … -
Sending data from view.py to a javascript in django
I know similar questions have been asked before but I am very new to django and js. I have tried many solutions but I am not able to make sense of many and able to run them. So I am writing my code and the solution that I have tried. Can someone please tell me what mistake am I doing. In my views.py I am handling a file which produces some results. These results are in the form of a Dataframe(used pandas). From this dataframe I am calculating few integer values which are stored in variables: tot,p,lp,us. I am also getting 3 sub-dataframes namely: dfp,dflp,dfus. I need to display all these on the webpage so I am sending them to an html: uploaded.html as shown below. dict_1 = {'Path':p, 'LPath':lp, 'USig':us} json1 = json.dumps(dict_1) return render(request, 'uploaded.html', locals(), {'js_json1': json1, 'TotVar': tot}) The above code just sends the variables and not the dataframe as I don't know how to do it. I have handled it in my uploaded.html in the following way: <!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>Upload File-Hereditary Cancers</title> <link rel="stylesheet" href="/static/css/style.css" type="text/css"> <script type="text/javascript"> function results() { var totalvariants = {{TotVar}}; document.getElementById("totvar").innerHTML = "Total number of variants … -
GeoServer and CentOS. Permissions denied when trying to create a layer
I have a Django/Python map application. This application uses gdal library to create geotiffs and tiled layers. Everything works absolutely ok - geotiffs are nicely created, folders with tiles are also created. But there is a problem - I can not create a store and publish a layer, because geoserver says, that it does not have permissions to write to my Django folders. The error message looks like so: '/var/www/django_project/django_project/layers/tiled/test_layer1/0/0.prj', "[Errno 13] Permission denied: And multiple similar error messages. When I check permissions to test_layer1 folder, I see that it is 777 and the owner is apache (not apache tomcat, but apache httpd). I guess the whole problem is in the owner - geoserver for some reason is not able to write to these folders (inspite of 777 permisions). But I'm not sure what owner and what permissions I should set, so that both Django application (or perhaps I should say apache) could write to this folder and GeoServer could read and write to it. By the way, GeoServer is running on top of Apache Tomcat. -
Django : Authenticated differents user models
In my project, I have 2 models named Students and Teachers. These two models are a OneToOne field to User. I have 3 applications : home (index page, faq, about...), teachers (interface for teacher, manage her courses, edit profil ...) and students (interface for students, profil ...) I have one login form (in application home), and I want to use it for log in teachers and students, and redirect to the correct application after authentication. What is the best way for doing that ? I think to create two groups (teachers and students) and assign to the correct group after registration form, and in log in form, just check the group ? PS : Student can create an account, but for teacher, our team creates accounts, so we don't have a registration form for teachers -
Django form not working for ManyToMany (auth.users)
I'm trying to create a Debt model using Django. It has a debtors field which link a debt to many users. It behaves the way I want through Django's administration panel, but I can't get it to work using a django form. I can create debts but the the debtors field is emptying, despite the browser showing an accurate list of users to choose from. What's even more surprising is that I thought that using blank=False in the model definition shouldn't allow that. models.py: from django.db import models from django.utils import timezone class Debt(models.Model): author = models.ForeignKey('auth.User', related_name='author') name = models.CharField(max_length=200) amount = models.FloatField() debtors = models.ManyToManyField('auth.User', blank=False) invoice = models.FileField(blank=True) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.name forms.py: from django import forms from .models import Debt class NewDebtForm(forms.ModelForm): class Meta: model = Debt fields = ('name', 'amount', 'invoice', 'created_date', 'debtors') views.py: from django.shortcuts import render, redirect from .models import Debt from .forms import NewDebtForm def debt_list(request): if request.method == "POST": form = NewDebtForm(request.POST) if form.is_valid(): debt = form.save(commit=False) debt.author = request.user debt.save() debts = Debt.objects.order_by('created_date') form = NewDebtForm() return render(request, 'debt_share/debt_list.html', {'debts': debts, 'form': form}) debt_list.html: {% extends 'debt_share/base.html' %} {% block content %} {% for debt in debts … -
Django get the context object when from loader.get_template
I have the following Django view. def tmp_view(request): c = Context({'tmp_value': "Hello World"}) t = loader.get_template('test.html') response = HttpResponse(t.render(c)) return response Now I want to test the view using the below function. def test_view(self): response = self.client.get('/tmp/', follow=True) self.assertEqual(response.status_code, 200) self.assertEqual(response.context['tmp_value'], "Hello World") But when I run the testcase, I am getting the below error. At line - self.assertEqual(response.context['tmp_value'], 'Hello World') KeyError: 'tmp_value' I am not sure why I am not able to get the context object in my test function. -
how to resolve "No module named jpype" from heroku
when i am running web page, "No module named jpype" error is found from heroku how do i resolve it ? if heroku is not supporting jpype , where should i deploy the project for free service ? -
Reverse for 'account_login' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
I have a view @login_required def dashboard(request): if request.session.get("pending-token"): return redirect("speaker_create_token", request.session["pending-token"]) return render(request, "dashboard.html") and a row in urls.py url(r'^dashboard/', dashboard, name='dashboard'), When I open /dashboard/ with logged user, I see page. My html code is for authentication is <div> <div id="user"> {% if user.is_authenticated %} <snap><a href="{% url 'profile' %}">{{ user.username }}</a> </snap> <snap><a href="{% url 'logout' %}">Logout</a> </snap> {% else %} <snap><a href="{% url 'login' %}">Sign In</a> </snap> <snap><a href="{% url 'create_user' %}">Sign Up</a> </snap> {% endif %} </div> </div> When I try to request /dashboard/ without logging I get the error NoReverseMatch at /dashboard/ Reverse for 'account_login' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] I added LOGIN_URL = '/accounts/login/' to settings.py, but it does not work. I saw similar questions, but I still can not understand how to avoid this error. -
How to test file response in Django?
I have an API that generates and returns a CSV file: def getCSV(): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename='export.csv' writer = csv.writer(response, csv.excel) # ... Write some CSV content ... return response This works fine when I call it from the browser, but I cannot figure out how to write a test that calls the API and check that the CSV contents are what they should be. If I: c = Client() r = c.get('/my/export/api') print(r.content) That just prints three bytes and is most probably conceptually completely wrong. How can I get the contents of the CSV file response in my test? -
ValueError: "<Notification: Notification object>" needs to have a value for field "notification" before this many-to-many relationship can be used
I have this model: class Notification(BaseTimestampableModel): # TYPES CONSTANTS HERE # TYPE_CHOICES DICT HERE sender = models.ForeignKey(User, related_name='sender_notifications') receivers = models.ManyToManyField(User, related_name='receiver_notifications') type = models.PositiveSmallIntegerField(choices=TYPE_CHOICES) data = models.TextField() sent = models.BooleanField(default=False) class Meta: verbose_name = _('Notification') verbose_name_plural = _('Notifications') def send(self): # Logic for sending notification here self.sent = True self.save() For other hand, I've this "static" class: class ChatNotifications: @staticmethod def message_created(message, chat): """ Send a notification when a chat message is created to all users in chat except to the message's sender. """ sender = message.user data = { 'text': message.text, 'phone': str(sender.phone_prefix) + str(sender.phone), 'chatid': chat.uuid.hex, 'time': timezone.now().timestamp(), 'type': 'text', 'msgid': message.uuid.hex } notification = Notification( sender=sender, receivers=chat.get_other_users(sender), type=Notification.TYPE_CHAT_MESSAGE, data=json.dumps(data) ) notification.send() But when I call ChatNotifications.message_created(msg, chat) (message and chat are previusly saved), I get this error: ValueError: "<Notification: Notification object>" needs to have a value for field "notification" before this many-to-many relationship can be used. Researching on Google, I try do this, but this don't solved my problem. With debug, I checked the error is throwing when Model constructor is called. This is the trace: Traceback (most recent call last): File "<input>", line 1, in <module> File "/home/vagrant/petycash/apps/chats/notifications.py", line 45, in message_created data=json.dumps(data) File "/usr/local/lib/python3.5/dist-packages/django/db/models/base.py", … -
django-cms install error ".pyc not found "
Getting below exception while trying to install django cms. Please help E:\Workspace\cms>pip install django-cms Collecting django-cms Using cached django_cms-3.4.1-py2.py3-none-any.whl Requirement already satisfied: django-treebeard>=4.0.1 in c:\users\satish.sharma\appdata\local\programs\python\python35-32\lib\site-packages (from django-cms) Requirement already satisfied: djangocms-admin-style>=1.0 in c:\users\satish.sharma\appdata\local\programs\python\python35-32\lib\site-packages (from django-cms) Requirement already satisfied: django-sekizai>=0.7 in c:\users\satish.sharma\appdata\local\programs\python\python35-32\lib\site-packages (from django-cms) Requirement already satisfied: Django<1.10,>=1.8 in c:\users\satish.sharma\appdata\local\programs\python\python35-32\lib\site-packages (from django-cms) Requirement already satisfied: django-classy-tags>=0.7.2 in c:\users\satish.sharma\appdata\local\programs\python\python35-32\lib\site-packages (from django-cms) Requirement already satisfied: django-formtools>=1.0 in c:\users\satish.sharma\appdata\local\programs\python\python35-32\lib\site-packages (from django-cms) Installing collected packages: django-cms Exception: Traceback (most recent call last): File "c:\users\satish.sharma\appdata\local\programs\python\python35-32\lib\site-packages\pip\basecommand.py", line 215, in main status = self.run(options, args) File "c:\users\satish.sharma\appdata\local\programs\python\python35-32\lib\site-packages\pip\commands\install.py", line 342, in run prefix=options.prefix_path, File "c:\users\satish.sharma\appdata\local\programs\python\python35-32\lib\site-packages\pip\req\req_set.py", line 784, in install **kwargs File "c:\users\satish.sharma\appdata\local\programs\python\python35-32\lib\site-packages\pip\req\req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "c:\users\satish.sharma\appdata\local\programs\python\python35-32\lib\site-packages\pip\req\req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "c:\users\satish.sharma\appdata\local\programs\python\python35-32\lib\site-packages\pip\wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "c:\users\satish.sharma\appdata\local\programs\python\python35-32\lib\site-packages\pip\wheel.py", line 323, in clobber shutil.copyfile(srcfile, destfile) File "c:\users\satish.sharma\appdata\local\programs\python\python35-32\lib\shutil.py", line 115, in copyfile with open(dst, 'wb') as fdst: FileNotFoundError: [Errno 2] No such file or directory: 'c:\\users\\satish.sharma\\appdata\\local\\programs\\python\\python35-32\\Lib\\site-packages\\cms\\test_utils\\project\\extensionapp\\migrations\\__pycache__\\0003_multitablepageextension_multitablepageextensionparent_multitabletitleextension_multitabletitleextens.cpython-35.pyc'