Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
fix for NoReverseMatch error after integrating django package (django-audiotracks)
I'm relatively new to django.. I'm trying to integrate the audiotracks package with my project. I'm trying to integrate the audiotracks package but I'm getting NoReverseMatch error. The documentation states.. Add audiotracks to your app ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Edit settings.py and add audiotracks to your list of INSTALLED_APPS. Then synchronize your database with:: $ python manage.py syncdb Edit your ROOT_URLCONF_ and add a piece of code similar to:: urlpatterns += patterns('', # Here we mount the app under /music. Feel free to use something else url("^music", include("audiotracks.urls")), # Some URLs require a Django username url("^(?P<username>[\w\._-]+)/music", include("audiotracks.urls")), ) Visit the URL /music/upload to upload your first track. the error occurs when i try to access music/upload.. here's the full traceback. Environment: Request Method: GET Request URL: http://127.0.0.1:8000/music/upload Django Version: 1.11.3 Python Version: 3.6.0 Installed Applications: ['account', 'music', 'audiotracks', 'django.contrib.sites', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Users\Alexander\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django_audiotracks-0.2.5-py3.6.egg\audiotracks\templates\audiotracks\base.html, error at line 25 Reverse for 'user_index' with arguments '('addemo1',)' not found. 2 pattern(s) tried: ['music/tracks/(?P\d)/?$', 'music/tracks$'] 15 : .errorlist { color: red; list-style: none; display: inline; } 16 : </style> 17 : {% block extra_head %}{% endblock %} 18 : </head> 19 β¦ -
Python Django and Celery periodictasks
I have a personal website that I want to track the price of bitcoin but I want the code to run every five minutes in the back end of the website. I am very new to Celery so I do not know much of what I am doing. That being said, I have updated my installed_apps, I have imported djcelery and I have done all of the updates to the settings page. I set up a periodic task through the admin website because it looked pretty straight forward but I have been unable to run the code automatically despite my function being an option as a task. I am pretty stuck here and any help would be awesome. Thanks. def bitcoin(): url = "https://api.coindesk.com/v1/bpi/currentprice.json" request = Request(url) response = urlopen(request) the_page = response.read() data = json.loads(the_page) btc_price = data['bpi']['USD']['rate'] print('According to CoinDesk, the price of bitcoin is: ' + str(btc_price)) -
Django Trunc with Time Zone Conversion
I'm using the Trunc function to aggregate some data: query_set.annotate(day=Trunc('time_received', 'day')).values('day').order_by('day').annotate(views=Sum('files_received')) The problem is items are saved in UTC, so django is always truncating the UTC timestamp. A request with date range 07/01 to 07/02 from New York (all datetime objects in my app are tz aware) yields: 2017-07-01 1209 2017-07-02 1002 2017-07-03 91 where the last entry is probably for midnight to 04:00AM UTC but still within 07/02 EDT. I've tried passing in tzinfo to the Trunc call but no luck. What's the correct way for Django to truncate and output for different timezones? Or do I have to do the time localization differently? Thanks! -
Website using python[2.7] [on hold]
Which web framework should I use while creating a website which fetches JSON data from various other website every 60 seconds extracts the required info from raw JSON data and displays the same. Any suggestions will be helpful. -
Update field in model base on matching quantities in another with foreign key
I am trying to update a boolean field in my current model when two quantities in a second model, with a FK, are equal. this is a one to many relation, so I need to check that the two quantities are equal for every instance of the Foreign key. I think what I am trying to do will work, but I am unsure of how to write it. I have only been working in Python/Django for a couple of weeks now class ModelA(): model_number = models.CharField(max_length=100) is_true = models.BooleanField(default=False) def update_is_true(self, *args, **kwargs): disting_model = ModelB.objects.filter( model_number=self.model_number ) if ordered != received """ get a count for every instance of (ordered != received) for each model_number. If count = 0, set (is_true = True) """ class ModelB(): model_number = models.ForeignKey(ModelA), on_delete=models.PROTECT) ordered = models.IntegerField(default=0) received = models.IntegerField(default=0) Here is my db structure. ModelA id model_number is_true 1 1 False ModelB id modelA_id ordered received 1 1 15 15 2 1 25 25 -
Django shell vs runserver performance
I have function that imports data from a csv file to django's database. I have put a timer to measure the execution time on the function. It prints steps of the script and the time needed to complete the task. I come out that the same script take 5 times more time when called through a view than with django's shell. When I run it through the shell it take in average 3 seconds to process 50 items. $ python manage.py shell >>> from recommend.import_data import import_csv as i >>> i(50) 1. File downloaded 2. Data importation |ββββββββββββββββββββββββββββββββ| 50/50 100% 3. Task completed in 0:00:03 >>> While when the script is called within a view, the same script takes between 14 and 20 seconds to proceed. $ python manage.py runserver 1. File downloaded 2. Data importation |ββββββββββββββββββββββββββββββββ| 50/50 100% 3. Task completed in 0:00:18 [07/Jul/2017 16:18:59] "GET /import_data/50 HTTP/1.1" 200 19 Does anyone have an explanation for that and/or a way to improve the performance within runserver. It is critical as I usually import thousands items and it ends up with differences in dozens of minutes between the two. Thank you for your help! -
**'Cannot send an e-mail without a Postmark API Key'**
I got this Error when user want to register: PMMailMissingValueException at /accounts/register/ 'Cannot send an e-mail without a Postmark API Key' Request Method: POST Request URL: http://127.0.0.1:8009/accounts/register/ Django Version: 1.11.3 Exception Type: PMMailMissingValueException and I dont know to which value for POSTMARK_API_TOKEN='' in settings.py file -
Using global variables in Celery: What's the best approach?
Im writing an app using Django 1.10 and Celery. Im trying to create a loop in celery that can be started and stopped through Django. My idea looks something like this (very simple): _run = False def do_work(): global _run while _run: # Do something @app.task def start(): global _run _run = True do_work() @app.task def stop(): global _run _run = False The problem is that celery is typically run in >1 working thread, and _run is not accessable between threads. Question: What's the best approach to achieve the functionality? Im thinking about setting a database variable, but I'm afraid its not the best approach. -
Django ManyToMany field get all values from an object without a 'for'
Is it possible to get the values of a ManyToMany from an object without using a 'for'? models.py class Citizenship(models.Model): name = models.CharField(max_length=100) class Meta: verbose_name_plural = "Citizenship" def __str__(self): return self.name class Anexa(models.Model): name = models.CharField(max_length=150, help_text="3") citizenship = models.ManyToManyField(Citizenship, help_text="4") I have an Anexa object with the name Alex and i have 4 citizenships for this object. I'm searching for something equivalent to this: for citizenships in x.citizenship.all(): print(citizenships.name) -
Delete an object in Django
I am trying to delete an object. This is the HTML, todo should be deleted when you Click on button (I am trying to call delete_todo) :- <ul> {% for todo in todolist.todos.all %} {% if not todo.is_finished %} <li><input type="checkbox" id="checkbox" data-todo-id="{{ todo.id }}"> {{ todo.description }}</li> <form action="{% url 'lists:delete_todo' %}" method=post> <input id="submit" type="button" value="Click" /> </form> {% endif %} {% endfor %} </ul> This is the views.py, def todolist(request, todolist_id): todolist = get_object_or_404(TodoList, pk=todolist_id) if request.method == 'POST': redirect('lists:add_todo', todolist_id=todolist_id) return render( request, 'lists/todolist.html', {'todolist': todolist, 'form': TodoForm()} ) In the views.py , I want something like, def delete_todo(request, todolist): todolist.delete() Which I can call from HTML. Below is my Model.py , class TodoList(models.Model): title = models.CharField(max_length=128, default='untitled') created_at = models.DateTimeField(auto_now=True) creator = models.ForeignKey(User, null=True, related_name='todolists') class Meta: ordering = ('created_at',) def __str__(self): return self.title def count(self): return self.todos.count() def count_finished(self): return self.todos.filter(is_finished=True).count() def count_open(self): return self.todos.filter(is_finished=False).count() class Todo(models.Model): description = models.CharField(max_length=128) created_at = models.DateTimeField(auto_now=True) finished_at = models.DateTimeField(null=True) is_finished = models.BooleanField(default=False) creator = models.ForeignKey(User, null=True, related_name='todos') todolist = models.ForeignKey(TodoList, related_name='todos') class Meta: ordering = ('created_at',) def __str__(self): return self.description def close(self): self.is_finished = True self.finished_at = timezone.now() self.save() -
differentiate between instances of the same form with different prefixes in Django
I am passing two form with different prefix in the template and each form has own submit button but how can I get data from these two form in submit button is pressed in any one of them and how to differentiate which form button was pressed return render(request,'part_details.html', {'part_stock_form': forms.part_stock_form(prefix='add'),'part_stock_edit':forms.part_stock_form(prefix='edit')}) -
Deploying project in Docker with Angular 4, Django and postgresql
I am trying to deploy on Heroku my project in Docker with Angular 4 frontend with Django backend and postgresql database. At this moment my files looks as shown below. I am note sure if this is done properly? I pushed it using heroku container:push web --app myproject but it doesn't work. I assume that if I use Docker I don't have to create Procfile etc.? May error be caused by lack of migration of database? My logs: 2017-07-07T10:27:30.448951+00:00 heroku[web.1]: State changed from crashed to starting 2017-07-07T10:27:30.436282+00:00 heroku[web.1]: Process exited with status 0 2017-07-07T10:27:50.846928+00:00 heroku[web.1]: Starting process with command `python3` 2017-07-07T10:27:53.350381+00:00 heroku[web.1]: Process exited with status 0 2017-07-07T10:27:53.365013+00:00 heroku[web.1]: State changed from starting to crashed 2017-07-07T10:27:53.876208+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host= myproject.herokuapp.com request_id=e1f8edfc-7dc4-4bd3-91be-0a853e948452 fwd="109.173.154.199" dyno= connect= service= status=503 bytes= protocol=https 2017-07-07T10:28:43.444860+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host= myproject.herokuapp.com request_id=361846d1-41cd-403a-989f-4c29a0d1179e fwd="109.173.154.199" dyno= connect= service= status=503 bytes= protocol=https 2017-07-07T10:28:43.984059+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host= myproject.herokuapp.com request_id=658795c8-0ba7-4988-9d39-34601b1334c7 fwd="109.173.154.199" dyno= connect= service= status=503 bytes= protocol=https 2017-07-07T10:28:44.673789+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host= myproject.herokuapp.com request_id=63fbabdc-7ba7-4997-81be-c601a0d83368 fwd="109.173.154.199" dyno= connect= service= status=503 bytes= protocol=https 2017-07-07T10:29:53.091547+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host= myproject.herokuapp.com request_id=a3943544-9dc4-44f0-b788-a462cdfba7d0 fwd="109.173.154.199" dyno= β¦ -
Adding fields to django-registration
I'm trying to setup django-registration form with an extra field or two. I've read the documentation and scoured StackOverflow. The closest I can find is here but it is somewhat out of date. I've created a new view (I've just cut and pasted register from django-registration because I just want it running initially): class MyRegistrationView (RegistrationView): form_class = UserRegForm def register(self, form): new_user = RegistrationProfile.objects.create_inactive_user( form, site=get_current_site(self.request) ) signals.user_registered.send(sender=self.__class__, user=new_user, request=self.request) return new_user It uses this form: class UserRegForm(RegistrationForm): CHOICES = Institution.objects.all().order_by('name') institution=forms.ChoiceField(choices=( (x.id, x.name) for x in CHOICES ), required = True) These are the additional models: class Institution(models.Model): name = models.CharField(max_length=200) def __unicode__(self): return u'%s' % (self.name) class UserProfile(models.Model): user=models.OneToOneField(User, on_delete=models.CASCADE) institution=models.ForeignKey( Institution, null=True, blank=True) def __unicode__(self): return u'%s' % (self.user) My URL url(r'^register', views.MyRegistrationView.as_view(form_class=UserRegForm), name='registration_register'), And I've added this to save the data: from models import UserProfile from forms import UserRegForm def user_created(sender, user, request, **kwargs): form = UserRegForm(request.POST) data = UserProfile(user=user) data.institution = form.data["institution"] data.save() from registration.signals import user_registered user_registered.connect(user_created) The correct form gets shown but the data isn't saved and validation emails aren't sent. What am I getting wrong? -
local variable 'data' referenced before assignment
UnboundLocalError at /post/ local variable 'data' referenced before assignment Request Method: POST Request URL: http://127.0.0.1:8000/post/ Django Version: 1.11.3 Exception Type: UnboundLocalError Exception Value: local variable 'data' referenced before assignment Exception Location: D:\website\formapp\views.py in index, line 56 def index(request): if request.method == 'POST': form = Postform(request.POST,request.FILES) if form.is_valid(): f=form.save(commit=False) f.user=request.user f.save() return HttpResponseRedirect('/post/') else: form = Postform() data=Post.objects.order_by('-date_created') return render(request,'home2.html',{'form':form,'data':data}) class Postform(forms.ModelForm): pic=models.FileField() vid=models.FileField() class Meta: model=Post #fields=['title','content','pic'] fields='__all__' <form action=' ' method = 'POST' enctype="multipart/form-data"> {% csrf_token %} <h3>Title:</h3> {{form.title}}<br><br> <h3>Content:</h3> {{form.content}}<br><br> <h3>Pic: </h3>{{form.pic}}<br> <button type= 'submit' class='btn btn-primary btn-md'>Save</button> <br><br> </form> -
django-celery as a systemd service in virtualenv
Is this possible to daemonize django-celery as a systemd service for a project in virtualenv? Here is my config: /etc/systemd/system/celery.service [Unit] Description=Celery Service After=network.target [Service] Type=forking User=vagrant Group=vagrant Restart=no WorkingDirectory=/vagrant/myproj/ EnvironmentFile=/etc/systemd/celery.conf ExecStart=/bin/sh -c '${PYTHON_VENV} ${CELERY_BIN} multi start ${CELERY_NODES} \ --pidfile=${CELERY_PID_FILE} --logfile=${CELERY_LOG_FILE} --loglevel=${CELERY_LOG_LEVEL} \ ${CELERY_OPTS}' ExecStop=/bin/sh -c '${PYTHON_VENV} ${CELERY_BIN} multi stopwait ${CELERY_NODES} \ --pidfile=${CELERY_PID_FILE}' [Install] WantedBy=multi-user.target /etc/systemd/celery.conf: PYTHON_VENV="/var/www/vhost/myproj_env/bin/python" CELERY_BIN="/vagrant/myproj/manage.py celery" CELERY_NODES="w1 w2 w3" CELERY_PID_FILE="/var/run/celery/%N.pid" CELERY_LOG_FILE="/var/log/celery/%N.log" CELERY_LOG_LEVEL="INFO" CELERY_OPTS="-Q availability,celery --time-limit=300" all the directories mentioned here do exist, and the permissions set correctly django-celery in settings.py: INSTALLED_APPS = ( ... 'djcelery', 'celery_haystack', ... ) import djcelery djcelery.setup_loader() CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler" BROKER_URL = "redis://localhost:6379/0" CELERY_RESULT_BACKEND = BROKER_URL CELERY_REDIS_MAX_CONNECTIONS = 30 The following command starts celery normally, and I can see tasks being executed: python manage.py celery worker --loglevel=INFO -Q availability,celery Which is basically the same as specified in the service conf, except it starts only one worker and doesn't use log, but posts to stdout However, when i try to systemctl start celery.service, it just fails silently: systemctl status celery.service reports inactive (dead) I'd be thankful for any hint on this problem. I might be missing something obvious, though i have a feeling that the process should not be so complicated, as it it β¦ -
Django Render Partial Page
I have a page with two graphs. Each graph will be generated based on the user's input. I want the two graphs to be isolated from each other. So when I generate one graph it will not effect the second graph. I want the two graphs to be in the same page however, I am not sure how to make them not interfere with each other. For example: If I generate the first graph, the second graph disappears since they are rendered in the same view and the Loan ID is passed as None. I looked up template tags but it doesn't have what I need since its mostly for static pages. Any ideas? -
Websockets in Django
I want to implement basic websockets connection in django where a client sends message to the django server and the servers sends him the reply. I don't want to use Redis or other methods of brodcasting (only client server connection). Where can I find a good tutorial for this? -
Form not showing, Only the button shows Django
I am trying to show a newsletter form, and it is not shown in the page This is my models.py from django.db import models # Create your models here. class newsletter_user(models.Model): email = models.EmailField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email This is my forms.py from django import forms from .models import newsletter_user class newsletterForm(forms.ModelForm): class Meta: model = newsletter_user fields = ['email'] def clean_email(self): email = self.cleaned_data.get('email') return email This is my admin.py from django.contrib import admin from .models import newsletter_user # Register your models here. class newsletterAdmin(admin.ModelAdmin): list_display = ('email','date_added',) admin.site.register(newsletter_user,newsletterAdmin) This is the views.py from django.shortcuts import render from .models import newsletter_user from .forms import newsletterForm # Create your views here. def newsletter_subscribe(request): form = newsletterForm(request.POST or none) if form.is_valid(): instance = form.save(commit=false) if newsletter_user.objects.filter(email=instance.email).exists(): print("already exists") else: instance.save() context = {'form':form,} template = "/blog/templates/footer.html" return render(request, template, context) This is the html <form method="post" action=''> <div class = "input-group"> {{form|safe}} {% csrf_token %} <span class = "input-group-btn"> <button class="btn btn-default" type="submit">Subscribe</button> </span> </div> </form> My Project directory The button is shown But the form is not shown.. -
Delay response until field has changed
Is there a way to delay a response from a api view until a field has changed? Sort of like a stream without using any libraries. -
Allowing both email and username login in django project
I'm creating a django project for a school, and there are three main kinds of users - parents, teachers, and students. For parents and teachers, I would like them to login using email (they are currently using email logins for a legacy system). However, for students, I would like them to login using the conventional username approach (since young kids don't have emails). Is this possible to do in Django or is there only one User Authentication model allowed? -
difficulty in updating csv file
I tried to update the csv file with a description column.I tried to add update the model by adding description = models.CharField(max_length=200, default='SOME STRING') wine = models.ForeignKey(Wine) pub_date = models.DateTimeField('date published') user_name = models.CharField(max_length=100) comment = models.CharField(max_length=200) rating = models.IntegerField(choices=RATING_CHOICES) description = models.CharField(max_length=200, default='SOME STRING') When I make migration I get an error! c:\Users\Amira Joshi\Desktop\winerama>python manage.py makemigrations Migrations for 'reviews': reviews\migrations\0002_review_description.py - Add field description to review How can I solve it?Please help! -
How could I get django query from one model and add the information from the model ForeignKey to it?
I want to get all Blogs in one query, and at the same time, I want to know each Blog's Entry(or Entries), if the Blog has. class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() class Entry(models.Model): blog = models.ForeignKey(Blog) headline = models.CharField(max_length=255) Like, get all Blogs first, and set each Blog with its entries: for blog in Blog.objects.all(): entry = Entry.objects.filter(blog=blog) setattr(blog, 'ENTRY', entry) Can I do this in just one query? Because I don't want to do Entry filter query in the for loop. -
Merging django-rest-framework results
I'm making my first API and it's almost what I want. Currently, my output looks like this: [ { "username": "admin", "top_access": [], "middle_access": [ { "name": "foo" }, { "name": "bar" } ], "lower_access": [], "group_affiliation": [ { "top_access": [], "middle_access": [ { "name": "eggs" } ], "lower_access": [] }, { "top_access": [], "middle_access": [ { "name": "foo" } ], "lower_access": [] } ] }, { "username": "person", "top_access": [], "middle_access": [ { "name": "spam" } ], "lower_access": [], "group_affiliation": [] } ] But I would like it to look more like this, where the group_affiliation results are merged into the other results: [ { "username": "admin", "top_access": [], "middle_access": [ { "name": "foo" }, { "name": "bar" }, { "name": "eggs" } ], "lower_access": [], }, { "username": "person", "top_access": [], "middle_access": [ { "name": "spam" } ], "lower_access": [], "group_affiliation": [] } ] Here is my models.py: class TopAccess(models.Model): name = models.CharField(max_length=100) site_user_access = models.ManyToManyField(User, blank=True) site_group_access = models.ManyToManyField(Group, blank=True) class Meta: verbose_name_plural = "Top Access" def __str__(self): return self.name class MiddleAccess(models.Model): name = models.CharField(max_length=100) site_user_access = models.ManyToManyField(User, blank=True) site_group_access = models.ManyToManyField(Group, blank=True) class Meta: verbose_name_plural = "Middle Access" def __str__(self): return self.name class LowerAccess(models.Model): name = β¦ -
OTRS and PyOTRS
Working with OTRS system with PyOTRS trying to create ticket. I get this message in response after I successfully create a ticket in the OTRS. I searched on the Internet for some people had a similar problem but found no solution anywhere. Traceback (most recent call last): File "/home/essaulov/try/try/lib/python3.5/site-packages/urllib3/connectionpool.py", line 600, in urlopen chunked=chunked) File "/home/essaulov/try/try/lib/python3.5/site-packages/urllib3/connectionpool.py", line 386, in _make_request six.raise_from(e, None) File "<string>", line 2, in raise_from File "/home/essaulov/try/try/lib/python3.5/site-packages/urllib3/connectionpool.py", line 382, in _make_request httplib_response = conn.getresponse() File "/usr/lib/python3.5/http/client.py", line 1197, in getresponse response.begin() File "/usr/lib/python3.5/http/client.py", line 297, in begin version, status, reason = self._read_status() File "/usr/lib/python3.5/http/client.py", line 266, in _read_status raise RemoteDisconnected("Remote end closed connection without" http.client.RemoteDisconnected: Remote end closed connection without response During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/essaulov/try/try/lib/python3.5/site-packages/requests/adapters.py", line 440, in send timeout=timeout File "/home/essaulov/try/try/lib/python3.5/site-packages/urllib3/connectionpool.py", line 649, in urlopen _stacktrace=sys.exc_info()[2]) File "/home/essaulov/try/try/lib/python3.5/site-packages/urllib3/util/retry.py", line 357, in increment raise six.reraise(type(error), error, _stacktrace) File "/home/essaulov/try/try/lib/python3.5/site-packages/urllib3/packages/six.py", line 685, in reraise raise value.with_traceback(tb) File "/home/essaulov/try/try/lib/python3.5/site-packages/urllib3/connectionpool.py", line 600, in urlopen chunked=chunked) File "/home/essaulov/try/try/lib/python3.5/site-packages/urllib3/connectionpool.py", line 386, in _make_request six.raise_from(e, None) File "<string>", line 2, in raise_from File "/home/essaulov/try/try/lib/python3.5/site-packages/urllib3/connectionpool.py", line 382, in _make_request httplib_response = conn.getresponse() File "/usr/lib/python3.5/http/client.py", line 1197, in getresponse response.begin() File "/usr/lib/python3.5/http/client.py", line β¦ -
How to get the list of hosts listening on a particular Que in Celery?
In my project I have two ques. I would like to know list of all the workers listening to a que.