Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to optimally invalidate a per-view cache in Django?
I am not using @cache_page decorators instead I am using per-view cache in the URLconf as suggested in the Django documentation (1.11.8). Now, I want to invalidate a key that I use to cache my list view if a new post is created or deleted. I found 2 answers online first, which does not suggest a clean way to do this and second, which is a good way to do this but uses a redundant request to the view. Is there a better way to do this? Moreover, where should I define the signal receiver for post_save and post_delete (either in my url.py or model.py)? Which one is a good practice? -
Django-Filer Pre-existing images
I've uploaded a large amount of image files to filer. I made a new webapp about coins that needs to use those image files. The ticker of the coin will be exactly the same as the name of the image file. Example: Ticker=ASD Image=ASD.png How do I use my model to call a preexisting image or upload a new image if the image was not found. from django.db import models from django.conf import settings # Create your models here. class coin(models.Model): name = models.CharField(blank=False, max_length=64, verbose_name='Coin Name', unique=True, help_text='Please enter coin name') ticker = models.CharField(blank=False, max_length=10, verbose_name='Ticker') icon = models.FileImageField -
Prefetch_related in Django views results in surplus database queries
I have blown my mind trying to figure what I am doing wrong in this code: contacts = Contact.objects.user(request.user).prefetch_related( Prefetch('contact_phone', queryset = ContactPhone.objects.order_by('value'))) for contact in contacts: for contact_phone in contact.contact_phone.all(): # do something Django hits database several times. Any ideas ? -
Django formfield_for_manytomany doesn't work
I have these two models in my models.py file: class Caar(models.Model): car_id = models.AutoField(primary_key=True) model_name = models.CharField(max_length=255) parent = models.CharField(max_length=255) and class Data(models.Model): number = models.IntegerField() observation = models.TextField() car = models.ManyToManyField(Caar) I want to show Caar in admin, using TabularInline. Also, I want to filter ManyToMany field. Everything works fine, except for the filtering. I use, in admin.py file: admin.site.register(Caar) class CaarInline(admin.TabularInline): model = Data.car.through readonly_fields = [ 'caar_model_name', ] def caar_model_name(self, instance): return instance.caar.model_name class DataAdmin(admin.ModelAdmin): inlines = [CaarInline,] exclude = ('car',) change_form_template = 'admin/web/data/change_form.html' def formfield_for_manytomany(self, db_field, request, **kwargs): print('first') if db_field.name == "car": print('second') kwargs["queryset"] = Caar.objects.filter(car_id=231) return super().formfield_for_manytomany(db_field, request, **kwargs) def add_view(self, request, form_url='', extra_context=None): extra_context = extra_context or {} # some truncated code. ignore it if request.method == 'GET' and 'value' in request.GET: value = request.GET.get('value'); extra_context['value'] = value else: extra_context['value'] = ''; return super(DataAdmin, self).add_view(request, form_url, extra_context=extra_context,) admin.site.register(Data, DataAdmin) When I load the page in admin I can't see first and neither second printing. What am I doing wrong? Thanks. -
How to link to local file download in HTML?
I'm using this tag: <a href:"{{ arquivo.caminho }}" download>link</a> With the download atribute to make a download link files from my local network (tiff images) but the downloaded file is a .tiff file containing the HTML code of my page. I noticed that the link returned from my page is prefixed by address of my django: http://127.0.0.1:8000/172.23.5.17/Imagens/etc... My HTML code: <tr> <td id="td_result"><p class="resultados_p">{{ resultado.nome }}</p></td> <td> <a href="{{resultado.download}}" download> <div class="download"></div> </a> </td> </tr> Value of resultado.download: \\172.23.5.17\Imagens\landsat\IMAGENS_LANDSAT_8_2017\Processadas\003_068l8_oli_002065_20140803_b654_fuseo_sirgas2000_utm.tiff (I already tried changing the bars) Link returned by page: http://127.0.0.1:8000/172.23.5.17/Imagens/landsat/IMAGENS_LANDSAT_8_2017/Processadas/003_068l8_oli_002065_20140803_b654_fuseo_sirgas2000_utm.tiff -
How to save form without validation
I want that my users can fill a post form partially, save as draft and then edit, finish and publish it. So the draft can have some required (text) fields empty. However I want the fields secure to store in the database (so, no special character, etc). What's the best (or a good way) way to do this? I think these solutions: 1) make two different models, one with required=False fields or 2) fill the empty text field with a temporary string ('draft'), then delete it e redraw as needed while edit, publish, save the draft. Or 3) deactivate the validation (novalidation, I'm not sure this works). or what else? I'm looking to the second way because the first I think will give me problems to manage two models and the third maybe is not secure. PS I'm using ajax to call the views. -
use .liquid template as django template
I am making an e-commerce site with Django oscar. I bought a template but later found that it was a template for Shopify and all the files were in a .liquid format which is a ruby on rails templating library. Is there any way to convert liquid templates into Django templates? If not, is there any alternative? I changed the format to .html and used it as Django template but the Tags didn't load correctly. I tried this answer but it will take a lot of time if I just keep on changing everything. I also saw this library in GitHub but could not figure out how to use it. Any suggestion is highly appreciated. I have already spent money on this this template and don't want to waste more time and money on another template. Thanks in advance. -
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.