Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
uwsgi ImportError: No module named myproject.settings
I'm receiving the following errors while trying to launch my site using django, uwsgi and nginx ImportError: No module named MIVT.settings My folder/file structure are as follows -webapps --myproject ---wsgi.py ---settings.py Inside my uwsgi.ini file for the project I have the following. # mivt_uwsgi.ini [uwsgi] plugin=python pidfile = /home/mysuer/webapp/webapp-pid.pid chdir = /home/mysuer/webapp/myproject wsgi-file = /home/mysuer/webapp/myproject/wsgi.py home = /home/mysuer/webapp/myproject/myprojectvirtual master = true processes = 10 socket = /home/mysuer/webapp/myproject/proj.sock chmod-socket = 666 vacuum = false I've based this project off of another one that works just fine. Any clues to why I'm getting the no myproject.settings found would really help out. It finds the wsgi.py file just fine. -
Django wagtail getting page children with levels
I have a page model as ' home > blog_index page > blog_page '. And a blog page can have sub pages. Now I am trying to create a blog archive page. Say I have a blog page named '1' and it has children 'a', 'b', 'c'. And blog page named '2' and it has children 'a', 'b', 'c'. When we loop in BlogPages we have eight pages as '1', 'a', 'b', 'c', '2', 'a', 'b', 'c'. Is there any chance that we get children with specific levels? For example if I want only '1' and '2' what can I do? Thank you -
Django Formset Missing Management Form Data
I'm attempting to write unit tests for a formset, but I'm getting the following error when trying to instantiate it. error: Traceback (most recent call last): File "/home/jwelborn/Documents/projects/Bingo/bingo/cards/tests/test_forms.py", line 218, in test_formset_accepts_valid_data self.assertTrue(formset.is_valid()) File "/home/jwelborn/Documents/projects/Bingo/bingoenv/lib/python3.6/site-packages/django/forms/formsets.py", line 321, in is_valid self.errors File "/home/jwelborn/Documents/projects/Bingo/bingoenv/lib/python3.6/site-packages/django/forms/formsets.py", line 295, in errors self.full_clean() File "/home/jwelborn/Documents/projects/Bingo/bingoenv/lib/python3.6/site-packages/django/forms/formsets.py", line 343, in full_clean for i in range(0, self.total_form_count()): File "/home/jwelborn/Documents/projects/Bingo/bingoenv/lib/python3.6/site-packages/django/forms/formsets.py", line 116, in total_form_count return min(self.management_form.cleaned_data[TOTAL_FORM_COUNT], self.absolute_max) File "/home/jwelborn/Documents/projects/Bingo/bingoenv/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/jwelborn/Documents/projects/Bingo/bingoenv/lib/python3.6/site-packages/django/forms/formsets.py", line 98, in management_form code='missing_management_form', django.core.exceptions.ValidationError: ['ManagementForm data is missing or has been tampered with'] This error says I'm missing ManagmentForm data, but I include it in the dictionary I'm passing to my form. I've checked different spellings and varying the min and max numbers, to no avail. forms.py: class BingoSquareForm(ModelForm): class Meta: model = BingoCardSquare exclude = ('created_date',) BingoSquareFormset = inlineformset_factory( BingoCard, BingoCardSquare, form=BingoSquareForm, min_num=24, validate_min=True, max_num=24, validate_max=True ) tests.py class BingoSquareFormsetTests(TestCase): def setUp(self): self.user = User.objects.get_or_create( username='FormsetTestUser', email='something@yahoo.org' )[0] self.user.set_password('bingo') self.user.save() self.card = BingoCard.objects.get_or_create( title='FormsetTest', free_space='free_space', creator=self.user, )[0] self.data = { 'form-TOTAL_FORMS': '24', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '24', 'form-MIN_NUM_FORMS': '24' } for i in range(24): text_key = 'form-{}-text'.format(i) text_value = 'square {}'.format(i) self.data[text_key] = text_value def test_formset_accepts_valid_data(self): formset = … -
Django conditional order by with many to many field
I need conditional ordering in django but don't know how to do it. I have two models: User and Post. Post model have seen_users = ManyToManyField(User) field. I want to get all posts, but my seen posts should be at first. I've tried with this code: Post.objects.all().annotate( is_seen=Case( When(seen_users__id__exact=me.id, then=1), default=0, output_field=IntegerField() ) ).order_by('-is_seen', '-created') but this one returns duplicated posts. I tried to add distinct but no luck. -
can i deploy a django web app on a web server i can't configure?
So we got a project at uni to create a website. We have not received any specific on what technologies to use, we were only given a theme. These projects will end up hosted on the uni website. The host for the website is: http://uni.co.uk The projects will end up at the url: http://uni.co.uk/module_code/projects/ Normally, the tutor expects just a front-end solution with a bundle of html, css and javascript files. I would like to add some back-end to make the website dynamic. I have played around with Django and node.js and I quite fancy Django and want to give it a try for this project. My only issue is that the web server my project will end up on is not accessible to me and I can't configure it. Is there any way I can still use some back-end in my project if I cannot access the main host web server configuration ? Any way I can create my own tiny web server at that url where my project ends up ? Not expecting any code solutions, if someone could just tell me if this is possible and point me to the right resource for information. I do apologize … -
Django Admin Inline Translation
Apologies if there is a similar question, I was having a hard time finding one to work out right. I am building an API with Django Rest Framework that will serve multiple languages. I have built in translations using the modeltranslation package, and it works well. Each of my users has a language specified to them, such as 'en' for English and 'no' for Norwegian. I am wanting to make my inline for a model choose the correct language for the user. Does anybody know how I can get this to work? Here is an example of code to more clearly demonstrate: Please note that I have a Dish Model where name and instructions have both translations: class Dish(models.Model): name = models.CharField(max_length=128) instructions = models.TextField(blank=True) food = models.ManyToManyField('Food', through='DishIngredient') user = models.ForeignKey(User, blank=True, null=True, default=None) I have a Food Model where name has translations: class Food(models.Model): name = models.CharField(max_length=128) And finally a DishIngredient Model: class DishIngredient(models.Model): food = models.ForeignKey('Food', on_delete=models.CASCADE) dish = models.ForeignKey('Dish', on_delete=models.CASCADE) quantity = models.FloatField() Now, in my admin.py page, I have: class DishAdmin(TranslationAdmin): model = Dish list_display = ['name_en', 'name_no'] inlines = [FoodQuantityInline] class FoodQuantityInline(admin.TabularInline): model = DishIngredient This works to show the proper dish ingredients in … -
How to use a function to pass the result to 'queryset'?
I'm working on a Python/Django project. I have to use the YearArchiveView base class, so I have this: class ArchiveView(YearArchiveView): queryset = ArticlePage.objects.all() make_object_list = True date_field = 'date' template_name='btcmag/pages/archives_list.html' allow_future = False context_object_name = 'articles' def extract_month(self, article): 'extracts the starting date from an entity' return article.date.month def extract_year(self, article): 'extracts the starting date from an entity' return article.date.year Instead of having queryset = ArticlePage.objects.all(), I would like to have a function returning the correct Queryset. Something like: queryset = getQuerySet() At the same time I have to pass in some parameters. I tried defining the function within the class, calling it with self and alone, but no luck. Where do I have to define the function/method? How can I pass it to queryset? -
Verifying text is present on web page
I am trying to perform behavior tests using django-behave against selenium. I am fairly new to behavior tests and because of my lack of experience, what I tried was: @then(u'is {thing} present') def step_impl(context, thing): #testing other things assert_true("text" in context.driver.page_source) This did not seem to work for multiple reasons. Firstly, I get the error AttributeError: 'PatchedContext' object has no attribute 'driver', which tells me my whole idea is wrong. Secondly, even if this worked, I wouldn't be capable of testing all of my pages with just this test, as I have to specifically give the "text" that I want to verify if present. Is there a way to test this with only 1 assertion? -
How to delete an object after 24hrs since creation of the same
I want to delete an instance after 24 hours since that instance has been created how to do that with celery How can i start the "TIMER" after the creation of an instance? I want something like Snapchat -
django user followers retrival from database
I have an application with a user follower system which I have been able to achieve but I try to retrieve individual user followers and following but I could not get it. Below is my code View.py def following(request): query = Profile.objects.filter(request.user.following) context = { 'query': query } template = 'following.html' return render(request, template, context) additional codes would be added on request. -
Django QuerySet API inverse field lookup
I'm wondering if it is somehow possible to use "the inverse" of the __contains fields lookup. https://docs.djangoproject.com/en/1.11/ref/models/querysets/#contains So for example: class Person(models.Model): ... last_name = models.CharField() And with this Person model I could do for example the following query that'll return the Persons that have a last_name field that would fit in the string given: >>> Person.objects.filter(last_name__contains='John Doe, Jane Roe, ...') <QuerySet: [Person: Donald Doe]> -
Using WhiteNoise with Django to serve directories of HTML files
I'm using Whitenoise successfully to serve all my Django site's static files under a /static/ path. I'd also like to have a couple of other directories of HTML files, images, etc served at different paths (e.g. /foo/my_file.html and /bar/hello.html). I think Whitenoise lets you add further directories using add_files() but I can't figure out how to use this with a Django site that's using the DjangoWhiteNoise class, and with a wsgi.py that currently looks like: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") application = get_wsgi_application() Has anyone done something like this? -
Is it possible for a queryset filter to not work properly? Django 1.11.12
I ran the code below... and somehow... I got a couple of campaigns that were not active and were passed into the update_existing_campaigns. I am a little mindblown as to how this happened... it was also only a couple of inactive campaigns that were passed in, not all of them. How is this possible? all_campaigns = AdCampaign.objects.all() active_campaigns = AdCampaign.objects.filter(active=True) update_existing_campaigns(active_campaigns) -
Django Using Slug Field for Detail URL
I'm attempting to setup my site so that the url for my job-detail will use a slug field instead of a pk. It's telling me that it cannot find my job with the given slug (which is an int, 147). urls: urlpatterns = [ url(r'^careers$', views.job_list, name='job-list'), url(r'^careers/(?P<slug>[0-9]+)/$', views.JobDetailView.as_view(), name='job-detail'), ] view: class JobDetailView(CacheMixin, DetailView): model = Job pk_url_kwarg = 'slug' def get_object(self, *args, **kwargs): # Call the superclass object = super(JobDetailView, self).get_object() # Return the object return object def get(self, request, *args, **kwargs): object = super(JobDetailView, self).get(request, *args, **kwargs) return object model: class Job(UpdateAble, PublishAble, models.Model): slug = models.CharField(unique=True, max_length=25) facility = models.ForeignKey('Facility') recruiter = models.ForeignKey('Recruiter') title = models.TextField() practice_description = models.TextField(blank=True, default="") public_description = models.TextField(blank=True, default="") objects = JobManager() def get_next(self, **kwargs): jobs = Job.objects.published() next = next_in_order(self, qs=jobs) if not next: next = jobs[0] return next def get_prev(self, **kwargs): jobs = Job.objects.published() prev = prev_in_order(self, qs=jobs) if not prev: prev = jobs[len(jobs)-1] return prev def __str__(self): return f'{self.facility}; {self.title}' manager: class JobManager(models.Manager): def published(self): return super(JobManager, self).get_queryset().filter(is_published=True).order_by('facility__name', 'title') -
Sending an email from python (purchased from wix)
A client of mine has recently decided to get his domain and email packages from Wix, and then decided to use that domain with a Django/python application. I cannot find a quick way to send an email using a python script, I have tried to use the same gmail settings to no avail. Is there a tutorial somewhere that I can follow? has anyone accomplished that before? -
Can't connect to docker from Django, but can connect directly and in shell
I have a Python/Django app that allows users to manage docker instances (with some abstraction). I can control the docker containers from bash and from the Django shell just fine, but when I try to run the same code from my Django views, which are running through Gunicorn as the same user as I am running bash and the Django shell from, but Gunicorn gives the following output: ERROR while fetching server API version: ('Connection aborted.', error(13, 'Permission denied')) The user that Gunicorn is running under is a member of the "docker" group, and I've restarted my server to be sure that the permissions should be in affect. I'm not sure what else to check or do. -
how to run popen in django with apache?
I met problem when try to upload file from my web server to s3. django 1.7.8 + python 2.7 os.popen(asw s3 cp c:\1.txt s3://bucket) The popen run well in my develop env(VS code, debug running ok) no apache. But it seems not run at all on product env, which apache hosts. Any body has some ideas? Thank you so much! -
Django: stop resubmit duplicate data when many time press enter key within keyboard
I created a form for data submission. When a user successfully fillup that form, I am using HTTP redirect method. Now Everything is okay and data do not resubmit when user want to page refresh. But user fillup that form and press Enter key again and again. Same data added how much user press Enter key button. I want to stop that. A user can be press Enter key onetime. Data do not add in the database if a user will press Enter Keyboard second or more time. this is my form html file {% extends "shop/base.html" %} {% block content_area %} <div class="row"> <div class="col-lg-5"> <p>Customers Details</p> <hr> <div class="customers_info_due"> <p>Invoice ID: : {{due_customers.customer_uid}}</p> <p>Name: {{due_customers.customer_name}}</p> <p>Product Name: {{due_customers.customer_product_name}}</p> <p>Price: {{due_customers.customer_price}} TK</p> <p style="color:red">Customer Paid First Time: {{due_customers.customer_first_time_payment}} Taka</p> {% if track_invoice %} <table class="table"> <thead> <tr> <th>SL</th> <th>Paid Taka</th> <th>Paid Date</th> </tr> </thead> <tbody> {% for x in track_invoice %} <tr> <td>{{forloop.counter}}</td> <td>{{x.customer_due}}</td> <td>{{x.customer_due_date}}</td> </tr> {% endfor %} <tr> <td> Total</td> <td><b>{{sum_cost_taka}}</b> TK </td> </tr> </tbody> </table> {% else %} {% endif %} <p>WARRENTY: {{due_customers.customer_product_warrenty}}</p> <p>QN: {{due_customers.customer_product_quantity}}</p> <p>Mobile No: {{due_customers.customer_mobile_no}}</p> <p>Sell Date: {{due_customers.customer_sell_date}}</p> </div> </div> <div class="col-lg-6"> <p>Update customers due info</p> <hr> <div class="due_forms"> <form action="{% url "shop:dueupdate" … -
Powershell LDAP Bind
I've wrote a Python app that successfully binds and connections to my LDAP server. However, I want to run a command to sync the LDAP users with my user database, using the following: python manage.py ldap_sync_users When I attempt to run the command it states: raise LDAPOperationResult(result=result['result'], description=result['description'], dn=result['dn'], message=result['message'], response_type=result['type']) ldap3.core.exceptions.LDAPOperationsErrorResult: LDAPOperationsErrorResult - 1 - operationsError - None - 000004DC: LdapErr: DSID-0C0907C2, comment: In order to perform this operation a successful bind must be completed o n the connection., data 0, v2580 - searchResDone - None My question is how can I bind to the LDAP connection in powershell prior to running my python script? -
Unable to understand the flow of list serializer update in django rest framework
I am using list Serializer by many = True. The create method is running perfectly but i am unable to understand the flow of custom update method of list serializer in documentation of django rest framework. Using the base of list serializer is clear but when i am using it in code the flow is not understandable. I am not able to understand what book.items mean in the fourth line. What is book ? In the documentation it is also asking to add an explicit id field to the instance serializer. The default implicitly-generated id field is marked as read_only. Looking to understand what documentation is saying and how to implement it. The context from documentation is give below. class BookListSerializer(serializers.ListSerializer): def update(self, instance, validated_data): # Maps for id->instance and id->data item. book_mapping = {book.id: book for book in instance} data_mapping = {item['id']: item for item in validated_data} # Perform creations and updates. ret = [] for book_id, data in data_mapping.items(): book = book_mapping.get(book_id, None) if book is None: ret.append(self.child.create(data)) else: ret.append(self.child.update(book, data)) # Perform deletions. for book_id, book in book_mapping.items(): if book_id not in data_mapping:a book.delete() return ret -
Django: Quickfix to pass JSON values from view to template
Good day SO, this is not a question per-se, but a quickfix solution I found while learning how to use Django and Python. I figured it might help someone else so here it goes.. I want to pass a queryset onto a ListView (I made an auto-refreshing div via jquery) and wanted to pull updated data in JSON every few seconds. Here is my view.py: import json from django.core import serializers from django.template import loader from django.views.generic.list import ListView from .models import * class getSomeJson(ListView): template_name='divPortionToRefresh.html' def get_context_data(self, **kwargs): find_id = self.kwargs['slug'] updateItem = Model.objects.filter(Model_ID=find_id) context = { 'jsonData': serializers.serialize('json', updateItem) } return context Here is my HTML portion: <script text="text/javascript"> var rawData = {{ jsonData|safe }}; </script> I hope I helped someone somewhere.. :) Have a nice day SO! -
Django Restful API Get Request Returns Nothing
I am trying to test the output of my APIs. class TestApiStatusCode(TestCase): client = APIClient() def test_urls(self): response = self.client.get('/api/total-fund-aum') print(response.content) self.assertEqual(response.status_code,200) However, when I try to print the response.content, I get this output: b'[]'. From my browser, data is being returned however. Why is this the case? I am using django-rest-framework -
Django Rest Framework serializers allow dotted notation
I'm using Django 1.11 and Django Rest Framework to make an REST API. I have models as: class Product(models.Model): ... class Image(models.Model): product = ForeignKey(Product) when i'm creating a POST request to create new product ( Content-Type: multipart\form-data]) i have to use the notation: images[0]image : <SOME_IMAGE_FILE> images[1]image : <SOME_IMAGE_FILE> Is there a way to use a dotted notation like: images.0.image : <SOME_IMAGE_FILE> images.1.image : <SOME_IMAGE_FILE> Should i create a custom parser ( http://www.django-rest-framework.org/api-guide/parsers/ ) ? -
Django Test API Output
I want to test the output of some API urls. Currently my code tests the status_codes of these API urls. class TestApiStatusCode(TestCase): client = Client() def test_urls(self): response = self.client.get('/api/total-fund-aum') self.assertEqual(response.status_code,200) But how can I get the output of the api urls? -
Vue and Django Development Environment
I just started a new little project for learning purposes and I want to try out Vue js with Django (with DRF). I'm trying to use vue loader (webpack-simple template). The problem is that I don't know how to synchronize npm run dev and python manage.py runserver. I don't know how to access a template that is rendered by django in webpack-dev-server. I mean I have a template with django-template specific keywords like {% load static %} that is not handled by webpack-dev-server, obviously. I know I can build it everytime npm run build, but that's kinda annoying and boring to wait for it everytime I want to make a little change. In webpack, it's specified to run on a default index.html file, how can I make it work on the template that is actually rendered in 127.0.0.1:8000 with python manage.py runserver running? Is there an alternative? Thanks in advance for answers!