Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Queryset for counting the object created for last one day
Lets say i have a model class Testmodel(): amount = models.IntegerField(null=True) contact = models.CharField() and I am creating the object for this model(Testmodel). Now I want to find out the count of object created in last 24 hours by contact field. past = arrow.utcnow().shift(hours=-24) what could be the best way of making query. Any help would be appreciated. -
Error when trying to update_index with an ElasticSearch backend
I have a Django environment set up to use ElasticSearch as the backend for our CMS, which is in Wagtail. I installed a recent version of ES (5.6.5 according to the service when I CURL it), and have my settings file using 'wagtail.wagtailsearch.backends.elasticsearch5' as the 'BACKEND' for WAGTAILSEARCH_BACKENDS. Wagtail is on version 1.13.1 according to my pip freeze, and the elasticsearch Python package is at 5.5.2. This all seems right per my reading of http://docs.wagtail.io/en/v1.13.1/topics/search/backends.html. The problem I am having is that when I try to do a './manage.py update_index', it gives me the following error: $ ./manage.py update_index Updating backend: default default: Rebuilding index wagtail__wagtailcore_page Traceback (most recent call last): File "manage.py", line 17, in <module> execute_from_command_line(sys.argv) File "/home/vagrant/.virtualenvs/wrds/lib/python3.5/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/vagrant/.virtualenvs/wrds/lib/python3.5/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/vagrant/.virtualenvs/wrds/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/vagrant/.virtualenvs/wrds/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/vagrant/.virtualenvs/wrds/lib/python3.5/site-packages/wagtail/wagtailsearch/management/commands/update_index.py", line 120, in handle self.update_backend(backend_name, schema_only=options.get('schema_only', False)) File "/home/vagrant/.virtualenvs/wrds/lib/python3.5/site-packages/wagtail/wagtailsearch/management/commands/update_index.py", line 77, in update_backend index.add_model(model) File "/home/vagrant/.virtualenvs/wrds/lib/python3.5/site-packages/wagtail/wagtailsearch/backends/elasticsearch2.py", line 113, in add_model index=self.name, doc_type=mapping.get_document_type(), body=mapping.get_mapping(), File "/home/vagrant/.virtualenvs/wrds/lib/python3.5/site-packages/wagtail/wagtailsearch/backends/elasticsearch.py", line 137, in get_mapping self.get_field_mapping(field) for field in self.model.get_search_fields() File "/home/vagrant/.virtualenvs/wrds/lib/python3.5/site-packages/wagtail/wagtailsearch/backends/elasticsearch.py", line 137, in <genexpr> self.get_field_mapping(field) for field in self.model.get_search_fields() File "/home/vagrant/.virtualenvs/wrds/lib/python3.5/site-packages/wagtail/wagtailsearch/backends/elasticsearch.py", line … -
Pairing up Django backend with frontend
Here's my problem. I have a small javascript game, which I am trying to pair with Django backend, to store highscores in sessions, maybe implement a highscore board, login, etc. in future. Just as a practice of interaction between front/backend. So far I have the game running in javascript, and my plan is this: upon getting a score, it sends an ajax (jQuery) request to django, telling django to increment the score. Now here's few questions I have in mind: Is it possible to render the highscore to template with Django/DTL? Score is set at 0, and each time a player scores, ajax-call to django backend will increment the score by one, and render it in template without refreshing the page. (Also compare it to highscore in sessions, and overwrite it if the new score is higher) To my understanding, it requires a page refresh, which is not what I want. Should I increment the score in frontend with JS, and after a game ends, send the score to django backend to compare it with the one in sessions etc etc. Can javascript access values of django view? JSON maybe? I'm still hesitating if I am heading to the right … -
How does Django media works behind the scene?
I'm a bit curious about Django media. This question isn't about the usage itself, but about what happens behind the scene. I have a production server with a media folder containing my media (obvious), this folder weights about 40Mo. When I run ./manage.py mediabackup it generates a tar file of almost 900Mo. I wonder how Django stores 900Mo (tar, compressed?) into a 40Mo folder. I guess it actually does some magic behind the scene, but what? -
Django - page loads incorrectly
In my all web page there is menu that enables us to navigate it to respective url. Lets say in my home page there is a menu called Owner Maintenance that contains few items called create, delete, view and update. When I am in home page and I click on create owner page(sub menu of Owner Maintenance) then it goes to create url, and now in create page also I have menu - Owner Maintenance. If from create owner page if I click view owner sub menu item it should go to its url and vice versa. Code :- 3 html file currently I have - adminHome.html, createOwner.html and viewOwner.html common code snippet for dropdown in html :- <div class="dropdown"> <button onclick="myFunction()" class="dropbtn">Owner Maintainance</button> <div id="actionDropdown" class="dropdown-content"> <a href="ownerMaint">Create Owner</a> <a href="deleteOwner">Delete Owner Details</a> <a href="updateOwner">Update Owner Details</a> <a href="readOwner">View Owner Details</a> </div> </div> urls.py :- urlpatterns = [path('successMsg/', views.success), path('adminMain/',views.adminMain), path('readOwner/',views.readOwner), path('ownerMaint/',views.ownerMaintainance), ] views.py :- def readOwner(request): ownerName = "rrr" if request.method == "POST": MyLoginForm = OwnerDetails(request.POST) if MyLoginForm.is_valid(): ownerName = MyLoginForm.cleaned_data['ownerName'] q = Owner.objects.get(name=ownerName) else: MyLoginForm = OwnerDetails() return render(request, 'main/readOwner.html',{'ownerName': ownerName}) def ownerMaintainance(request): your_name = "not logged in" if request.method == "POST": MyLoginForm = OwnerDetails(request.POST) if MyLoginForm.is_valid(): … -
Django pycharm can't find setting.py and manage.py in my project
enter image description here Help plllz !! -
Django Tests Pass with SQLite, Fail with Other DB's
My Django tests all pass when I use the built-in SQLite as my database. However, when I switch to the built-in MySQL and PostgreSQL, they fail. (All local database servers.) The connections to the DB are live enough -- the database is created and migrations applied. But the tests aren't even hitting views.py before the test server returns a 500 (and no additional explanation beyond "Server Error", even in debug mode). I'm using Django with Django REST Framework, and testing with REST Framework's RequestsClient class. My test fixtures are generated with Factory Boy. Any ideas? I have a vague feeling it's to do with Factory Boy but nothing concrete. The fact that it fails with multiple databases, and successfully builds the tables, makes me suspect it's not the database itself. Versions tested: Django 1.11.6 and 1.11.9 Django REST Framework 3.7.1 Postgres 10.1 MySQL 5.7.21 Factory Boy 2.9.2 -
Django: change language from timesince
I want to change the language of timesince. Do I need to change directly in my django source or is there a way to modify TIMESINCE_CHUNKS variable in the settings file? -
Connecting to an oracle database through Django
I would like to connect to an existing oracle database though Django and write a select statement to query the results. I am a beginner to Django and would like to know the steps to follow to achieve the same. I did change the settings.py file to reflect the changes DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'name', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'host.com', 'PORT': '1521', } } -
Django request.post no data available
I have already searched for similar questions on StackOverflow but could not find the solution that would work for me. I have the following code snippet: def post_request(request): if request.method == "POST": access_token = AccessToken.objects.get(token = request.POST.get("access_token"), expires__gt = timezone.now()) As I get the following response to my request: AccessToken matching query does not exist. , I started debugging the app and found that request.POST = . I have no data in there I am making a POST request in POSTMAN, where I added the data to raw -> form-data. I also tried sending data through raw->json but anyway the request.POST does not contain anything. What is the cause that I have no Post data? How can I get the POST data? Thank you! -
What is the right method to use many to one and one to many relationships in Mongo DB?
I am using mongoengine with Python and Django. models.py for DB Design with mongoengine class Skills(EmbeddedDocument): skill_name = fields.StringField(required=True) class ProfessionalProfile(Document): user_id = fields.IntField(required=True) skills = fields.ListField(fields.EmbeddedDocumentField(Skills)) Note: I am using Django along with Mongoengine so I store the id to document. If we go by this method, each user should have one document right? In SQL we will be using the same table with an extra column with a foreign key to link to the user. The above-mentioned method with mongoengine works! "_id" : ObjectId("5a70b44d8db17c2af0ec3d75"), "user_id" : 2, "skills" : [ { "skill_name" : "Django" }, { "skill_name" : "Photoshop" } ] But is this the right way to do it? -
JSON serialisers and alternative http responses with Django
I'm trying to create a filter system on a click event - using an AJAX post method to update the context that is shown on the template. I'm currently using: return HttpResponse(json.dumps(context), content_type="application/json") To return a response with a context object. However, this doesn't quite work with certain object types: TypeError: is not JSON serializable I know there's something regarding serialisers but I'm currently unable to either a.) use them correctly or b.) use them at all. For some context I'm passing filter variables to the view with the AJAX post method - then: posts = Post.published.filter(category__name__in=category_filter_items) And adding this to my context: context['posts'] = posts Would anyone know the correct way to update the context is such a manner? -
Django+Paramiko SSH
def testssh(request): build = 'DISPLAY=:0 chromium-browser' connection = paramiko.SSHClient() connection.set_missing_host_key_policy(paramiko.AutoAddPolicy()) connection.connect(ip, username='pio', password='piopio') ftp = connection.open_sftp() f = ftp.open('run.sh', 'w+') f.write(build) command = "sh run.sh" stdin, stdout, stderr = connection.exec_command(command) connection.close() return render(request, 'testssh.html') The function writes run.sh to another remote machine and opens the chrome on that machine. The chrome opens many tabs until I stop running the script. It looks like an infinite loop. What did I miss? -
Django 1.11.5 Class based (generic) redirect function with args
Within my created application within Django 1.11.5 I have created update, create and delete functionality using ClassBased or Generic views which do work, however I am having a problem redirecting my user to correct dynamic page. In a instatcne if a user has opened a details page for a specific product, when the user updates the product infromation I want the application to redirect user back to the updated page. As of yet I have achieved this using args by specifing a specific id, which obsiously redirects to specified page but not dynamic. Any help or assitance regarding the topic would be trully appriciated. views.py from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.core.urlresolvers import reverse_lazy from django.core.urlresolvers import reverse class CommentUpdate(UpdateView): model = Comment fields = ['comment_body'] def get_success_url(self): return reverse('detail', args=(2,)) #how to make this part dynamic example of detail view. class DetailsView(generic.DetailView): model = Product template_name = 'details.html' urls.py (just in case) url(r'^(?P<pk>[0-9]+)/$', views.DetailsView.as_view(), name="detail"), url(r'review/(?P<pk>[0-9]+)/$',views.CommentUpdate.as_view(), name="comment-update"), -
C:\Python3.6.3\python manage.py runserver is not responding correctly
C:\Python3.6.3\python manage.py runserver is not responding correctly. I checked the references and documents both python and Django is installed correctly. -
django.db.utils.IntegrityError: (1048, "Column 'category_type' cannot be null")
goods.py class Goods(models.Model): category = models.ForeignKey(GoodsCategory, verbose_name='xxx') goods_sn = models.CharField(default='', max_length=50, verbose_name='xxx') name = models.CharField(max_length=300, verbose_name='xxx') click_num = models.IntegerField(default=0, verbose_name='xxx') sold_num = models.IntegerField(default=0, verbose_name='xxx') GoodsCategory.py class GoodsCategory(models.Model): CATEGORY_TYPE = ( (1, "Level 1"), (2, "Level 2"), (3, "Level 3"), ) name = models.CharField(default="", max_length=30, verbose_name="Category name", help_text="Category name") code = models.CharField(default="", max_length=30) desc = models.TextField(default="", verbose_name="describe") category_type = models.IntegerField(choices=CATEGORY_TYPE, verbose_name="Category Level", help_text="Category Leve") parent_category = models.ForeignKey("self", null=True, blank=True, related_name="sub_cat") is_tab = models.BooleanField(default=False) add_time = models.DateTimeField(default=datetime.now) import_goods_data.py for goods_detail in row_data: goods = Goods() goods.name = goods_detail["name"] goods.market_price = float(int(goods_detail["market_price"].replace("¥", "").replace("$", ""))) goods.shop_price = float(int(goods_detail["sale_price"].replace("¥", "").replace("$", ""))) goods.goods_brief = goods_detail["desc"] if goods_detail["desc"] is not None else "" goods.goods_desc = goods_detail["goods_desc"] if goods_detail["goods_desc"] is not None else "" goods.goods_front_image = goods_detail["images"][0] if goods_detail["images"] else "" category_name = goods_detail["categorys"][-1] categories = GoodsCategory.objects.filter(name=category_name) if categories.exists(): category = categories[0] else: category = GoodsCategory.objects.create(name=category_name) goods.category = category goods.save() When I run this script, I get this error: django.db.utils.IntegrityError: (1048, "Column 'category_type' cannot be null") I have tried many times and still haven't solved this problem. Can you help me? -
python virtualenv os.py not found although exists in system wide
With virtualenv version 1.10.1 I've created /var/www/vhosts/example.com/django-app-env/ and lib64 point to lib within the /lib/python2.7 directory os.py points at /usr/lib64/python2.7/os.py which exists. However, passenger reports File "/var/www/vhosts/example.com/django-app-env/lib64/python2.7/os.py", line 312, in execl execv(file, args) OSError: [Errno 2] No such file or directory Its Python 2.7.5 Why? -
How to properly set a django secret key on a gandi simple instance?
I think the question is quite descriptive of my problem, but I will set the whole story anyway. I have a website ready for production. I tested it with clear secret key set in the settings.py file, exactly as it is said not to, with a big warning :) Now that I’m sure that the website works correctly, I’m trying to find a way to deploy it again, with hidden secret key, but I don’t know how. I tested locally, with secret key set as environment variable, but it does not work on the gandi instance. Is it possible to set environment variables on gandi’s simple instance ? Is there some other proper ways to hide that key ? Thanks for your answers. -
Django model - how to go about this concept
I have a product model with the following: class Product(models.Model): name = models.CharField(max_length=255) handle = models.CharField(max_length=55) summary = models.CharField(max_length=255, blank=True) category = models.ForeignKey(Category) Above is just the product detail, but there are 3 types of pricing: Standard - normal regular pricing by filling the price field Variant - pricing with product variants (size, colour, etc.) with their respective prices Combined - this is a combination of other saved products, with a custom price provided by user. For 1 and 2 I have the below model. If the product model has more than 1 price on StandardProduct model then I know it has variants. class StandardProduct(models.Model): variant_type = models.CharField(max_length=55) variant_name = models.CharField(max_lenght=55) product = models.ForeignKey(Product) sku = models.CharField(max_length=55, blank=True, null=True) barcode = models.CharField(max_length=55, blank=True, null=True) selling_price = models.DecimalField(max_length=15, decimal_places=2) How do I go about creating the CombinedProduct model? The combined product model can have different created products inside (with their quantities). The price is specified by the user. Below is what I have, but I don't know how to approach this. class CombinedProduct(models.Model): product = models.ForeignKey(Product) item = models.ForeignKey(StandardProduct) quantity = models.DecimalField(max_length=15, decimal_places=2) -
Only return the value instead of {'this' : 5} in Django
Sorry for the unclear title. Here is my joueur.py def vie_pourcentage_user (self): viepourcentageuser = (self.user.profile.vie * 100) / self.user.profile.vie_max return {'viepourcentageuser': int(viepourcentageuser)} def energie_pourcentage_user (self): energiepourcentageuser = (self.user.profile.energie * 100) / self.user.profile.energie_max return {'viepourcentageuser': int(energiepourcentageuser)} Here is my view.py def index(request): viepourcentageuser = joueur.vie_pourcentage_user(request) energiepourcentageuser = joueur.energie_pourcentage_user(request) return render(request, 'base.html', { 'viepourcentageuser': viepourcentageuser, 'energiepourcentageuser': energiepourcentageuser, }) Here is what I see : {'viepourcentageuser': 100} Here is what I would like to see : 100 Sorry I know this is basics but it seemed like I missed something. Thanks ! -
How eliminate selection in ManytoMany form field
I have this model: class Transaction(models.Model): date = models.DateTimeField(auto_now_add=True) buyer = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name="buyer") smokers = models.ManyToManyField(UserProfile) price = models.FloatField(blank=True) And have this form: class TransactionForm(ModelForm): class Meta: model = Transaction fields = ['smokers', 'price',] I would like to access smokers field and eliminate few options (that user won't be able to select it or even see it in HTML). Is that even possible? -
How to get prerequisites for gettingstartedwithdjango.com tutorial?
I'm following the tutorial "Getting Started With Django" on gettingstartedwithdjango.com. I'm at the prerequisites on a VM that runs Precise64. The maker supplies a shell script named postinstall.sh. Executing that, it tries to install, among others, ruby1.8.7 but fails to download it. After that it wants to install net-ssh-gateway, mime-types, chef and puppet, which all fail, because they need ruby2.0 or 2.2. So i've done "apt get install ruby", which got me ruby1.8. I've tried to get a newer version, but it couldn't be found. When I run the script again it still fails to install the apps, that need ruby. And installing them via "apt get install" only works for puppy, the others are unknown. I would love to do the tutorial, but I fear this applications or libraries are needed. So how do I get those libraries/applications installed? -
site-packages and organizing a multi-app django environment to make sense of templates
I am trying to figure out the best and most logical way to install multiple Django apps and have them organized. In actual fact, I am trying to make sure that my templates are inheriting in the right manner but first off I thought perhaps some Django gurus can let me know what is the best way to organize a multi-app Django site. Starting off, I have used Wagtail as my core installation first and then decided to install more apps from there. Basically, on top of Wagtail, I have decided to install puput following their instructions from https://puput.readthedocs.io/en/latest/setup.html#installation-on-top-of-wagtail pip install puput And at the same time in the same virtualenv I also installed the blog app thru python manage.py startapp blog from this very good tutorial from here. So basically I have both these apps in my INSTALLED_APPS settings but puput is in site-packages whereas the blog app resides in the folder beside where manage.py is. So I was wondering should I move puput to the same directory such that PROJECT_DIR |-blog/ |-puput/ |-mysite/ |--|-settings/ |--|-templates/ |--|-urls.py |--|-etc |-manage.py |-etc The main reason I am asking this is because I am trying to figure out the best way people … -
Displaying images in html - Django
I have a little problem, and I dont have idea why my project doesn't work how I want. I have a models.py class Strona(models.Model): title = models.CharField(max_length=250, verbose_name="Tytuł", help_text="Podaj tytuł artykułu") slug = models.SlugField(unique=True, verbose_name="Adres url SEO", help_text="Automatycznie tworzony przyjazny adres URL") content = HTMLField(verbose_name="Treść artykułu", help_text="Wypełnij treścią artykułu") image = models.FileField(upload_to='blog_images',verbose_name="Obrazek", help_text="Załącz obraz") and in view.py I have from django.shortcuts import render from .models import Strona def strona_glowna(request): strona_glowna = Strona.objects.all() context = {'strona_glowna': strona_glowna} return render(request, 'strona/index.html', context=context) After that I've create the html file and include inside a code : ... {% for strona in strona_glowna %} <strong>{{strona.title}}</strong><br> {% if strona.image == True %} <img src="{{strona.image.url}}"><br> {% else %} {% endif %} <p>{{strona.content|safe}}<p></p> {% endfor %} ... in setting.py I declared: STATIC_URL = '/static/' MEDIA_URL = '/media/' And the problem is, when I reload a website the images doesn't show. I think the routing for upload is ok, but I don't know why I can't display the images. Any ideas? -
Unknown field error in django
I am trying to follow a tutorial and i get this error when i run makemigrations, however in the tutorial, they dont get the error. here is the tutorial: https://www.codingforentrepreneurs.com/blog/how-to-create-a-custom-django-user-model/ This is the error i get at 24:59 in the video: django.core.exceptions.FieldError: Unknown field(s) (username) specified for CustomUser. Here is full traceback: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/core/management/base.py", line 327, in execute self.check() File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/core/checks/urls.py", line 26, in check_resolver return check_method() File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/urls/resolvers.py", line 254, in check for pattern in self.url_patterns: File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/urls/resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/site-packages/dj ango/urls/resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "/Users/chrismaltez/anaconda3/envs/simplesocialenv/lib/python3.5/importlib/__init …