Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django translating MySQL query to Django Query
How can i get the equivalent of this MySQL script in Django views? The depart_city, arrive_city, and travel_date will be inputed by the user. Here is my Models class Driver(models.Model): first_name = models.CharField(max_length=30, null=True, blank=False) last_name = models.CharField(max_length=30, null=True, blank=False) class Schedule(models.Model): depart_time = models.TimeField() arrive_time = models.TimeField() class TravelDate(models.Model): start_date = models.DateField(null = True) interval = models.IntegerField(null = True) class Route(models.Model): depart_city = models.CharField(max_length=50, null=True, blank=False) arrive_city = models.CharField(max_length=50, null=True, blank=False) driver = models.ForeignKey(Driver) schedule = models.ForeignKey(Schedule) traveldate = models.ForeignKey(TravelDate) Here is my MySQL script. This works when i run it on MySQL workbench but I'm not sure how to translate this to Django Query SELECT busapp_route.depart_city, busapp_route.arrive_city, busapp_driver.first_name, busapp_schedule.depart_time FROM (((busapp_route INNER JOIN busapp_driver ON busapp_route.driver_id = busapp_driver.id) INNER JOIN busapp_schedule ON busapp_route.schedule_id = busapp_schedule.id) INNER JOIN busapp_traveldate ON busapp_route.traveldate_id = busapp_traveldate.id) WHERE busapp_route.depart_city='Tropoje' AND busapp_route.arrive_city='Tirane' AND (DATEDIFF('2017-11-26', busapp_traveldate.start_date) % busapp_traveldate.interval = 0); -
Django STATIC files does not work in Develop mode
Django STATIC files does not work in Develop mode. I tried in many ways, but I did not succeed. Could someone tell me where I'm wrong? Thank you very much for your attention. STATIC_URL = '/static/' STATIC_ROOT = "/Users/user/Projects/RMA/static/" STATICFILES_DIRS = ( os.path.join(BASE_DIR, '..', 'static'), ) .... 'django.contrib.staticfiles', routes urlpatterns = [ url(r'^$', views.index, name='index') ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) View def index(request): return render(request, 'base.html', {'question': 'ads'}) template {% load static %} <link href="{% static 'site/bower_components/select2/dist/css/select2.min.css' %}" rel="stylesheet"> -
Searching in multiple fields respecting the row order
I have a model like the following: class Foo(models.Model): fruit = models.CharField(max_length=10) stuff = models.CharField(max_length=10) color = models.CharField(max_length=10) count = models.IntegerField() exists = models.BooleanField() class Meta: unique_together = (('fruit', 'stuff', 'color'), ) It is populated with some data: fruit stuff color count exists Apple Table Blue 4 True Pear Book Red 4 False Pear Phone Green 3 False Apple Phone Blue 7 True Pear Table Green 3 True I need to merge/join this with a collection (not a queryset): [('Apple', 'Table', 'Blue'), ('Pear', 'Phone', 'Green')] So basically rows 0 and 2 should return when I search this model with this list of tuples. Q seemed promising with a little modification on the list: from django.db.models import Q Foo.objects.filter( Q(fruit__in=['Apple', 'Pear']), Q(stuff__in=['Table', 'Phone']), Q(color__in=['Blue', 'Green']) ) but this returns rows 1 and 3 as well. Currently my workaround is to read Foo.objects.all() into a DataFrame and do a merge with the list of tuples and get the ID's to pass to Foo.objects.filter(). I also tried iterating over the list and calling Foo.object.get() on each tuple but it is very slow. I feel like there should be a clean, efficient way of doing this. Is there? Note: The list of tuples does … -
migrating from one-to-many to many-to-many: interm. table does not have UNIQUE constraint
TL;DR; changing completely different field in the same migration as introducing many-to-many field leads intermediate table does not have UNIQUE constraint. Root challenge. I need to replace one-to-many relation with many-to-many. Step-by-step. Assume initially I have: class Test(models.Model): pass class Test2(models.Model): title = models.CharField(max_length=100) test = models.ForeignKey(Test) After changing test2.test into ManyToMany class Test(models.Model): pass class Test2(models.Model): title = models.CharField(max_length=100) tests = models.ManyToManyField(Test) and running makemigrations/migrate I'm getting new table test2_test with UNIQUE constraint for pair test_id + test2_id and that's definitely I expect. But once I wanted to update another field also: class Test(models.Model): pass class Test2(models.Model): title = models.TextField() tests = models.ManyToManyField(Test) And test2_test does not get UNIQUE INDEX for test_id + test2_id. As a workaround I've finally moved changes for different field into separated migration. Question Does anybody know reason for a such behavior? -
Sending a file via POST using Django using Javascript instead of HTML Form
I have a PDF file saved in a variable 'report.' I am using Django and want to pass it to a function in my views.py file using POST -- @xframe_options_exempt @csrf_exempt def process_report(request): if request.method == 'POST' report_file = request.FILES['docfile'] .... return response How can I send a ajax POST request with this file? The filetype is a PDF. I was using an HTML form to do this before, but I wanted to style the form upload using javascript. I tried styling the button using javascript (changing colors and text depending on file type uploaded), but the file was no longer being able to be passed through the POST request. Now I just have the file saved in a javascript variable, and am trying to just pass it via POST without using form. I understand it's impossible to prepopulate a form with a file. My old code: <form id="boring" action="{% url "process_report" %}" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.non_field_errors }} {{ form.docfile.label_tag }} {{ form.docfile.help_text } {{ form.docfile.errors }} {{ form.docfile }} </form> What I have been trying to do with ajax var formdata = new FormData(report); $.ajax({ url: 'process_report', type: 'POST', processData: false, contentType: false, dataType : 'application/pdf', … -
Django throwing isoFormat error when receiving string for model DateField
I am trying to utilize a DateField in my model, but when I send it an iso formatted string from my javascript form ('2017-10-17') I get an error on the backend stating: AttributeError at /comment/ 'str' object has no attribute 'isoformat' It looks like something far down in django/python is treating this like a python datetime object. I can get around this by converting my string into a python datetime object in the corresponding serializer, but that seems like it should be unnecessary. Here is my code # Inside comment/models.py submission_date = models.DateField(blank=True, default=datetime.date.today) # Work around inside comment/serializers.py if 'submission_date' in validated_data: validated_data['submission_date'] = datetime.strptime(validated_data['submission_date'], "%Y-%m-%d") I'm sorta new to Python and Django, but I find it hard to believe that I'd have to force the conversion of an incoming string (the only way to pass data from the front end) into a python datetime object for every DateField that may come up. This also seems especially odd as all the documentation around the DateField uses the same iso formatted strings that I am using. Am I doing something silly? Are my assumptions incorrect about how this should work? -
django 'ModelFormOptions' object has no attribute 'virtual_fields'
models.py class Products(models.Model): company = models.ForeignKey(Companys) name = models.CharField(unique = True, max_length = 50) description = models.CharField(unique = True, max_length = 500) price = models.PositiveIntegerField() in_stock = models.BooleanField(default = True) crated = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name forms.py class ProductForm(forms.ModelForm): class Meta: model = Companys fields = '__all__' name = forms.CharField() description = forms.CharField(widget = forms.Textarea, ) company = forms.ModelChoiceField(queryset = Companys.objects.all(), label = 'Company') in_stock = forms.BooleanField(initial = True) price = forms.ImageField() views.py class ProductCreate(CreateView, ProductEditMixin): model = Products template_name = 'store/product_add.html' fields = '__all__' Please help me. Without forms code work. But with forms i have AttributeError: 'ModelFormOptions' object has no attribute 'virtual_fields' error -
I need consultation and possibly a solution for the matter of serializing a complex object in django to json
So as I've started saying in the title, my problem is that I have a complex object that I've constructed specificaly for a project but it's in python and I want to serialize and convert it to JSON format and receive it on the client side JS. Now my question is, what is the best approach to such a problem? should I in fact not be doing any work on the backend of django and actually sending raw lists and objects to the JS client side and there build the complex object, or is this aproach sensibile and I should just deal with the problem of serializing this complex object and deliver it to the client JS? I've added my code so that you can understand the full context of what I'm trying to acheive : def get_foundation_estimated_value(found): if found.sumCalls: return found.lastAcc.sum / found.sumCalls else: return 0 def add_to_foundation_batzir_year(found): found.batzir = 0 if found.actions['calls'] and found.actions['calls'][0]: found.batzir = found.actions['calls'][0].date.year def update_kibbutz_total_actions_sums(found, kibbutzim_totals): kibbutzim_totals[found.kibbutz.name]['callTotal'] += found.sumCalls kibbutzim_totals[found.kibbutz.name]['distTotal'] += found.sumDists if found.lastAcc: kibbutzim_totals[found.kibbutz.name]['accsTotal'] += found.lastAcc.sum def add_actions_to_foundation(found): capital_calls = CapitalCall.objects.filter( foundation_id=found.id).all().order_by('date') capital_accounts = CapitalAccount.objects.filter( foundation_id=found.id).all().order_by('date') distributions = Distribution.objects.filter( foundation_id=found.id).all().order_by('date') found.actions = { 'calls': capital_calls, 'accs': capital_accounts, 'dists': distributions } def add_to_foundation_sums_of_actions(found): # … -
I have this kind of error python. reset_password
I wanted to make a reset password on Django but this problem came. I tried to rename it but it does not work. The problem comes: NoReverseMatch at /password_reset/ Reverse for 'password_reset_done' not found. 'password_reset_done' is not a valid view function or pattern name. **URL.PY** from django.conf.urls import url from . import views from django.contrib.auth import views as auth_views from grooveapp import views as core_views from django.contrib.auth.views import ( password_reset, password_reset_done, # password_reset_confirm, # password_reset_complete ) urlpatterns = [ url(r'^login/$', auth_views.login, name='login'), url(r'^logout/$', auth_views.logout, {'next_page': 'grooveapp:login'}, name='logout'), url(r'^login/$', auth_views.login, name='login'), # url(r'^lobby/$', views.lobby, name='lobby'), # url(r'^lobby/(?P<name>[0-9]{1})/$', views.lobby, name='lobby'), url(r'^lobby/(?P<name>[0-9]+)/$', views.lobby, name='lobby'), url(r'^profile/$', views.profile, name='profile'), url(r'^profile/edit/$', views.edit_profile, name='edit_profile'), url(r'^change-password/$', views.change_password, name='change_password'), url(r'^infostories/$', views.infostories, name='infostories'), url(r'^story/$', views.story, name='story'), url(r'^makechat/$', views.makechat, name='makechat'), url(r'^api/lobby_messages$', views.get_messages), url(r'^signup/$', core_views.signup, name='signup'), url(r'^password_reset/$', password_reset, name='password_reset'), url(r'^password_reset/done/$', password_reset_done, name='password_reset_done'), ] -
How to pass a array to form field
i want to attach an array to input field and post. i cant seem to store the value of the array to a form field. Here is my code plz help $('#field_id').append(array) var values = form.serialize() $.post(url,values ) } -
Python on my website
I know this has been asked before but I don't understand any of the answers I have read. I taught myself HTML and CSS and created a website. I am now teaching myself Python and, probably like everyone else, have made lots of little programs like choose-your-own-adventure style text based programs using if statements and stuff ("Press 1 if you want to take the left path..." etc). Anyway, I want it so that when someone visits my site and sees a list of my python programs, they can click on one - this then opens a box or a new page and they can play the game, exactly as you would if you ran the program from IDLE by pressing F5. I have NO IDEA about frameworks and CGI and apache and cgi-bins or anything else. Literally ZERO idea. I don't understand any of these terms. They seem incredibly complex. I wouldn't mind so much but everyone's answer is completely different from everyone else's. All I know is how to create a website using HTML and CSS and how to write simple dumb python programs. Finally, if there is NO simple way of doing this, my last question is WHY … -
How to update database (postgresql) of a deployed django-app, after modifying a model?
I'm having trouble with my Django-app that's been deployed. It was working fine but I had to do a minor modification (augmented the max_length) of a Charfield of some model. I did migrations and everything was working fine in the local version. Then I commited the changes without a problem and the mentioned field of the web version now accepts more characters, as expected, but whenever I click the save button a Server Error rises. I assume I have to do some kind of migration/DB update for the web version but I don't seem to find how. (I'm working with Django 1.11, postgresql 9.6, and DigitalOcean). -
django-cachalot keyError 'ENGINE'
I've pulled a Django project to my local environment, set up a virtual environment and installed the requirements.txt, however when I try to run the local server I get the following error. File "/Users/ianmakgill/git/openoppscom/venv/lib/python3.6/site-packages/cachalot/settings.py", line 76, in <setcomp> if setting['ENGINE'] in SUPPORTED_DATABASE_ENGINES} KeyError: 'ENGINE' The developer says that his version runs fine using the same set up and same hardware - macosx. We're using Django (1.9.4) and django-cachalot (1.5.0) -
Docker crashing when Tensorflow starts in Django
I currently have it working on local in the same docker container, but on my Digital Ocean droplet, I cannot get it working. I believe the error is occurring here: https://github.com/jrobchin/lyterai/blob/master/app/hub/demo/keras_demo.py from keras import backend as K from keras.preprocessing import image from keras.applications.imagenet_utils import preprocess_input from keras.models import model_from_json K.set_image_dim_ordering('tf') K.set_image_data_format('channels_last') def load_model(layers, weights): # Load model architecture and parameters model_json = open(layers, 'r') loaded_model_json = model_json.read() model_json.close() model = model_from_json(loaded_model_json) # Load model weights model.load_weights(weights) return model def predict(image, layers, weights, classes_str): """ Takes a path to an image and returns the predicted class and confidence score. """ classes = classes_str.split(",") K.clear_session() # Make and parse the prediction model = load_model(layers, weights) output = model.predict(image) prediction_index = output[0].argmax() confidence = float(output[0][prediction_index]) # prediction = {'class': classes[prediction_index], 'confidence': confidence} prediction = classes[prediction_index] K.clear_session() return prediction, confidence I am running Tensorflow within a Django server in Docker and when I try to make a prediction I get this output: python_1 | 2017-11-24 20:18:24.198764: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations. python_1 | 2017-11-24 20:18:24.200163: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 … -
Django CSRF in a cluster
Can someone example to me how CSRF works in the cluster setup? I have a kubernetes cluster hosting a django website, and I'm having some occasional issues with 403 errors. I have multiple instances of the site load balanced in kubernetes. How does CSRF work when a POST is sent from 1 instance and handled by another? Does CSRF site work if the docker images are updated during the time the form is being filled out? Thanks! -
nodemcu post request to django site with csrf token
How to send a post request from nodemcu to django server with csrf token . -
Dropdown menu is only available when the parent is active
I'm trying to create a dropdown menu which presents available blog posts. I noticed that, in order for the drop down arrow to appear, the "blog" node has to be selected. If I select any other node, then the arrow doesn't appear. Home Page - no drop down available Dropdown appears only when the blogs tab is active I'd like this to be laid out in a way which would allow users to open the drop down menu without having to go through the "blog" page. For example: a user could be on the home page, click on the dropdown, remain on the homepage, and then go straight to "blog 1". This is the code that I'm currently working with: from menus.base import NavigationNode from menus.menu_pool import menu_pool from django.utils.translation import ugettext_lazy as _ from cms.menu_bases import CMSAttachMenu from cms.models import Title class TestMenu(CMSAttachMenu): name = _("test menu") def get_nodes(self, request): nodes = [] n = NavigationNode(_('blog 1'), "/", 1) n2 = NavigationNode(_('blog 2'), "/bye/", 2) n3 = NavigationNode(_('blog 3'), "/hello/", 3) n4 = NavigationNode(_('blog 4'), "/hello/world/", 4) nodes.append(n) nodes.append(n2) nodes.append(n3) nodes.append(n4) return nodes menu_pool.register_menu(TestMenu) -
How to escape a " in Django?
For a schoolproject we are making a webshop. We use Django 1.11 and HTML 4. We have divided the tasks, and after some work the webshop is almost complete. However, there is still a major error in the searchbar. When someone enters text before an apostrophe (a", "a", "a"", etc.) the website crashes. The error message we get is ord() expected a character, but string of length 0 found And it is used in this function while i <= len(query): if query == "" or len(query) == 0: query = "No query found" # Remove unwanted characters. if 33 <= ord(query[i-1:i]) <= 47: query = queryVerbeterFunctie(query[:i-1] + query[i:]) print("Removed") if 58 <= ord(query[i-1:i]) <= 64: query = queryVerbeterFunctie(query[:i-1] + query[i:]) print("Removed") if 91 <= ord(query[i-1:i]) <= 96: query = queryVerbeterFunctie(query[:i-1] + query[i:]) print("Removed") if 122 <= ord(query[i-1:i]): query = queryVerbeterFunctie(query[:i-1] + query[i:]) print("Removed") We have looked online for a while but as of yet have found no appealing options other than - update the site to HTML5, although this would require rewriting most HTML pages / functions - solve the problem with Javascript. We're not sure if this will work though, since none of us have experience with it. What … -
Problems with cache queryset django rest framework
Good day to all, I have been trying to make this query be consulted every time the REST service is used in the API, but only the first time it obtains the data from the DB and when the data changes the service only brings the cache stored data My Code: urls.py router.register(r'cron-log',views.CronLogViewSet, base_name='cron-log') Views.py - my viewset class class CronLogViewSet(viewsets.ModelViewSet): queryset = Cron_log.objects.all().order_by('-id').values()[:5:1] serializer_class = CronLogSerializer Models.py my model class from Cron_log class Cron_log(models.Model): log = models.CharField(max_length=40) time = models.CharField(max_length=40) def as_dict(self): return {'log':self.log,'time':self.time} Serializer.py serializer class class CronLogSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Cron_log fields = ('log','time') I tried with a for before the queryset, with list(query_set) but the issue still there thanks! for your help -
How to get Qustion from answer object in django?
I have two class Question and Answer in models. Both are connected to user by ForeignKey. In a template I want to print all answer of the looged in user. Which is happening easily. But my problem is I want to get question corresponding to the answer. What will be the query to get the question? models, template and views given below-- class Question(models.Model): title = models.CharField(max_length=200, blank=True, null=True) description = models.TextField() pub_date = models.DateTimeField() user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title class Answer(models.Model): answer_text = models.TextField() questions = models.ForeignKey(Question, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) pub_date = models.DateTimeField() def __str__(self): return self.answer_text views: def answered_by_me(request, user_id): user = User.objects.get(pk=user_id) answers = user.answer_set.all() questions = user.question_set.all() context = {'answers': answers, 'questions': questions, 'user_id': user_id} return render(request, template_name='ans/answered_by_me.html', context=context) template: {% block body %} {{ answers }} {% if answers %} <ul> {% for answer in answers %} <li> {{ answer }}</li> {% endfor %} </ul> {% endif %} {% endblock %} -
In Django admin, the "view on site" link has "https://" in it twice, making the link unuseable
I have a model, which has a get_absolute_url method defined as follow : def get_absolute_url(self): return reverse('shop__restaurant_listing', kwargs={'slug': self.slug, }) The reverse portion correctly returns /varieties/grenaille. However, in the Django admin, when I view an instance of the model, the "View on site" link is formatted with "https://" twice. So the link is something like https://https//www.potato.com/varieties/grenaille/. I had a look at the Django code, and found this line in django.contrib.admin.templates.admin.change_form.html : {% if has_absolute_url %} <li> <a href="{{ absolute_url }}" class="viewsitelink"> {% trans "View on site" %} </a> </li> {% endif %} I have almost no customization here, so is there something wrong with how I reverse the URL ? What is causing the double HTTPS ? -
Sending emails with celery in Django project
I can't understand how to send emails with Celery to real people. May be some one can help me? I can send mail to console with EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' . But how to configure settings.py file to send email for example to my gmail? If you have djproject with celery on github I want to see it to understand what i have to do. My github https://github.com/Loctarogar/Django-by-Example -
Adding any number of items to wagtail setting
In wagtail I'm attempting to create a setting, per site, whihc will allow me to define which specific urls I want to display in a footer / navbar. For being able to add any number all of the tuts I see define a relation through a foreign key to a page but since this inherits from BaseSettings I'm not sure how to accomplish this same effect. There's an example in the docs but this won't work since there is no page to associate. Here's my setup which doesn't work due to the foreign key to the NavbarSettings: class LinkFields(models.Model): link_external = models.URLField("External link", blank=True) link_page = models.ForeignKey( 'wagtailcore.Page', null=True, blank=True, related_name='+' ) link_document = models.ForeignKey( 'wagtaildocs.Document', null=True, blank=True, related_name='+' ) @property def link(self): if self.link_page: return self.link_page.url elif self.link_document: return self.link_document.url else: return self.link_external panels = [ FieldPanel('link_external'), PageChooserPanel('link_page'), DocumentChooserPanel('link_document'), ] class Meta: abstract = True class RelatedLink(LinkFields): title = models.CharField(max_length=255, help_text="Link title") panels = [ FieldPanel('title'), MultiFieldPanel(LinkFields.panels, "Link"), ] class Meta: abstract = True @register_setting(icon='link') class NavbarSettings(BaseSetting): pass class NavbarRelatedLink(RelatedLink): setting = models.ForeignKey( NavbarSettings, related_name='related_navbar_links', ) How can I acheive being able to add as many links as I want to the setting in wagtail? I can set the … -
How to draw a map at zip code level in Django?
I have a database with three columns - country, zip code, and some value that I want to display in that zip code. We can avoid the country part since it's just the US for now. I have tried looking into Highcharts, leaflets but can't seem to find anything reasonable with at zip code. Can you please share any useful link/documentation to handle this? -
How can I upload an image file in Swagger generated service?
How can I define in my rest framework API that a model receives an ImageField attribute and Swagger recognizes it when I generate the client services (typescript-angular)? I have this model: class User(models.Model): avatar = models.ImageField(upload_to='avatars') name = models.CharField(max_length=20) this serializer: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = '__all__' this viewset: class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer