Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-import_export is not working asking for DJANGO_SETTINGS_MODULE or call settings.configure()
django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variabl e DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
taking csv file as input from forms.py and processing it in django views
I am submitting form with csv file and want to process it on server forms.py class SaveCsvForm(forms.Form): upload_file = forms.FileField(label="Uplaod CSV File", help_text="Uploa data file in CSV format") I am using csv_file = request.FILES["upload_file"].read() in views.py to get the file data, But what I get in csv_file is content of file in string Is There any better way to get the file from POST request and process it. Note: when I don't read the file using read() I get InMemoryUploadedFile as stated in question [Parse and process CSV in Django -
Have received the following error while reusing movie app in my django project
I am using windows 10 python 3.7.3 and django 2.7.2 ,I am new to Django. Want to reuse the movie app "https://github.com/nathanborror/django-basic-apps/tree/master/basic " in my project. Steps done before running the manage.py runserver: 1) Copied the folder in my django project directory 2) Have added the app in the Installed apps in Settings.py 3) Have updated the apps url in the urls.py file of my main django project 4) Have checked from the git repo page , no additional dependancy to be downloaded. Error after running manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[0](_exception[1]).with_traceback(_exception[2]) File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "C:\Users\dhaval1.desai\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen … -
Do django-select2 form fields default to required=False?
I noticed my select2 fields don't have the required attribute in HTML? According to Django's form documentation the default required value is True. Any idea if select2 is defaulting to False? class CustomFroalaEditor(FroalaEditor): def __init__(self, *args, **kwargs): super(CustomFroalaEditor, self).__init__(*args, **kwargs) def render(self, name, value, attrs=None, renderer=None): html = super(FroalaEditor, self).render(name, value, attrs) return mark_safe(html) class NewBlaForm(forms.ModelForm): company = forms.ChoiceField(widget=forms.Select(attrs={'id': 'nbc__name-dropdown', 'class': 'form-control'})) product = forms.ChoiceField(widget=forms.Select(attrs={'id': 'nbp__name-dropdown', 'class': 'form-control', 'disabled': 'disabled'})) class Meta: model = Bla fields = ('product') -
Can't submit form because FroalaEditor field is required but hidden
I have a problem where I can't submit my form because my description textarea is required but hidden in my form. Any idea how I can solve this? I have no idea where style="display:none;" is coming from. Any idea? class CustomFroalaEditor(FroalaEditor): def __init__(self, *args, **kwargs): super(CustomFroalaEditor, self).__init__(*args, **kwargs) def render(self, name, value, attrs=None, renderer=None): html = super(FroalaEditor, self).render(name, value, attrs) return mark_safe(html) class NewBlaForm(forms.ModelForm): description = forms.CharField(widget=CustomFroalaEditor(attrs={'id': 'nb__description-editor'})) class Meta: model = Bla fields = ('description') -
Sort queryset with float values by specific order
I'm using django and I would like to get your help in order to sort my queryset as I would like. My queryset gets list of versions from a model. This is my queryset: def actual_edition(): return MyModel.objects.values_list('version', flat=True).filter(smt__isnull=False, published=True).order_by('version').first() It gives me: <QuerySet ['10.0', '9.10', '9.8', '9.9']> But I would like to handle my queryset in order to display the result in this order: <QuerySet ['9.8', '9.9', '9.10', '10.0']> version field is a CharField in my model (I can't update this one to FloatField for example). I don't find a way to do that with Django. Any idea ? Thank you ! -
Return list of dictionaries using django get_queryset()
I am facing an error while trying to fetch and return data from database. I am using get_queryset() returning queryset. command that i am using is data = MyModel.objects.filter(account_id=account_id) but i am getting error 'BaseList' object has no attribute 'items'. I think it is due to my data in the database, I have data in this format in my DB, Is it due to result has list of dicttionaries { "result" : [ { "savings" : 43.0548666420733, "count" : 18 }, { "savings" : 387.651510654053, "count" : 161 }], } models.py from mongoengine import Document, fields class MyModel(Document): result = fields.DictField() views.py class MyModelViewset(viewsets.ModelViewSet): renderer_classes = [renderers.JSONRenderer] serializer_class = MyModelSerializer def get_queryset(self): try: data = MyModel.objects.filter(account_id=account_id) return data except Exception as e: logger.exception(e) serializers.py class MyModelSerializer(serializers.DocumentSerializer): class Meta: model = MyModel fields = '__all__ -
How to remove a django app which is part of other app's migrations?
In a django 1.11 project with many apps, one app obsolete_app has become obsolete and is to be removed completely. It has a field ObsoleteField which is used in a model of app bar. The field is therefore referenced in migration files there. ObsoleteField is a child class of ManyToManyField with to to ObsoleteModel of app obsolete_app (both will be gone) Those migrations have already run on the production server I'm going in a circle but cannot find a order to make django happy: Add a migration that deletes ObsoleteField from the model of app bar Delete the models.py + add a migration to delete model ObsoleteModel Remove the app from INSTALLED_APPS Remove all fileds from obsolete_app Edit the old migrations that import the deleted fields/model I see this error: File "/var/venv-stable/lib/python2.7/site-packages/django/db/migrations/operations/fields.py", line 150, in state_forwards delay = not old_field.is_relation AttributeError: 'NoneType' object has no attribute 'is_relation' My idea was to make django believe the app never existed and therefore remove all imports, all migrations.AlterField etc. but manage.py migrate always complains about something. -
Redirecting to different URLs based on a variable or dictionary
I'm setting up a large scale experiment on 600 online classrooms. Each classroom has a unique classroomId and a URL associated with it. I would like to make a simple webpage, that once click on a "Next" button, correctly map students to the correct URL based on their classroomId. Students in the same classroom has the same classroomId, of course. Can some kind souls help me with the solutions or pointers to solve this problem using HTML/Javascript-Jquery/Django? I'm a social researcher and fairly new to the web technology. So far I've only manage to capture the online classroomId, creating webpages for the experiment. But got stuck on the mapping part. -
django-tables2 pagination menu too long for mobile and overflowing
I'm using django-tables2 on django2. it works great on desktop browser but when on mobile, the pagination menu on the bottom causes whole tablle to overflow. Basically the menu is just longer than my screen. I'm using css of DJANGO_TABLES2_TEMPLATE = 'django_tables2/semantic.html' below is the screenshots. I have tried django-tables2's default paginator, lazy paginator and playing around with per_page. class ReportListView(SingleTableMixin, FilterView): table_class = ReportTable template_name = 'report/report_list.html' context_object_name = 'reports' filterset_class = ReportFilter table_pagination = { 'paginator_class': LazyPaginator, } now it is currently showing 12 buttons on the pagination menu, including left and right arrow. I want paginator menu to be shorter. -
Connection Issues in Corporate Networks net::ERR_CONNECTION_REFUSED
I'm running a chat app in production using the code in https://github.com/Bearle/django-private-chat. Some users are reporting that they encounter the error Error in connection establishment: net::ERR_CONNECTION_RESET when trying to use the chat. It often seems to be the case in corporate environments. I posted an issue in the respective framework https://github.com/Bearle/django-private-chat/issues/31 and was asked to update some libraries - however it didn't fix the issue. The problem seems to occur when I'm trying to establish the websocket connection as follows. var base_ws_server_path = "wss://mentorcruise.com:2096/"; websocket = new ReconnectingWebSocket(base_ws_server_path + '{{ request.session.session_key }}/' + opponent_username); Keep in mind that usually this works fine for ~300 daily active users. I'm tracking the issues with Sentry and get about 4-5 of these errors per week. Given that it often occurs in a business setting makes me a little confused & I'd like to figure this out. I'd like that my users can always connect to the websocket - even in a corporate environment. -
How to setup categories model efficiently in python
I am setting up a model in Django. There is a field named category which I made a foreign field (because it would contain a lot of categories that will be added through the model). I want to be able to add more than one category per profile created by the user or in the admin, but I am only able to add one category per profile created. Please how can I solve this problem, I have no idea how to approach this. so far, the code below shows how far I have been able to do so far, and the picture to my admin: !https://imgur.com/a/UVYNs43 from django.conf import settings from django.db import models class Category(models.Model): name = models.CharField(max_length=50, default=None) slug = models.SlugField(max_length=50, unique=True, default=None) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name class Profile(models.Model): bio = models.TextField(blank=False) personal_website_url = models.URLField(blank=True) personal_website_name = models.URLField(blank=True) general_category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.bio or "" How can I add multiple categories per profile? because I am only able to add one category per profile in the Django model. -
Python: pyxform convert csv to xls
I have a system in Django that is used to store survey data. Some of the survey data were lost and now I need to recover those data. The data are backed up in csv and xls format. A model like below saves the data in different formats. class Forms(models.Model): xform = models.ForeignKey(XForm, related_name="fshistory") date = models.DateTimeField(auto_now=True) xls = models.FileField(upload_to=upload_to, null=True) json = models.TextField(default=u'') description = models.TextField(default=u'', null=True) xml = models.TextField() id_string = models.CharField(editable=False, max_length=255) title = models.CharField(editable=False, max_length=255) uuid = models.CharField(max_length=32, default=u'') version = models.CharField(max_length=255, default=u'') The xml and json stored in above model have been generated using pyxform(https://github.com/XLSForm/pyxform). from pyxform.builder import create_survey_from_xls survey = create_survey_from_xls(xls_file) xml = survey.to_xml() The problem is that I have only been able to convert the xls files using pyxform into xml. Other data that are stored in csv format are cannot be directly converted to xml so I need to convert them into xls first. So, I need to know whether pyxform has any module to convert csv to xls, or is there any other way possible to do so and obtain a proper xml file? I did try other techniques to convert the csv to xls like: def csv_to_xls(dir_name): for csvfile in … -
Saving json data to a Django model
I'm trying to save json data to a model. I'm getting all the data i need, how do i save them to a model? views.py ... def book_api(request): if request.method == 'POST': search = request.POST['textfield'] url = 'https://www.googleapis.com/books/v1/volumes?q=' + search print(url) r = requests.get(url).json() book_info = { 'title': r['items'][0-2]['volumeInfo']['title'], 'description': r['items'][2]['volumeInfo']['description'], 'author_name': r['items'][0-2]['volumeInfo']['authors'], 'genres': r['items'][0-2]['volumeInfo']['categories'], } print(book_info) return redirect('index') else: return render(request, 'api/book_api.html') ... models.py class Genres(models.Model): genres = models.CharField(max_length=200) def __str__(self): return self.genres class Authors(models.Model): author_name = models.CharField(max_length=200) def __str__(self): return self.author_name class Books(models.Model): title = models.CharField(max_length=300) description = models.TextField() authors = models.ForeignKey(Authors, on_delete=models.CASCADE) genres = models.ForeignKey(Genres, on_delete=models.CASCADE) def __str__(self): return self.title Was trying to do Books.objects.save(**book_info) but it raises a error "'Manager' object has no attribute 'save'" -
Why Django gives 'IntegrityError:NOT NULL constraint failed'?
In my model I have IntegerField, that is set to blank=True. But if I add a new record without value for this field it gives error IntegrityError: NOT NULL constraint failed. class Client(models.Model): ... sum_of_debts = models.IntegerField(blank=True) ... I already created and applied all migrations. I think I should set null=True, but can you explain why? -
Django - Method not Allowed (POST) after send data via AJAX
Error: Method Not Allowed (POST): / 405 occurs when submitting form via AJAX with POST method. Ultimately this should take all submitted values (first_name, last_name, phone, email) and save them respectively to proper Models with Foreign Key. I'm currently using class-based views and in def post I have to save object with simple validation but for few hours I wonder how to do it. urls.py urlpatterns = [ path('', views.AddressView.as_view()), path('add/', views.AddressPost.as_view()), path('delete/<int:pk>/', views.AddressDelete.as_view()), ] views.py class AddressView(generic.ListView): model = Person template_name = 'address_book/main.html' def get_context_data(self, *, object_list=None, **kwargs): context = super(AddressView, self).get_context_data(**kwargs) context.update({ 'people_list': Person.objects.all(), 'phones_list': Phone.objects.order_by('person_id'), 'email_list': Email.objects.all(), }) return context class AddressDelete(APIView): def get_object(self, pk): try: return Person.objects.get(pk=pk) except Person.DoesNotExist: raise NotFound def delete(self, request, pk, format=None): self.get_object(pk).delete() return Response(status=status.HTTP_204_NO_CONTENT) class AddressPost(APIView): def post(self, request, *args, **kwargs): pass add_contact.js $(document).ready(function () { var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val(); var csrftoken = $.cookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function (xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $("#addContactForm").submit(function(event){ var next_id = parseInt($("#addressTab tbody tr:last-child td:first-child").html())+1; var first_name = $("#first_name").val(); var last_name = $("#last_name").val(); var phone = $("#phone").val(); var email = $("#email").val(); if (first_name … -
graphene get in query GenericForeignKey field
i am just using graphql. Got problem with querying GenericForeignKey. Lets say i have following model also created schema using DjangoObjectType: class Feature(GenericRelationValidator, ActiveMixin, TimestampMixin, UUIDMixin): start_time = models.DateTimeField(db_index=True, validators=[validate_start_time]) content_type = models.ForeignKey( ContentType, on_delete=models.CASCADE, limit_choices_to={"model__in": ["album", "collection", "mix"]} ) object_id = models.UUIDField(db_index=True, unique_for_date="start_time") item = GenericForeignKey("content_type", "object_id") class FeatureNode(DjangoObjectType): class Meta: model = Feature interfaces = (relay.Node,) filter_fields = ("content_type",) I have tried query like this but got error. query Features { features { edges { node { id, objectId, item, contentType { model } } } } } I defined ContentType with DjangoObjectType so it has no problem. How can i get item? -
How to build clean method for a formset?
I overrided the clean() method of a form and I had a formset of this form. The problem is that the clean() method isn't called I think, the validation doesn't work and I don't understand why. Can you help me ? I'm maybe (for sure) doing something wrong ? forms.py class SetUpdateForm(forms.ModelForm): class Meta: model = Set fields = [ 'scoreTeam1', 'scoreTeam2', 'match', ] def clean(self): cleaned_data = super().clean() scoreTeam1 = cleaned_data.get("scoreTeam1") scoreTeam2 = cleaned_data.get("scoreTeam2") sport = cleaned_data.get("match").phase.tournament.sport if scoreTeam1 and scoreTeam2: print("a") if scoreTeam1 < sport.nbPointPerSet and scoreTeam2 < sport.nbPointPerSet or scoreTeam1 > sport.nbPointPerSet and scoreTeam2 > sport.nbPointPerSet: raise forms.ValidationError("A set is played in" + str(sport.nbPointPerSet) + " points") if scoreTeam1 == scoreTeam2: raise forms.ValidationError("Scores can't be equal") return cleaned_data MatchSetFormset = forms.inlineformset_factory(Match, Set, form=SetUpdateForm, min_num=1, extra=0, can_delete=False) Normally the method should be called each time a form is validated ? I don't understand. -
Django ORM - get records that are older than record's `duration` days
I have the model: class Plan(models.Model): date = models.DateTimeField() duration = models.DurationField(default=30) I want to get the records that are older than today - duration with ORM. Is it possible? Maybe something like Plan.objects.filter(date__lt='self.duration') exists? -
how to place pop up box in django url
Here is my js code to display the pop up.I want to use this pop up in the delete course url inside the table body.How can i do that so that after only pop up i can delete the course.I have very few knowledge in js and and i am also very new to django so can anyone help me to solve this ? js code <div class="col-lg-3 col-md-6"> <div class="box"> <div class="box-header"> <h3 class="box-title">Warning message</h3> <p class="m-0">(Click on image)</p> </div> <div class="box-body pad res-tb-block"> <img src="../../../images/alert/alert4.png" alt="alert" class="model_img img-fluid" id="sa-warning"> </div> <!-- /.box-body --> </div> <!-- /.box --> </div> <script src="{% static '/js/pages/data-table.js' %}"></script> <script src="{% static '/assets/vendor_components/sweetalert/sweetalert.min.js' %}"></script> <script src="{% static '/assets/vendor_components/sweetalert/jquery.sweet-alert.custom.js' %}"></script> template <tbody> {% for course in courses %} <tr> <td> <ol > {{ forloop.counter }} </ol> </td> <td>{{course.title}}</td> <td>{{course.basic_price|intcomma}}</td> <td>{{course.advanced_price|intcomma}}</td> <td>{{course.basic_duration}}</td> <td>{{course.advanced_duration}}</td> <td style="min-width: 250px">{{course.shift}}</td> <td><a href="{% url 'students:edit_course' course.id %}"> Update</a></td> <td><a href="{% url 'students:delete_course' course.id %}"> Delete</a></td> # I want this js pop while clicking delete url . </tr> {% endfor %} </tbody> -
Can I reference project URLs in Django templates by providing the project name?
I have a Django project called reports with apps report_1, report_2 etc. For certain reasons, I want to treat the project as an app, so I have added reports to INSTALLED_APPS alongside report_1 and report_2 and also created views.py file and templates folder in the main project folder (where settings.py sit). In the views.py I have added app_name = reports. However, calling the url from within template will work only if I skip the app name: so {% url 'reports:index' %} will throw 'reports' is not a registered namespace' error, but {% url 'index' %} will work. Why is that so? I thought Django traverses all apps listed in INSTALLED_APPS, looks for app_name (which is provided) and matches it with URL name. -
Storing data from csv file into model in django?
I am submitting csv file from form using POST method and want to save its content into model forms.py class SaveCsvForm(forms.Form): upload_file = forms.FileField(label="Uplaod CSV File", help_text="Uploa file in CSV format") Views.py def save_csv(request): if request.method == 'POST': form = SaveCsvForm(request.POST, request.FILES) if form.is_valid(): print("All ok I am check One") # instance = CsvStorage(file_field=request.FILES['file']) file = request.FILES['upload_file'].read() print(file) csv_to_db(file) ack = { 'status': 'Success', 'message': 'Data is successfuly submited into database' } return JsonResponse(ack) else: ack = { 'status': 'Error', 'message': 'Server Returned '+form.errors.as_json(), } return JsonResponse(ack) else: form = SaveCsvForm() return render(request, 'upload_csv.html', {'form': form}) file handler method for storing data in Model def csv_to_db(filename): with open(filename, 'r') as file: ''' reading csv file in dictionary format ''' reader = csv.DictReader(file) for row in reader: instance = CsvStorage(username=row['username'], first_name=row['user'], city=row['city'], mobile=row['mobile'] ) instance.save() if instance: return({'status': 'successfuly'}) else: return({'status': 'error'}) Note: 1.The main problem is while reading the file 2.I don't want to store file in models fileField -
How to Save file in database instead of upload in server media folder ,using models.FileField?
I want to save file in database instead of upload it in server media file and save URL in Database,I want directly save file in Database using. Right now i am doing this model.py File = models.FileField(upload_to='CSR/', null=True , blank = True) template.html <td> {{certificate.File.url}} </td> -
How to fixing django admin login error in scrapy
I am setting this spider on my windows 10 machine. I am using python3 this time to crawling. HTTPERROR_ALLOWED_CODES =[403] My problem is when i am runing it. it's showing 403 csrf error and i am showing it into browser with response from allowing HTTPERROR_ALLOWED_CODES. # -*- coding: utf-8 -*- import scrapy from scrapy import Spider from scrapy.http import Request from scrapy.utils.response import open_in_browser import os class ManvCrawlSpider(scrapy.Spider): name = 'django_crawl' start_urls = ['https://127.0.0.1:8080'] def parse(self, response): token = response.xpath('//*[@name="csrfmiddlewaretoken"]//@value').extract_first() return [FormRequest(url="https://127.0.0.1:8080/admin", headers={ 'Content-Type': 'text/html; charset=UTF-8', "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B179 Safari/7534.48.3", }, formdata={'csrfmiddlewaretoken': token, 'method': 'post', 'username': 'palash', 'next': '/admin/', 'password': 'palash1234', }, callback=self.parse_page)] I expect the result would be fix the 403 response -
WAMP server loading static files when DEBUG = True not when DEBUG=False even after collectstatic
I deployed a django based app on WAMP server using mod_wsgi and to serve all the static files I run the py manage.py collectstatic command. I checked that the site is serving well but the static files are serving only when DEBUG=True. But as per the Django's document DEBUG=True will serve the static files on the development server for other servers we should use DEBUG=False. I also checked that all the static files got collected after collectstatic I am not understanding why it is happening. Below is the settings.py file """ Django settings for olxApp project. Generated by 'django-admin startproject' using Django 2.1.5. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # SECURITY WARNING: don't run with debug turned on in production! DEBUG =False THUMBNAIL_DEBUG = False ALLOWED_HOSTS = ['10.0.100.148','127.0.0.1','192.168.1.8','localhost'] # Application definition INSTALLED_APPS = [ 'olx.apps.OlxConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'sorl.thumbnail', 'bootstrap3', ] MIDDLEWARE = …