Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Heroku and Django, database resets when heroku restarts the site
After 30mins of not being used Heroju resets my django site, however when the site is reset the database/models controlled and changed in the admin page are reset back to when the site was first uploaded. How do i stop this and make changes made in admin mode permanently to the site? thank you. -
employee multiple role relationship
I have tables of Employee and Roles. In Roles model I'm storing manager details, there is manager hierarchy like Manager, AGM, DGM, and MD, I have to design my schema such a way that each employee has one manager and 5 managers will be reporting to one AGM and 5 AGM to one DGM. How to design this schema? Any help would be appreciable. Thanx in advance. -
Django RF: AssertionError: Relational field must provide a `queryset` argument, override `get_queryset`, or set read_only=`True`
In my models there is a Meeting model with a GenericForeignKey which can be either DailyMeeting or WeeklyMeeting like: class Meeting(models.Model): # More fields above content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() recurring_meeting = GenericForeignKey('content_type', 'object_id') class DailyMeeting(models.Model): meeting = GenericRelation(Meeting) # more fields class WeeklyMeeting(models.Model): meeting = GenericRelation(Meeting) # more fields As described in the documentation, I created a custom field in my serializers.py: class RecurringMeetingRelatedField(serializers.RelatedField): def to_representation(self, value): if isinstance(value, DailyMeeting): serializer = DailyMeetingSerializer(value) elif isinstance(value, WeeklyMeeting): serializer = WeeklyMeetingSerializer(value) else: raise Exception('Unexpected type of tagged object') return serializer.data class MeetingSerializer(serializers.ModelSerializer): recurring_meeting = RecurringMeetingRelatedField() class Meta: model = Meeting fields = '__all__' In the views.py I am overriding the create method and I am passing a DailyMeeting object. def create(self, request, *args, **kwargs): data = request.data d = DailyMeeting.objects.create(...) data['recurring_meeting'] = d serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) But the problem is that I am getting the following error: AssertionError: Relational field must provide a queryset argument, override get_queryset, or set read_only=True. Why does the Relational field has to be read_only? If I set it as read_only then it is not passed in the data in the serializer. How can I pass the DailyMeeting object in the serializer and print … -
django email sending after template js if function
I tried to send a email using django after the javascript if statement came true in template. when I refresh the web page it need to be send a email only that if statement is true. How I can achieve this? please help -
Add uuid field in django Existing User model?
I am using Django Rest framework for my application. I almost implemented registration and login process using django User Model without customizing it now i want to add a uuid field in it. Is there any way we can just add uuid field and other process remains same? -
Django: How to use apps installed with pip
I want to make use of Django's modularity and integrate some external apps that I installed using pip. However, I am encountering difficulties in understanding how can I integrate and use or extend their urls, views, models. There isn't much on this subject, I can't figure why. Let's take the example of changuito-cart: Do i create a folder named "changuito" in root and create urls/views in here, or should I just create a new app named like it? In settings.py I added "changuito" to my installed apps list and I got "no module named 'changuito'" error. How do I add it correctly? What are the basic steps required to integrate it? -
Multiple table filtering in Django DRF serializer or view
What I am trying to do is retrieve records that are relevant to the current user. I am using DRF JWT so the user_id is being stored in sessionStorage along with the JWT token. As I understand it, because JWT is being used, session authentication is not, so such things like request.user do not work. At least I could never get it working and was just told to store the user_id in sessionStorage with the JWT token. As such, if I want to retrieve records that are relevant to the current user, sessionStorage.getItem('user_id') needs to be passed to the API with POST. GET won't work since 1) request.user doesn't work and 2) can't send sessionStorage.getItem('user_id'). So here are the models I am working with that I need to filter on with some example data: -- Products table prod_id | prod_name | active ---------------------------- 3 | Widget1 | 0 10 | Widget2 | 1 11 | Widget3 | 1 -- Users table user_id | username ------------------ 10011 | joesmith -- User_to_Products table user_id | prod_id ----------------- 10011 | 3 10011 | 11 So what should be happening is the React FE sends the sessionStorage.getItem('user_id') to the DRF BE via POST, the … -
Django query - count up to 10 votes from one IP
let's say I have a simple voting form with different answers. the people can vote multiple times from one IP. I can easily find how many votes a given answer has got - a.vote_set.all().count() (no limit of votes from 1 IP) I can also find out how many votes there were, given the limit 1 vote from 1 IP - a.vote_set.all().values('ip').distinct().count() (limit of votes from one IP =1) How to get the sum of votes for a given answer provided that I want count up to 10 votes from 1 IP (limit=10)? -
How to store timezones efficiently in Django model?
I have a timezone field in my Django model : import pytz ALL_TIMEZONES = sorted((item, item) for item in pytz.all_timezones) ... class Snippet(models.Model): tz = models.CharField(choices=ALL_TIMEZONES,max_length=32) I'm a little bit concerned about the space occupied by the tz field because I expect to have many many snippets in the future. Longest timezone is 32 characters long but there are only 593 timezones so 2 bytes would be sufficient to store the timezone. Is there a better way to store/define my tz field? Of course I could use my own coding scheme but before I want to make sure there is no other solution. -
django inlineformset_factory error_messages not working
I use a subform and validation works fine. But I want to override the error_messages, which for some reason doesn't work when using inlineformset_factory. What I want to achieve is overriding the required error message of the formset. The django documentation says: error_messages is a dictionary of model field names mapped to a dictionary of error messages. For that reason in inlineformset_factory I passed a dictionary as following: forms.py: from django import forms from .models import Product from brand.models import Brand from masterdata.models import Masterdata from django.forms.models import inlineformset_factory Master_Inlineformset = inlineformset_factory( Product, Masterdata, fields=('title', 'description', 'mpn', 'brand_id', 'categories'), extra=1, can_delete=False, labels={'title': 'Title', 'description': 'Description', 'mpn': 'Articlenumber', 'brand_id': 'Brand', 'categories': 'Categories'}, error_messages = { 'brand_id': { 'required': 'some custom required message', }, } ) You can also have a look on the remaining files: views.py: class ProductUpdateView(LoginRequiredMixin, UpdateView): form_class = ProductCreateForm template_name = "artikel/product_form.html" def get_queryset(self): queryset = Product.objects.filter(pk=self.kwargs.get("pk")) return queryset def get_context_data(self, *args, **kwargs): context = super(ProductUpdateView, self).get_context_data(*args, **kwargs) if self.request.POST: formset = Master_Inlineformset(self.request.POST, self.request.FILES, instance=self.object) else: formset = Master_Inlineformset(instance=self.object) context["formset"] = formset return context def form_valid(self, form, **kwargs): self.object = form.save() context = self.get_context_data(**kwargs) formset = context["formset"] if formset.is_valid(): formset.save() else: return render(self.request, self.template_name, {"form": self.form_class(self.request.POST), "formset": formset,}) …