Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Celery Eventlet - Getting "No address found" error
I am currently using celery default prefork for concurrency and I want to use Eventlet. I tried to install Eventlet and used it for concurrency, but I am getting following error: [2017-01-01 04:11:14,233: ERROR/MainProcess] consumer: Cannot connect to amqp://application:**@rabbit:5672//: [Errno -2] No address found. But it is working good with default prefork and I could execute jobs async. I am currently using django 1.10 and Celery 4.0.1 -------------- celery@worker v4.0.1 (latentcall) ---- **** ----- --- * *** * -- Linux-4.4.0-57-generic-x86_64-with-Ubuntu-16.04-xenial 2017-01-01 03:59:11 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: fivefrets:0x7f97ca281a58 - ** ---------- .> transport: amqp://fivefrets:**@rabbit:5672// - ** ---------- .> results: disabled:// - *** --- * --- .> concurrency: 10 (eventlet) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery can anyone help please, I could not get the answers googling. Please us me know, if anyone have any questions. Not sure what I am missing -
redirect all views in django if a condition is met
I have a field on my user profile model to see if a user: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True) ... password_change_required = models.BooleanField(default=True) Is their a way I can redirect all views like this: if request.user.profile.password_change_required: redirect(....) Where can I put this logic so it hits all views? -
Django: Reverse lookup with no parameters?
In my template I've got this ajax call: $.ajax({ url: "{% url 'webapps:ajax-test' webapp.slug %}" ... (note that the value of webapp.slug is 'ajax-test') And my urls.py looks like this: url(r'^ajax/(?P<pk>[a-zA-Z0-9\-]+)/$', views.ajax_test, name='ajax-test') Which works fine, but if I try to do this without a param like this: url(r'^ajax/ajax-test/$', views.ajax_test, name='ajax-test') I get a NoReverseMatch error. In this situation, I don't need a param because each ajax view is going to be a standalone view. Is there a cleaner way to do this without putting in a 'dummy' param? -
Gunicorn + Nginx Internal server error while trying to apply code changes
I set up a VPS (djangp + gunicorn + nginx ) and it was working fine showing default django screen, but after I updated my django code and made all migrations I thought that now I need to restart gunicorn to apply changes. So I did this: sudo systemctl restart gunicorn After this I'v got 'Internal Server Error' Everything is set up like here https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04 -
Href value for the root domain?
What value do you put to href to redirect to the root domain, for example www.mydomain.com? I tried #! and the domain itself www.mydomain.com but did not work ? I'm setting up in the django template file. -
How to deploy a multi-tenant django app to AWS?
I have an Django+Postgres app that has a multi-tenant structure and I don't have prior experience deploying this type of app to AWS. I have followed the general Elastic Beanstalk tutorial to deploy a simple app. (https://realpython.com/blog/python/deploying-a-django-app-to-aws-elastic-beanstalk/) However, I am looking for a solution that allows me to more flexibly create different "sites". Currently, I have learned to create different sites via this tutorial (http://mycodesmells.com/post/django-tutorial-multi-tenant-setup). And I don't have a good idea as of 1. how to deploy this app 2. how I could create different sites after deploying this app. -
How to trigger a url action method in Django
<form action="{% url 'action' %}" method="Post"> {% csrf_token %} <table class="table table-bordered table-hover"> {% for item in itemList %} <tr> <td> <div class="col-xs-6"> <input type="hidden" value="{{item.id}}" name="txtId" /> <button type="button" class="btn btn-danger btn-small" name="category_delete" title="Delete Item" onclick="{% url 'action' %}?id=1"> <span class="glyphicon glyphicon-minus" aria-hidden="true"></span> </button> </td> </tr> {% endfor %} </table> </form> url(r'^action/?id=1', action, name='action'), def action(request): """Renders the about page.""" id = 1 return HttpResponseRedirect('/') -
How to post a url action parameter in Django
<form action="{% url 'action' %}" method="Post"> {% csrf_token %} <table class="table table-bordered table-hover"> {% for item in itemList %} <tr> <td> <div class="col-xs-6"> <input type="hidden" value="{{item.id}}" name="txtId" /> <button type="button" class="btn btn-danger btn-small" name="category_delete" title="Delete Item" onclick="this.form.submit()"> <span class="glyphicon glyphicon-minus" aria-hidden="true"></span> </button> </td> </tr> {% endfor %} </table> </form> def action(request): """Renders the about page.""" if request.method == "POST" and "category_delete" and "txtId" in request.POST: id = request.POST.get("txtId") item = Item.objects.get(id=id) item.delete() return HttpResponseRedirect('/') I will have more than 2 rows so it wont catch the txtId properly -
How to pass parameter to form post method in django
<form action="{% url 'action' %}" method="Post"> {% csrf_token %} <button type="button" class="btn btn-danger btn-small" title="Delete Item" onclick="this.form.submit()"> <span class="glyphicon glyphicon-minus" aria-hidden="true"></span> </button> <button type="button" class="btn btn-primary btn-small" title="Own Item" onclick="this.form.submit()"> <span class="glyphicon glyphicon-thumbs-up" aria-hidden="true"></span> </button> </form> When a button Delete Item or Own Item is clicked how to pass a parameter to form post method. I am able to post via onclick={{this.form.submit()}} -
Django - use variables in a vew following a search result
I'm using django 1.10.3, and I'm trying to take two variables that are chosen in a search template and re-use the variables in the view that follows the search. I have been doing research for several days. I am trying to create a sessions variable (as recommended here : Django - get an object back from template form to view (from a search result)). Data is feeding into my search form, I can make a selection, and when I hit submit, I get this error message. Can somebody spot what I'm doing wrong ? Thank you so much. My error msg : KeyError at myapp/nameresults/ 'request_first_name' # settings.py SESSION_ENGINE = "django.contrib.sessions.backends.cache" # forms.py class NameSearchForm(forms.Form): name_choices = ( ('1', 'Option A'), ('2', 'Option B'), ('3', 'Option C'), ('4', 'Option D') ) request_first_name = forms.ChoiceField(choices=name_choices, required=True) request_second_name = forms.ChoiceField(choices=name_choices, required=True) # views.py def find_names(request): if request.method == 'POST': form = NameSearchForm(request.POST) if form.is_bound: request.session['firstname'] = form.data['request_first_name'] request.session['secondname'] = form.data['request_second_name'] return HttpResponseRedirect('myapp/name_results.html') else: form = NameSearchForm() return render(request, 'myapp/find_names.html', {'form': form}) def report_names(request): template_name = 'myapp/name_results.html' # c = RequestContext(request) # requested_first_name = c['request_first_name'] # requested_second_name = c['request_second_name'] requested_first_name = request.session['request_first_name'] requested_second_name = request.session['request_second_name'] response = HttpResponse() response.write('<p>This is a test.</p>') response.write('<p>----- … -
How can I install Pillow on OpenShift (V2)
I want to install Pillow in openShift. I tried adding the dependency in setup.py but, it didn't help me. I also tried to login the remote server (rhc ssh app_name) and run the command pip install pillow. But, that was also a failure. Then, how can I install Pillow on OpenShift v2 ? -
How to save a model record in Django
class Item(models.Model): id = models.AutoField(primary_key=True) userId = models.ForeignKey(User, on_delete=models.CASCADE) categoryId = models.ForeignKey(Category, on_delete=models.CASCADE) itemName = models.CharField(max_length=100) startDate = models.DateTimeField('startDate') endDate = models.DateTimeField('endDate') priority = models.IntegerField(default=0) progress = models.IntegerField(default=0) own = models.IntegerField(default=0) advanced = models.IntegerField(default=0) item = Item.objects.create(request.user.id,categoryId,txtItemName,txtStartDate,txtEndDate,priorityName,progressStatus,ownStatus,advanced) item.save() It is asking for a primary key field. How to get the primary key field value during create? -
Getting metadata from links using BeautifulSoup
I'm trying to scrape links to get the title, description, and image to give a small overview of the article or webpage. Currently I have og:title by getting the meta property through BeautifulSoup. This works fine for news articles. if tag.get("property", None) == "og:title": scraper.title = tag.get("content", None) However, links for an Amazon Echo for example, don't pull any images or product title. How can I go about doing this using BeautifulSoup and Python and pulling the first image found and the title from any website -- maybe not just one supported by opengraph? -
Django Autocomplete Light - Displaying multiple fields(columns) in the dropdown box
My JavaScript skills are pretty weak at this point, so I've been attempting to build my app primarily in Python/Django. That's why I chose AutoComplete light to implement autocomplete forms on my site. I'm searching through the docs and it doesn't appear as though DAL includes support for a dropdown with multiple fields. For example, I have a model: class Builder(models.Model): added_by = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) company_name = models.CharField(max_length=80, help_text="Full Company Name", unique=True) short_name = models.CharField(help_text="Short Company Name", max_length=30, unique=True) slug = models.SlugField(unique=True) website = models.CharField(max_length=80, help_text="Format: www.[website].com", unique=True, blank=True, null=True) ... Rather than just showing the company name in the dropdown, I'd like to show other values from my builder object as well. DAL uses a Jquery Library Select2 which appears to support this. Check this link and search for 'Infinite Scroll with Remote Data' for an example: http://select2.github.io/select2/ However, like I said my JS skills are weak and I'm having trouble making any progress. I attempted adding a Jquery function for formatResult inside the attrs field when calling the select2 widget from my Form like this: widget=autocomplete.ModelSelect2( url='builder-auto', attrs={ 'data-placeholder': 'Select a Builder', 'data-minimum-input-length': 3, 'formatResult': '''format(item) { var originalOption = item.element; return item.company_name, item.added_by }''', }, ) ) … -
Many to Many or One to Many Django
I have the following two models in Django. One is basically an extension of the base Django user class and the other is a company model. I want to say that a user can belong to one or more companies and that a company can also have one or more contacts = "Users". Would this be a correct setup? How should I represent the tie between user and company? User Profile model: class Profile(models.Model): user = models.OneToOneField(User) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) Company model: class Company(models.Model): name = models.CharField(max_length=120) account_name = models.CharField(max_length=10, default="") sales_rep = models.ForeignKey(User, related_name="%(app_label)s_%(class)s_sales", default="") csr = models.ForeignKey(User, related_name="%(app_label)s_%(class)s_csr", default="") class CompanyContact(models.Model): name = models.CharField(max_length=40, default="") email = models.CharField(max_length=50, default="") user = models.ForeignKey(User) company = models.ForeignKey(Company) -
AttributeError: 'module' object has no attribute 'MathField'
After I makemigrations, I am getting this error when I try to migrate. mathfield is installed in INSTALLED_APPS. from django.db import models from django.utils import timezone import mathfield class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() latex = mathfield.MathField(default=timezone.now) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title django-mathfield is installed in my virtualenv django-mathfield usage The error happens with the default or if I allow the one-off default during makemigrations. -
What is the best way to have user specific numbering in Django?
I'm making a web site for a friend for a small business, and for each user, I want them to be able to access their orders by number which starts from 1 for each user, but in the backend this should be a global numbering. So for each user, their first order will be at /orders/1/ and so on. Is there a consensus on how this should be achieved in general? Way I see it, I can do this 2 ways: Store the number in another column in the orders table. I'd prefer not to do this because I'm not entirely sure how to handle deletions without going through and updating all the records of the user. If someone knows the edge cases I need to handle, I might go with this. OR For every queryset I make when getting the orders page for each user I handle the numbering, benefit of this is that it will always give the correct numbering, especially if I just do it in the template. Right now this seems easier, but I have a feeling this would give rise to problems in the future. Main problem I see is I'm not sure how to … -
Best way to determine a new site user - Django
I want a way of checking if someone has filled out their profile information (new user) with django. If they havn't I want to show a modal that won't go away until all information has been filled out. No matter what page they go to, it should show this modal until filled out. Should I do the check with javascript(ajax) to a route that would make the check and return a json request with the answer? If the json object says they are new, I would append the modal to the screen dynamically. -
Set to none suspicious operation RequestDataTooBig
I did found this piece of documentation on django doc : The maximum size in bytes that a request body may be before a SuspiciousOperation (RequestDataTooBig) is raised. The check is done when accessing request.body or request.POST and is calculated against the total request size excluding any file upload data. You can set this to None to disable the check. Applications that are expected to receive unusually large form posts should tune this setting. But I don't know how to disable that check , the error that I get is : Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE. Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE. Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE. Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE. Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE. Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE. Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE. Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE. -
Django static file on false debug runing on IIS
I started a django site on my VPS and it works perfectly when the debug is True but when I change it to False it don't show the static file. I searched a lot and I know that "With debug turned off Django won't handle static files for me any more" and my web server should handle it but how should I do that -
which user opens a file in python
I am working with django and celery, in my celery task, i instantiate a class and that class is responsible for generating and mailing a csv file. My problem is i am getting IOError: [Errno 13] Permission denied when i try to do fp = open(filename, 'w'). But How do i get to know which user of my server is trying to create that file and how can i provide that user with appropriate permissions.I am working on AWS server. my code for writing files is this: with open(filename, 'w') as f_pointer: os.chmod(filename, 777) myfile = csv.writer(f_pointer) myfile.writerow(columns) myfile.writerows(rows) Thanks -
Django & ZeroMQ - how to keep the ZMQ context? + issues with nginx/uwsgi multiple processes?
I have a Django application, and I would like to make ZeroMQ calls during views. I would like to initialize the context once and have it globally available. My question is twofold: How can I initialize a context at the start-up of Django and cause it to be globally shared? Does the multi-threading of uwsgi/nginx cause n completely separate instances, or does it do a fork, causing me to require n separate contexts? -
Creating multiple objects takes a very long time
In our Django project, there is a view which creates multiple objects (from 5 to even 100). The problem is that creating phase takes a very long time. Don't know why is that so but I suppose that it could be because on n objects, there are n database lookups and commits. I want to speed up this process. There are two things I think may be worth to consider: To create these objects in one query so only one commit is executed. Create a ThreadPool and create these objects parallel. This is a part of the view which causes problems (We use Postgres on localhost so connection is not a problem) @require_POST @login_required def heu_import(request): ... ... product = Product.objects.create(user=request.user,name=name,manufacturer=manufacturer,category=category) product.groups.add(*groups) occurences = [] counter = len(urls_xpaths) print 'Occurences creating' start = datetime.now() eur_currency = Currency.objects.get(shortcut='eur') for url_xpath in urls_xpaths: counter-=1 print counter url = url_xpath[1] xpath = url_xpath[0] occ = Occurence.objects.create(product=product,url=url,xpath=xpath,active=True if xpath else False,currency=eur_currency) occurences.append(occ) print 'End' print datetime.now()-start ... return render(request,'main_app/dashboard/new-product.html',context) Output: Occurences creating 24 . . . 0 End 0:01:07.727000 EDIT: I tried to put the for loop into the with transaction.atomic(): block but it seems to help only a bit (47 seconds instead of … -
django maximum recursion depth exceeded when making calculation
I'm trying to do a calculation here. If the install choice is equal to 'FIRST' then the amount entered should be subtracted from the fee and return the balance, else the amount should be subtracted from the previous balance (FIRST will always be captured before the other choices). class Payment(models.Model): fee = models.ForeignKey( Fee ) installment = models.CharField( _('Installment'), max_length=30, choices=INSTALLMENT_CHOICES, default=u' ', null=False, blank=False ) amount = models.FloatField( _('Amount'), null=False, blank=False, default=0.00 ) @property def balance(self): if self.installment == "FIRST": return self.fee.totalannualfee - self.amount else: return self.balance - self.amount But I'm however getting this error if the installment choice is not FIRST: RuntimeError at /admin/sisdatasources/payment/ maximum recursion depth exceeded -
Inheriting Meta Class in Django Models
I have a question as newbie and I am looking for the concept related to inheritance of Meta class in Django classes. Following are the models and I would appreciate if someone can help me. class Base(models.Model): code = AutoSlugField(_("Slug"), max_length=128, unique=True, populate_from='name') name = models.CharField(_("Name"), max_length=128, unique=True) description = models.TextField(_("Description"), blank=True) countries = models.ManyToManyField('Country', blank=True, verbose_name=_("Countries")) is_discounted = False class Meta: app_label = 'shipping' ordering = ['name'] verbose_name = _("Shipping Method") verbose_name_plural = _("Shipping Methods") class OrderAndItemCharges(Base): price_per_order = models.DecimalField( _("Price per order"), decimal_places=2, max_digits=12, default=D('0.00')) price_per_item = models.DecimalField( _("Price per item"), decimal_places=2, max_digits=12, default=D('0.00')) free_shipping_threshold = models.DecimalField( _("Free Shipping"), decimal_places=2, max_digits=12, blank=True, null=True) class Meta(Base.Meta): app_label = 'shipping' verbose_name = _("Order and Item Charge") verbose_name_plural = _("Order and Item Charges") Traceback: class OrderAndItemCharges(Base): File "C:\Users\AliKhan\supermarekt\market\shipping\models.py", line 46, in Or derAndItemCharges class Meta(Base.Meta): AttributeError: type object 'Base' has no attribute 'Meta'