Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Connecting Raspberry Pi to Django Web App
I currently have a django web app which is deployed at: http://ltdiadams.pythonanywhere.com/, the home view consists of a bunch of graphs which are made from a csv (stored.csv) included in the project folder. Here is a link to the github for the files: https://github.com/ltdiadams/Garden-Bot-3000. The csv file 'stored.csv' is created using another python script on my Raspberry Pi which reads in values for moisture, light, temperature, etc. from sensors and outputs them into columns of a csv. Now that I have the functioning web app which reads in from a csv I gave it, I'm having trouble getting it to connect to the Pi. That is, how can I make it so that I can go to this website on my Pi, have the Pi output the csv file and have this website read and make the graphs from that csv rather than the one that's included in the django folder? The two csv files are exactly the same, just one has set values I used to get it up and running, and the other which is outputted on the Pi updates constantly as the sensors read in data, I would like for the web app to read in this … -
How to do django-reversion with ManyToMany fields?
I am using django-reversion, it works well on an entity and simples relationships but when the model class have ManyToManyField, o reversion not work. I saw about use `reversion.register(CodeList, follow=["fieldManyToMany"])` but I am using the declarative form `@reversion.register() class MyModel(models.Model):` And don't know how and where to use reversion.register(CodeList, follow=["fieldManyToMany"]) -
Change text or image of an html page from Django admin page?
Is it possible in Django to change a paragraph of index page or to change an image of the index page as an admin from admin page? -
Dynamic Django dynamic initial input with phone number
Looking for some assistance in adding a form field where the phone formatting is done actually in the input itself. Where the ( ) and - automatically fit around the numbers as are they're typed. Any suggestions? -
Django ManyToMany field filter
So I have this system where my Post object has a ManyToMany field and it's called Saves. So like for example on Reddit you can save a post. So I got it working and users can save posts, and it adds them to the ManyToMany field. However, I want to filter out these posts and only show the posts where said user is in the ManyToMany field. Here is my models.py class Post(models.Model): author = models.ForeignKey(User,related_name='posts',on_delete=models.CASCADE) saves = models.ManyToManyField(User,blank=True,related_name='post_saves') I have the saves field connected to the User model Django provides. And here is my views.py class PostSaveRedirect(RedirectView): def get_redirect_url(self,*args,**kwargs): pk = self.kwargs.get("pk") slug = self.kwargs.get("slug") obj = get_object_or_404(Post,pk=pk,slug=slug) url_ = obj.get_absolute_url() user = self.request.user if user.is_authenticated: if user in obj.saves.all(): obj.saves.remove(user) else: obj.saves.add(user) return url_ So this is all working fine, it adds the user to the ManyToMany field, but now I want to know how I can filter out posts and only display ones where the user is in the ManyToMany field. Here is my saved posts view. class PostSaveListView(ListView): model = Post template_name = 'mainapp/post_saved.html' paginate_by = 10 queryset = models.Post.objects.all() def get(self,request): posts = Post.objects.all() return render(request, self.template_name) def get_queryset(self): return Post.objects.filter().order_by('-published_date') So with Post.objects.all(), how … -
Cannot submit a form in django template from javascript
I have the following django template. I am submitting the form through javascript, because ultimately I want that the submit button will be hidden, and the form will autosubmit when the input text changes (i want it to autosubmit when a "." is the last character in the text): <form action="/rewrite/" method="post" id="sentence"> {% csrf_token %} <textarea name="inp" id="ans">abc</textarea> <input type="button" value="Submit" name="new_stop" onclick="submitForm()" id="but"> </form> <script> function submitForm() { form.submit(); } </script> Upon clicking the button I get a Forbidden (403) CSRF verification failed. Request aborted. error -
Elasticsearch 5.x Fails to Start
I have been trying to install Elasticsearch, which, for version 7.x seemed easy, whereas for version 5.x is a pain in the neck. The whole ordeal exists because there is a slew of compatibility requirements between the Elasticseach, Django Haystack, Django CMS and other things. If someone has a nice table or a way to wrap their head around that, I'd be happy to hear it. As to the actual question, after installing ES 5.x, I cannot seem to get it working. user@user-desktop:~/sites/project-web/project$ sudo systemctl restart elasticsearch user@user-desktop:~/sites/project-web/project$ curl -X GET localhost:9200 curl: (7) Failed to connect to localhost port 9200: Connection refused user@user-desktop:~/sites/project-web/project$ Entities that are uncommented in /etc/elasticsearch/elasticsearch.yml # ======================== Elasticsearch Configuration ========================= # # NOTE: Elasticsearch comes with reasonable defaults for most settings. # Before you set out to tweak and tune the configuration, make sure you # understand what are you trying to accomplish and the consequences. # # The primary way of configuring a node is via this file. This template lists # the most important settings you may want to configure for a production cluster. # # Please consult the documentation for further information on configuration options: # https://www.elastic.co/guide/en/elasticsearch/reference/index.html # # ---------------------------------- Cluster ----------------------------------- … -
Only displaying red errors in pylint-django VS Code
In Visual Studio Code, when working on a Django project, I made the decision to use the pylint-django package for linting. Currently, In my python files, Numerous "warnings" occur in the colour blue. This is not what I want. In my python files, I don't want any blue or yellow warnings, I only want any red or "major" errors to display within my files. Does anybody know how to accomplish this within Visual Studio Code? Also here is my current settings.json for VS code: { "window.zoomLevel": 2, "python.linting.pylintArgs": [ "--load-plugins=pylint_django" ] } -
Django many to one relationship, foreign key as text input
I have 2 databases, Book and Comment (one book could have many comments, but each comment only refers to one book). Each database has an HTML form for the user to input book data or comment. ISBN is the primary key for the Book database and foreign key for the Comment database. In both html form, user will use text input to input ISBN. How can I revise my html form and code below so that such many to one relationship will be created? models.py class Book(models.Model): ISBN = models.BigIntegerField(primary_key=True) Chinese_Book_Name = models.CharField(max_length=200) English_Book_Name = models.CharField(max_length=200, blank = True) Author_Name = models.CharField(max_length=100) class Comment(models.Model): ISBN = models.ForeignKey(Book, on_delete = models.CASCADE) age = models.CharField(max_length=10) score = models.IntegerField() comment = models.TextField() topic = models.CharField(max_length=100, blank = True) name = models.CharField(max_length=50) contact = models.CharField(max_length=200, blank = True) Views.py def saveBook(request): ISBN = request.POST['ISBN'] Chinese_Book_Name = request.POST['chinese name'] English_Book_Name = request.POST['english name'] Author_Name = request.POST['author name'] book = Book(ISBN = ISBN, Chinese_Book_Name = Chinese_Book_Name, English_Book_Name = English_Book_Name, Author_Name = Author_Name) book.save() return redirect('/input/addComment') def saveComment(request): ISBN = request.POST['ISBN'] age = request.POST['age'] score = request.POST['score'] topic = request.POST['topic'] name = request.POST['name'] contact = request.POST['contact'] comment = Comment(ISBN=ISBN, age = age, score = score, topic = … -
Else dont work in django, i dont know how to solve this
Request Method: GET Request URL: http://127.0.0.1:8000/articles/ Django Version: 2.2.7 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 12: 'else', expected 'endblock'. Did you forget to register or load this tag? {% extends 'base.html' %} {% block title %}Ultemele statii{% endblock %} {% block content %} {% if latest_articles_list % } {% for a in latest_articles_list %} <a href="#">{{a.article_title}}</a> {% endfor %} {% else %} statii ne naidena ))= {% endif %} {% endblock %} Code don't work -
Django Import-Export Overwriting / Updating non-unique CharField
I am trying to import xls files that in some cases have missing data. Rather than manually changing the necessary fields before import, I'd ideally like Django to account for them. In this case, while each product should have a unique barcode, some products in this xls file have 'N/A' instead. For some reason Django is interpreting these products as the same, and updates them instead of creating new. This problem does not occur for the other CharFields like Format or Cost; if all entries have a Format of 'LP' the import proceeds without error. Any ideas what is causing this? Bonus Question: Any way to chop off the time from the Release Date? I believe this is all the relevant code. resources.py class ArtistWidget(widgets.ForeignKeyWidget): def clean(self, value, row=None, *arg, **kwargs): return self.model.objects.get_or_create(artist=value)[0] if value else None class LabelWidget(widgets.ForeignKeyWidget): def clean(self, value, row=None, *args, **kwargs): return self.model.objects.get_or_create(label=value)[0] if value else None class ProductResource(resources.ModelResource): artist = fields.Field(column_name='artist', attribute='artist', widget=ArtistWidget(Artist, 'artist')) label = fields.Field(column_name='label', attribute='label', widget=LabelWidget(Label, 'label')) prod_format = fields.Field(column_name='format', attribute='prod_format') release_date = fields.Field( column_name='release date', attribute='release_date') cat_number = fields.Field(column_name='cat#', attribute="cat_number") class Meta: model = Product import_id_fields = ('barcode',) fields = ('artist', 'title', 'cat_number', 'prod_format', 'label', 'barcode', 'cost', 'release_date',) skip_unchanged = True … -
Wagtail: How to verify if a user can access a page in the template
I am creating a personal website using Django with Wagtail, in which users belonging to different groups can access certain pages. For example, the family group can see my holiday photos, while the co-workers group can see some internal documents. Setting up permissions is very straightforward to set up through the admin. However, I would like to show a lock next to the link to forbidden pages. This will make it very clear to the user which links can be followed and which ones can't. Is there any way to verify whether the current user has access to a given page? -
Jquery not returning the unique values
I have created one viewall page for all the products in django and the page is created dynamically using the context object data. I have created one hidden input type which holds the value of unique id of products. When i click on the product i wish to fetch the value of hidden input type. But it is returning the value of first product only i.e the first object in the context. below is the code. {% for album in list1 %} <div class="col-lg-3" id="div1"> <div class="card" style="width: 20rem;"> <input type="hidden" class="custId" value={{ album.id }}> {{ album.product_name }} Category : {{ album.product_category }} Price : {{album.id }} $('.k').click(function(){ var a = $('.custId').val(); alert(a) console.log(a) $('#myModal').modal('show'); }); -
problem with manage.py: No module named 'django'
When I tried to execute python manage.py runserver, it failed due to the SyntaxError. Then I tried it with python 3, it still didn't help and said "No module named 'django'". However, when I searched the packages in my virtualenv, it seemed that django is inside this virtualenv. It seems like it's using the local packages but not the packages inside the virtualenv. Can someone help me resolve this problem? Thx -
django + electron.js .exe
Existe alguna forma de crear una aplicacion de escritorio ejecutable .exe con django + electron.js?, si existe, podrian pasarme algun tutorial, ejemplo, documentacion, video. Que me ayude a entender ? -
django does't know MultiValueDictKeyError
when i try to recieve data from my html code for first time it Errors 'MultiValueDictKeyError' def comment(request): c = request.GET['comment'] return render( request, 'comment.html', context={ 'c' : c } ) becuase at first time there is no request. i changed this code to def comment(request): c = str() try: c = request.GET['comment'] except MultiValueDictKeyError: print(' ') return render( request, 'comment.html', context={ 'c' : c } ) but it Errors: name 'MultiValueDictKeyError' is not defined -
django/apache problem with No module named 'django
My problem is this Image When trying to access my Apache website I get the error 500 and that's why I decided to check the Apache log and I can't understand how to solve it The log of apache with error is this: [Sun Nov 24 19:06:06.409034 2019] [wsgi:error] [pid 30236] [client 173.44.36.79:49895] mod_wsgi (pid=30236): Target WSGI script '/var/www/html/taller_ortiz/taller_ortiz/wsgi.py' cannot be loaded as Python module. [Sun Nov 24 19:06:06.409188 2019] [wsgi:error] [pid 30236] [client 173.44.36.79:49895] mod_wsgi (pid=30236): Exception occurred processing WSGI script '/var/www/html/taller_ortiz/taller_ortiz/wsgi.py'. [Sun Nov 24 19:06:06.409444 2019] [wsgi:error] [pid 30236] [client 173.44.36.79:49895] Traceback (most recent call last): [Sun Nov 24 19:06:06.409527 2019] [wsgi:error] [pid 30236] [client 173.44.36.79:49895] File "/var/www/html/taller_ortiz/taller_ortiz/wsgi.py", line 12, in <module> [Sun Nov 24 19:06:06.409550 2019] [wsgi:error] [pid 30236] [client 173.44.36.79:49895] from django.core.wsgi import get_wsgi_application [Sun Nov 24 19:06:06.409617 2019] [wsgi:error] [pid 30236] [client 173.44.36.79:49895] ImportError: No module named 'django' [Sun Nov 24 19:06:06.813975 2019] [wsgi:error] [pid 30238] [client 173.44.36.79:49927] mod_wsgi (pid=30238): Target WSGI script '/var/www/html/taller_ortiz/taller_ortiz/wsgi.py' cannot be loaded as Python module. [Sun Nov 24 19:06:06.814064 2019] [wsgi:error] [pid 30238] [client 173.44.36.79:49927] mod_wsgi (pid=30238): Exception occurred processing WSGI script '/var/www/html/taller_ortiz/taller_ortiz/wsgi.py'. [Sun Nov 24 19:06:06.814249 2019] [wsgi:error] [pid 30238] [client 173.44.36.79:49927] Traceback (most recent call last): [Sun Nov … -
django.core.exceptions.FieldError: Cannot resolve keyword 'Topic' into field. Choices are: accessrecord, id, name, topic, topic_id, url
this is my molels.py from django.db import models # Create your models here. class Topic(models.Model): top_name = models.CharField(max_length=264,unique=True) def __str__(self): return self.top_name class Webpage(models.Model): topic = models.ForeignKey('Topic',on_delete=models.PROTECT) name = models.CharField(max_length=264,unique=True) url = models.URLField(unique=True) def __str__(self): return self.name class AccessRecord(models.Model): name = models.ForeignKey('Webpage',on_delete=models.PROTECT) date = models.DateField() def __str__(self): return self.date and this is my populate script import os os.environ.setdefault('DJANGO_SETTINGS_MODULE','first_project.settings') import django django.setup() ##fake pop script import random from first_app.models import AccessRecord, Webpage, Topic from faker import Faker fakegen = Faker() topics = ['Search','Social','Marketplace','News','Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(N=5): #get the topic for the entry top = add_topic() #create the fake data for that entry fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.name() #create a fake new Webpage entry webpg = Webpage.objects.get_or_create(Topic=top,url=fake_url,name=fake_name)[0] #create a fake access record for that Webpage acc_rec = AccessRecord.objects.get_or_create(name=webpg,date=fake_date)[0] if __name__ == '__main__': print("population script") populate(20) print("populate complete") ** i m trying run populate_first_app script .i have error.and this is my error I've never seen the error like this I am using this script under the influence of a virtual environment which I already installed all the packages I already checked a few things like uninstalling and installing the 'faker' library again … -
How can i deliver the product to the customer but not the source code in Django?
I'm working as a freelance developer for a while. I'm developing a web application using the Django web framework which is using python. Now consider the following scenario and help me out what should I do in such scenario? The customer wants to provide his own server for deploying the website on the other side I don't want to hand the source code to the customer, Now what should I do? is there any solution? By the way, based on the aforementioned scenario if the Django does not have such capability, what other frameworks do? (For example, this is the same for PHP frameworks, I think) -
Jquery click function not working for all the ids
I have created a page which contains all the products from the database, and this is dynamic page. Columns are created in loop. Whenever user clicks the product i am fetching the product id which is unique, however this is working only for one product, for next product even if click the function is not triggered. below is the code for reference. {{ album.product_name }} Category : {{ album.product_category }} Price : {{ album.product_price }} $(document).ready(function() { $('#k').click(function(){ var a = $('#custId').val(); alert(a) console.log(a) }); This is working perfectly fine for the first product only i.e the first product from the loop. for rest the click function is not working. Please help! -
self.foreign_related_fields[0] IndexError: tuple index out of range in django
I have tried before using same code but got an error like FieldDoesNotExist userid but why I do not know! Now I have got an error like this.. I am newcomer in django. Please help me to make this project. My custom authentication model in django: from django.db import models from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager ) from organization.models import Organization class UserManager(BaseUserManager): # use_in_migrations = True # python manage.py createsuperuser def create_user(self, orgid, username, email, password=None, is_admin=False, is_staff=False, is_active=True): if not orgid: raise ValueError("Organization of user must not empty") elif not username: raise ValueError("User must have an username") elif not email: raise ValueError("User must have an email address") org_obj = Organization.objects.all(orgid=orgid) user_obj = self.model( orgid=org_obj, username=username, email = self.normalize_email(email), password=password ) user_obj.set_password(password) user_obj.admin=is_admin user_obj.staff=is_staff user_obj.active=is_active user_obj.save(using=self._db) return user_obj # python manage.py createsuperuser def create_superuser(self, orgid, username, email, password=None): user = self.create_user(orgid,username,email,password=password,is_admin=True,is_staff=True,is_active=True) return user def create_staffuser(self, orgid, username, email, password=None): user = self.create_user(orgid,username,email,password=password,is_admin=False,is_staff=True,is_active=True) return user class User(AbstractBaseUser): orgid = models.ForeignKey(Organization, max_length=6, on_delete=models.CASCADE) username = models.CharField(primary_key=True, max_length=50) email = models.EmailField(max_length=255, unique=True, null=False, blank=False) admin = models.BooleanField(default=False) staff = models.BooleanField(default=False) active = models.BooleanField(default=True) date_joined = models.DateTimeField(auto_now_add=True) objects = UserManager() USERNAME_FIELD = "username" # REQUIRED_FIELDS must contain all required fields on your User … -
How to perform layer navigation in Django
i have a view to search in products using the Q library look in the product title and description. it works fine, what if i want advanced search for example after looking for iphone, within the search results i want the grey color using the side layer navigation like any professional ecommerce website any tutorial for the same? -
Django Form Doesn't Accept DateTime From DateTimePicker
I'm working on a todo web app and has a user enter an events datetime with a custom bootstrap datetimepicker from here. I have the custom widgets on a form formatted to MM/DD/YY hh:mm A. However, Django doesn't accept the form. A similar question has been asked, but instead of overriding the default DateTimeInput, I would like the form to display in a certain format but be stored in a database in the default format. I'm thinking of using widget tweaks to customize the picker but I don't know how to store it in default formats. What would be the best way to do this? Forms.py from bootstrap_modal_forms.forms import BSModalForm from .widgets import BootstrapDateTimePickerInput from bootstrap_datepicker_plus import DateTimePickerInput from .models import ToDoItem class NewEventForm(BSModalForm): class Meta: model = ToDoItem fields = ['title', 'description', 'start_time', 'end_time', 'remind_time'] widgets = { 'start_time': DateTimePickerInput( options={"format": "MM/DD/YYYY hh:mm A"} ), 'end_time': DateTimePickerInput( options={"format": "MM/DD/YYYY hh:mm A"} ), 'remind_time': DateTimePickerInput( options={"format": "MM/DD/YYYY hh:mm A"} ), } Event form: {% load bootstrap4 %} {% load static %} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <!-- Custom Stylesheet --> <link rel="stylesheet" type="text/css" href="{% static 'main/main.css' %}"> <!-- Moment.js --> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js" … -
Handling SMS messages when processing forms
I have a few views which handle the forms for new objects being created which seem to lag the user experience due to having to connect to the Twilio API. For example, the following form_valid method sends an SMS message to all receivers of a memo: def form_valid(self, form): form.instance.sender = self.request.user form.save() receiving_groups = form.cleaned_data['receiver'] for group in receiving_groups: username = list( employees.models.Employee.objects.filter( employee_type=group)) for user in username: form.instance.unread.add(user) memo_url = form.instance.pk user.send_sms('memo', memo_url) user.send_email('memo', memo_url) form.save() return super(MemoCreateView, self).form_valid(form) The issue here is that the send_sms method has to wait for a response before continuing. This really makes the site seem slow to the user. I have started to create a request_finished signal but I would have to pass a lot of parameters to the signal so this seems like a bad option. What other options do I have for sending the SMS messages post-success/redirect of the object being created? -
Can I use Sphinx write my help dicumentation in a django project
I have a django project and one menu option is 'Help'. The help documentation is written using Sphinx and there are many pages, e.g. Index, Introduction, First View, Users, Glossary. I have used the html: <li><a href="help" target="_blank">Help</a></li> My urls and views are: urls.py urlpatterns = [ url(r'^help/', views.index, name='index'), ] views.py: def index(request): context = {} url = 'help/index.html' return render(request, url, context) This takes me to the help index page from my menu, but every link I click on in the documentation page re-routes me back through index in views, and re-shows the index page, instead if displaying the link that I requested. If display the index page directly in a browser, without using the django site, it works as expected. I am loathe to integrate the help sub-system into django, because it would get over-written every time I 'make html'. What approach should I take?