Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix Django in virtualenv on FreeBSD Raspberry reloads constantly
I have installed a fresh FreeBSD installation on a Raspberry PI 3+ with Python3.6 and virtualenv. Inside virtualenv 'web' I have created the Django Project 'prod' and uWSGI. I can start a uWSGI server instance without problem. But if I try to run python manage.py runserver 0.0.0.0:8000 Django reloads the server constantly because it detects changes to python files: December 07, 2018 - 15:00:59 Django version 2.2, using settings 'prod.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. /usr/local/lib/python3.6/gettext.py changed, reloading. Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). December 07, 2018 - 15:01:05 Django version 2.2, using settings 'prod.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. /usr/local/lib/python3.6/uuid.py changed, reloading. Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). this happens for every file in '/usr/local/lib/python3.6/' I have the same setup on a VirtualBox (not 100% same, the VirtualBox is a amd64 version of FreeBSD) if I run: python manage.py runserver 0.0.0.0:8000 --noreload the Server is reachable and stable I reformated the SD card and started the Project anew, same result. The only change to a file I did: ALLOWED_HOSTS … -
How to loop over custom plugin data on the template in django cms 3.5.3
I am trying to implement a website that uses RSS Feeds. My use case is to be able to display one RSS feed at a time, then loop over to the next maybe after 5 seconds. These RSS feeds need to be displayed on the same placeholder. I am new to django cms in case you need more info please let me know. I have googled a lot but all I can see is how to add plugins from the frontend and they will all automatically show inside the placeholder. Or modify the render method of the custom plugin class to display what you want. But I want to display everything but one at a time in a continuous manner @plugin_pool.register_plugin class ExternalArticlePlugin(CMSPluginBase): model = ExternalArticle name = _("External article") render_template = "external_article.html" cache = False def render(self, context, instance, placeholder): context = super(ExternalArticlePlugin, self).render( context, instance, placeholder ) return context I expect to display one RSS feed at a time inside my placeholder. Those feeds are links to the actual webpage with more info. -
Django forms: create a GET request that will instantiate as a form
Working in Django 2.1, I'm trying to genuinely forge a GET request that will resolve as a valid form after a redirect in the most DRY possible way. Basically I am in a view (some_view below) and I want to generate a GET request without prior knowledge on the way the form fields have to be serialized. urls.py path( r'select/', views.filtered_view, name='filter-view' ) path( r'save/', views.save_view, name='save-view' ) views.py # a form class with 'non-trivial' fields (e.g. not ints) class FilterForm(forms.Form): date = forms.DateInput() user = forms.ModelChoiceField(queryset=User.objects.all()) def filtered_view( request ): filter_form = FilterForm(request.GET) # do something with the form... # another view somewhere def some_view(request): ... user = User.objects.get( some_filter ) date = compute_some_datetime_date_object # generates here a GET request that will instantiate the FilterForm # correctly someargs = ... return redirect( 'filter-view' + someargs ) I know I can do something like (skipping the urllib.parse.urlencode...): return redirect( 'filter-view' ) + \ '?user='+ str(user_object.id) + \ '&date' + date.strftime('%Y-%m-%d') but it assumes I know that the pk is used to pass user object (depends on the form) and that I know also the format to use for the date... What I would like to do is something like: ff … -
How to start time and end time between to unique
i have order model, the order have vehicle , How to start time and end time between to unique -
why i am getting this error KeyError at /evaluationtest/? 'request'
hi i have create an Crud function for evaluation Test but i am getting keyerror 'request' this kind of strange to me i have not seen this error before i am new to django can somebody help me to fix it? def validate(self, data, *args, **kwargs): questions = self.context['request'].data.get("questions") if not questions: raise serializers.ValidationError("questions are required") if self.context["request"].method == "POST": self.questions = QuestionSerializer(data=questions, many=True) self.questions.is_valid(raise_exception=True) elif self.context["request"].method == "PUT": self.questions = questions self.new_questions = self.context["request"].data.get( "new_questions") if self.new_questions: self.new_questions = QuestionSerializer( data=self.new_questions, many=True) self.new_questions.is_valid(raise_exception=True) return data def create(self, data): evaluation_test = EvaluationTest() evaluation_test.category = data['category'] evaluation_test.admin = data['admin'] evaluation_test.title = data['title'] evaluation_test.type = data['type'] evaluation_test.save() for question in data['questions']: question.evaluationtest = evaluation_test question.save() return evaluation_test def update(self, instance, validated_data): instance.title = validated_data.get["title", instance.title] instance.type = validated_data.get["type", instance.type] instance.category = validated_data.get["category", instance.category] instance.admin = validated_data.get["admin", instance.admin] for question in self.questions: q = QuestionSerializer(instance=question["id"], data=question) q.is_valid(raise_exception=True) q.save() if self.new_questions: new_questions = self.new_questions.save() for question in new_questions: question.save() return instance -
Django email sending in development
My django email sending methods work fine in my local host .After deploying my django project on heroku .I have allowed the login from unknown devices in my gmail settings .Gmail does not allow the server login to my account and send me a message : spicious login attempt blocked infobot9@gmail.com Someone tried to log into your account using the password set for them. If it was not you, we recommend that you change your password as soon as possible. Unknown Device April 4, 11:39 Near this place: Dublin, Ireland 176.34.163.6 (IP address) Should I set extra parameters in my settings.py file or I need change my gmail account settings? Thank you in advance. -
making a chat subscription system with django and android
I want to build a chat system with subscriptions plan. A user can chat and get advice five times per subscription from advisors(advisors may vary based on problems). It is backend by django and api based on android app. Any advice on what can i do and where should i start? Actually I don't want to reinvent the wheel if there is anything that i can use to speed up the production. I Am looking for architecture that couldn't find anyone yet. I have tried to use ticketing system but most of them didn't have any api that can be used in Django and also android. -
How can I run a web app which is build using Angular and django on a single development Server?
I have a web application the front end is separated from the api, the front end is made of Angular running on a different developer server for example it is running on dev server 192.168.0.185:8000. And my api which is build using Django and python running on different development server also so the two is separated. The api is running on development server for example 192.168.0.185:8080. I am actually using 2 tabs (terminals) in running the two. My question: is there a way I can merge them so that I will only be using a single development server for the two of them? Would that affect my current project structure? Any idea? I know this is not about coding syntax or algorithms, hope you understand. Thank you. -
Django is caching my site even when caching is disabled
I am working on a development site, and most of the time caching is enabled in settings.py: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': '/var/www/example.com/cache', } } When I am actively working on it, I comment out the BACKEND and LOCATION lines above and add a dummy: CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', } } Django is caching the site even when I disable caching and empty the cache. It is very strange -- I can actually delete the main application folder (not the project folder) and the site continues to work. I ran into this while modifying templates and finding that my updates were not reflected in site content. I have tried option-reloading in Safari, loading in Chrome, private/incognito windows etc. Does Django have some secret cache that I don't know about? -
how to update FrontEnd in real time when the database get update from other apps?
first of all many thx in advance. I have deployed my django(1.11) project to azure, it works together with the postgresql db. Now for the frontEnd I would like to build up a live chart/figure, which means that every time when the postgresql db receive any update (from the function app on azure, not the django self), my chart/figure should be automatically refreshed. I have tried Signal, but it only react to the update which is made by django self. Then I try channels + redis, followed up the example(chat), but still not sure how to make it. my question is: which package/ components/ Tech should I use in this case? can you guys give me some example or a link to the certain tutorial? Look forward to the fancy idea from u guys. -
Django overriding settings.py OBJECT in unittest not working
There is Django app that uses Django Rest Framework. The settings file contains an object with the settings: settings.py REST_FRAMEWORK = { ... 'DEFAULT_THROTTLE_RATES': { 'burst': '30/second', }, ... } The unittest is supposed to test the throttling actually works. However none of the tools provided by Django Test module (SimpleTestCase.settings, override_settings, modify_settings) actually work: SimpleTestCase.settings class ThrottlingTest(RestApiTestCase): def test_per_second_throttling(self): new_config = settings.REST_FRAMEWORK new_config['DEFAULT_THROTTLE_RATES']['burst'] = '1/second' with self.settings(REST_FRAMEWORK=new_config): for _ in range(0, 2): response = self.client.get(self.api_reverse('foo')) self.assertEqual(response.status_code, 429) # fails, 200 != 429 override_settings class ThrottlingTest(RestApiTestCase): new_config = settings.REST_FRAMEWORK new_config['DEFAULT_THROTTLE_RATES']['burst'] = '1/second' @override_settings(REST_FRAMEWORK=new_config) def test_per_second_throttling(self): for _ in range(0, 2): response = self.client.get(self.api_reverse('foo')) self.assertEqual(response.status_code, 429) # fails, 200 != 429 Both methods work fine for primitive variables and lists, however fail for the object. Any clues how to handle this? -
Is it a good way to use pre_save signal in Django?
I want to know whether it is a good way to use pre_save signal in Django? Because between the time the pre_save signal is emitted and the model is actually saved on the database, there could be app crash or any other issue. My question is whether pre_save signal is reliable (can we assume always that if pre_save signal is emitted, data is going to be saved onto the database). -
Can't migrate after installation of django-allauth
I'm following the docs of django-allauth for installation, but I'm unable to manage.py migrate. I've included 'django.contrib.sites' in my INSTALLED_APPS, and SITE_ID = 1, but I get the error django.db.utils.ProgrammingError: relation "django_site" already exists I'm running Django 2.1.5. I can't find anything about "django_site" already exists, only "django_site" does not exist. -
difference (?) and recommendation (?) between "django-admin startapp" and "python manage.py startapp"
I've seen these two commands doing the same thing in practice. Which one of the two would you recommend and why would you recommend it? Thanks. -
Build a learning platform - link exercise to its lesson - onetoone field or foreign key?
I'm trying to build a small project - an e-learning project. I'm trying to bind some exercises to its lesson id. I've read the django docs and I don't know if I should use a OneToOne field or a Foreign Key. I've tried the idea with the foreign key, as I feel like this is the right answer. lessons - models.py (Lectie = lesson) from django.db import models # Create your models here. class Lectie(models.Model): YTLink = models.CharField(max_length = 100) PDFLink = models.CharField(max_length = 100) exercises - models.py (intrebare = question, variante = options, variantaCorecta = the right answer) from django.db import models from django.contrib.postgres.fields import ArrayField from lectii.models import Lectie # Create your models here. class Exercises(models.Model): idLectie = models.ForeignKey(Lectie, on_delete=models.DO_NOTHING) intrebare = models.CharField(max_length = 300) variante = ArrayField(models.CharField(max_length=300), null=True) variantaCorecta = models.IntegerField() def __str__(self): return self.intrebare I'm getting this error: You are trying to add a non-nullable field 'idLectie' to exercises without a default; we can't do that (the database needs something to populate existing rows). I will only add these questions from the back-end, they will not be added by the user, and I get this answer. Django doesn't know what ID to bind the exercise to. … -
How to DYNAMICALLY pass values from template to views, and then receive them too?
I have a template with a drop down list and some text boxes. I want the values appearing in the text box to change dynamically based on what the user selects in the drop down. How can I implement them such that when the user selects an option in drop down, corresponding data from database gets fetched and appears in those text boxes? -
I have a file generated from Django, I need to send that file as response to frontend using drf?
Using the python i have parsed a file and stored, now i need to send that file to my front end using drf as api view. Can I send a file as a response like json response? If so how t send it? -
Dynamic django form for admin panel
I have a Django form with an IntegerField. I would like to add fields in the form on the basis of the IntegerField. For Example: If the IntegerField is set to 4, 4 fields should be added to the django form in the admin panel. -
"ModuleNotFoundError", How to fix it?
`from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(receiver, instance, created, **kwargs): if created: Profile.objects.create(User=instance) @receiver(post_save, sender=User) def save_profile(receiver, instance, **kwargs): instance.Profile.save() apps.py from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals Error in server File "C:\Users\Mian.G\Desktop\django_admin\users\apps.py", line 7, in ready import users.signals ModuleNotFoundError: No module named 'users.signals' ` -
how to use query_string in django elasticsearch_dsl?
I am making elastic query using Q object and I have indexed documents, one of the documents contains "jbl speakers are great", but my query has "speaker" instead of speakers how can I find this document with query string. I have tried match_phrase but it is unable to find this document and when I had tried query_string it threw an error saying "query_string does not support for some key". I have also tried wildcard but that is also not working with query like {"query": {"bool": {"must": [{"match_phrase": {"prod_group": "06"}}, {"match_phrase": {"prod_group": "apparel"}}, {"wildcard": {"prod_cat_for_search": "+speaker*"}}, {"range": {"date": {"gte": "2018-04-07"}}}]}}} Q('match_phrase', prod_cat_for_search='speaker') I expect the output document containing speakers but actual output is no document containing speakers -
Django - How to use getattr for Dynamic Model?
Django - How to use getattr for Dynamic Model. I can not make this work. Any idea ? Thanks for listening _tipo = getattr(Model(), request.GET.get('modelName'))('objects') print(_tipo.all()) -
Django: set views, urls and templates for objects in categories/foreignkey
I have created models with categories, subcategories and sub-subcategories. I have had a lot of problems getting it to work. My models.py: class School(models.Model): school_name = models.CharField(max_length = 100) slug = AutoSlugField(populate_from = 'school_name', unique = True) ... class Department(models.Model): department_name = models.CharField(max_length = 100) slug = AutoSlugField(populate_from = 'department_name', unique = True) school = models.ForeignKey(School, on_delete = models.CASCADE) ... class Professor(models.Model): Professor_name = models.CharField(max_length = 100) slug = models.SlugField() department = models.ForeignKey(Department, on_delete = models.CASCADE) ... My views.py: def department_list(request, category_slug): category = get_object_or_404(School, slug = category_slug) schools = School.objects.filter(school_name = category) departments = Department.objects.filter(school = category) context = {'schools':schools, 'departments': departments} return render(request, 'main/department_list.html', context) def professor_list(request, category_slug, department_slug): category = get_object_or_404(School, slug = category_slug) subcategory = get_object_or_404(Department, slug = department_slug) schools = School.objects.filter(school_name = category) departments = Department.objects.filter(school = category) Professors = Professor.objects.filter(department = subcategory) context = {'Professors ': Professors} return render(request, 'main/Professor_list.html', context) class DepartmentCreateView(CreateView): model = Department fields = ['department_name'] def get_context_data(self, **kwargs): school = get_object_or_404(School, pk=self.kwargs['school_id']) kwargs['school'] = school return super().get_context_data(**kwargs) def form_valid(self, form): school = get_object_or_404(School, pk=self.kwargs['school_id']) form.instance.school = school return super().form_valid(form) My urls.py urlpatterns = [ path('<category_slug>/', views.department_list, name = 'departments'), path('<category_slug>/<department_slug>/', views.professor_list, name = 'Professors'), path('<category_slug>/new/', DepartmentCreateView.as_view(), name = 'department-create'), ] … -
Django Python - query count for the month and the past 6 months
I'm using django 1.10.5 with python 3.6. I have the following model class: class PublishedRecordedActivity(models.Model): published_details = models.ForeignKey(PublishedDetails, null=True, blank=True, on_delete=models.CASCADE) timestamp_added = models.DateTimeField(auto_now_add=True) activity_type = models.IntegerField(null=False, blank=False, default=1) I'm wanting to count the number of records for an activity type (1, 2, 3 or 4) for the current month and also for each of the past 6 months. For example, a count for the entire current month (April, 2019). A count for one month ago (the entire month of March 2019). A count for the two months ago (the entire month of February 2019), etc. I can write the query for the count, but I am unsure how to add the filter for each entire month. Here is my query: test_count = PublishedRecordedActivity.objects.filter(activity_type=1).count -
Problems uploading files to Django from React/Redux frontend with axios
I've got a django project set up using react/redux on my frontend and I need to be able to upload multiple files from the frontend which are read on the backend (not saved to the database or anything) so that I can do some server-side processing. However, I just can't seem to get the files in the django request handler. I'm sure it's something silly to do with my headers or the way I try post it but I've read like 30 other SO questions with similar titles and I can't seem to make mine work. I've got a FileUploader component that (seems to) allows me to upload the files and store them in my state. On hitting the upload button, I coerce it into formData (as most django sources said to do this) and fire off my post request. My React component export class FileUploader extends Component { static propTypes = { files: PropTypes.object.isRequired }; fileSelectedHandler = event => { this.props.uploadFiles(event.target.files); }; fileUploadHandler = event => { let formData = new FormData(); formData.append("files", this.props.files); console.log(this.props.files); console.log("formData", formData); this.props.addSubmission(formData); }; render() { return ( <div className="file-uploader"> <input type="file" multiple onChange={this.fileSelectedHandler} /> <button onClick={this.fileUploadHandler}>Upload</button> </div> ); } } const mapStateToProps = … -
Django pagination didn't work in my search results page
I just tried to add paginator for my search results page but it didn't work. I have 10 articles in search results and I set 3 for each page, which means totally the results list will be divided into 4 pages. However, when I searched keywords, it showed all 10 articles in the same page and the paginator didn't work. My view.py is: def search_titles(request): q = request.GET.get('q') error_msg = '' if not q: error_msg = 'Please enter keywords!' return render(request, 'search_results.html', {'error_msg': error_msg}) else: nq = q.split(' ') a_list = Q(article_ti__icontains=nq[0]) | Q(article_content__icontains=nq[0]) | Q( abstract__icontains=nq[0]) | Q( author__icontains=nq[0]) for i in nq[1:]: a_list.add(Q(article_ti__icontains=i) | Q(article_content__icontains=i) | Q(abstract__icontains=i) | Q(author__icontains=i), a_list.connector) queryset = Article.objects.filter(a_list).distinct() queryset_count = queryset.count() paginator = Paginator(queryset, 3) page_var = 'page' page = request.GET.get(page_var, 1) try: sets = paginator.page(page) except PageNotAnInteger: sets = paginator.page(1) except EmptyPage: sets = paginator.page(paginator.num_pages) return render(request, 'search_results.html', {'error_msg': error_msg, 'b_list': queryset, 'a_list_count': queryset_count, 'sets': sets, 'page_var':page_var}) my HTML code is: <div class="ui text container"> {% if error_msg %} <p>{{ error_msg }}</p> {% else %} {% for a in b_list %} <div class="ui segment"> <a target="_blank" href={{ a.get_abs_url }}> <h3>{{ a.article_ti }}</h3> <h5>{{ a.author }}</h5> <p>{{ a.abstract }}</p> </a> </div> {% empty …