Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
try to read csv using python to pythonanywhere host
We try to read csv file using view.py in pythonanywhere.com host. We try to get three cells (id, statement, and paragraph) from each row in the 1.csv file until last one. The code is: def home(request): Stats = Statments.objects.all() __file__ = '1.csv' module_dir = os.path.dirname(__file__) # get current directory file_name = os.path.join(module_dir, 'Politi_Stat/1.csv') #Load statments to database from CSV with open(file_name,"r", encoding = 'utf-8') as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: book = Statments(id = row[0] ,statment=row[1], Paragraph=row[2]) book.save() d = deque(posts) d.extendleft(reversed(Stats)) We import the csv and os. It seems an encoding problem of the unicode UTF-8 of csv. The output of the site is: Server 500 The output from the log file is: Traceback (most recent call last): File "/home/fattoh/.virtualenvs/django2/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/fattoh/.virtualenvs/django2/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/fattoh/.virtualenvs/django2/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/fattoh/Politi_Stat/app/views.py", line 46, in home for row in csv_reader: File "/home/fattoh/.virtualenvs/django2/lib/python3.7/codecs.py", line 322, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 82: invalid start byte 2019-11-27 19:20:54,714: Internal Server Error: / Traceback (most recent call last): File … -
Error 500 when Debug off on both local and Heroku with Whitenoise
I'm having alot of trouble either understanding how to properly host my static files on both local and heroku. Currently when Debug is turned off, I get an error 500- otherwise it works fine. I've read quite a few SO posts but so far, no solution has helped. Below is my code: settings.py INSTALLED_APPS = [ 'widget_tweaks', 'django_select2', 'masterform', 'tempus_dominus', 'team', 'sms', 'opportunities', "rest_framework", 'import_export', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', ] STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR, "live-static", "static-root") urls.py from django.views.static import serve from bdsurveyapp import settings urlpatterns = [ url('', include('opportunities.urls')), url(r'^sms/', include('sms.urls')), url(r'^admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), url(r'^dashboard/', include('dashboard.urls')), path('login/', auth_views.LoginView.as_view(template_name='pages/login.html'), name="login"), path('logout/', auth_views.LogoutView.as_view(template_name='pages/logout.html'), name="logout"), url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}), ] partial base.html <!DOCTYPE html> <html lang="en"> {% load static %} <head> {{ form.media.css }} <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <link rel="apple-touch-icon" sizes="180x180" href="{% static 'img/apple-touch-icon.png' %}"> <link rel="icon" type="image/png" sizes="32x32" href="{% static 'img/favicon-32x32.png' %}"> <link rel="icon" type="image/png" sizes="16x16" href="{% static 'img/favicon-16x16.png' %}"> <link rel="manifest" href="{% static 'img/site.webmanifest' %}"> <link rel="mask-icon" href="{% static 'img/safari-pinned-tab.svg' %}" color="#5bbad5"> <meta name="msapplication-TileColor" content="#da532c"> -
Filter using Q in Django , when multiple inputs can be null
I have a model product_details, with the following fields brand_name,model_name, bodystyle, transmission, and min_price, max_price Example of budget values in the dropdown is 1 - 5 5 - 10 10 - 15 I have 5 select dropdown fields on the basis of which I want to filter my results. I am using the method below to filter based on first three fields def select(request): q1 = request.GET.get('brand') q2 = request.GET.get('model') q3 = request.GET.get('bodyStyle') #q4 = request.GET.get('budget') cars = product_details.objects.filter(Q(bodystyle__icontains=q3)|Q(brand_name__icontains=q1)|Q(model_name__icontains=q2)) #cars = product_details.objects.filter(bodystyle=q3) return render(request, 'search/search_results.html', {'cars': cars}) I have two questions 1: How do I filter if only 1 or 2 values are selected from dropdowns. What should be my if condition? 2. How do I filter on the basis of range for budget fields? Since the budget needs to be compared with min_price and max_price. Any help or guidance would be appreciated. -
How could I remove the "import error" I am receiving on Django
I am watching this video to learn more about Django https://www.youtube.com/watch?v=v7xjdXWZafY my code is exactly like his however I am getting an import error. It says "no modules named urls" This is my code: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('weather.urls')), ] -
Why is Django not adding an entry to my Model table?
I am using an HTML page in Django's Views as well as other helper functions in Views to take data from form fields in the HTML page and send them to one of the Models databases through Django. This is all done off of my local host. I'm basing what I'm doing off of this solution. When I hard code an entry and send it from views to models, there isn't an issue. When I try to take data from the HTML field and then send it, I get a code 200, but logging into the admin panel and trying to access the database causes the local host server to crash, and the data is not entered into the table. Below is my code: Views Functions for getting and sending table entry to Models def addCharacter(sUserID, sPlayerName, sRace, sPlayerClass, sStr, sCon, sDex, sInt, sWis, sCha): from pathfinder.models import characterTable c = characterTable(userID = sUserID, playerName = sPlayerName, race = sRace, playerClass = sPlayerClass, strength = sStr, constitution = sCon, dexterity = sDex, intelligence = sInt, wisdom = sWis, charisma = sCha) c.save() #this function courtesy of Mahshid Zeinaly on stackoverflow https://stackoverflow.com/a/19761466/12352379 def request_page(request): if(request.GET.get('mybtn')): userID = 'testUser' addCharacter(userID, string(request.GET.get('characterName')), string(request.GET.get('race')), … -
Django fixture for a model with no fields?
If I have a Django model, with some field(s) defined: # model.py from django.db import models class Model(models.Model): text = models.CharField(max_length=10) I can initialize it by using a fixture: # sample.yaml - model: app.Model pk: 1 fields: text: "some text" with the command: manage.py loaddata sample.yaml and everything works fine. My problem is that I cannot do the same for a model with no fields: # model.py from django.db import models class Model(models.Model): pass # sample.yaml - model: app.Model pk: 1 fields: Then the same manage.py loaddata sample.yaml command gives an error: Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/django/core/serializers/pyyaml.py", line 73, in Deserializer yield from PythonDeserializer(yaml.load(stream, Loader=SafeLoader), **options) File "/usr/local/lib/python3.8/site-packages/django/core/serializers/python.py", line 112, in Deserializer for (field_name, field_value) in d["fields"].items(): AttributeError: 'NoneType' object has no attribute 'items' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 23, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.8/site-packages/django/core/management/commands/loaddata.py", line 72, in handle self.loaddata(fixture_labels) File "/usr/local/lib/python3.8/site-packages/django/core/management/commands/loaddata.py", line 114, in loaddata self.load_label(fixture_label) File "/usr/local/lib/python3.8/site-packages/django/core/management/commands/loaddata.py", line 172, in … -
trouble install mysqlclient on ubuntu18.04
I am trying to install mysqlclient on ubuntu 18.04 for a Django project but having problem installing mysql. Here is the information from terminal: MySQLdb/_mysql.c:29:10: fatal error: mysql.h: No such file or directory #include "mysql.h" ^~~~~~~~~ compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 -
Django - when user clicks button, get text in separate div tag, send it to the views.py and update the value for that user in the model
I am new to Django and the Front-end. The project I am working on is an E-Learning site where a user can go on a page (I call it a slide page) that has a text editor in it, and has to solve problems and does so via the text editor. When the user first visits a slide page that they have not been on before, a new record in the Slides model is added, and the value for the 'code' column (which is the text that is in the text editor) is automatically set to what is in that column for the admin (pre-defined text such as variables and comments). Then when the user updates the text in the text editor with their answer to the coding problem on the page and clicks any of the buttons on the page, I want to check this updated text with what is already in the 'code' column in the Slides model for that user (1 row per user for each slide), and if there is a difference, update the value of the 'code' column for that user in the Slides model. I tried playing around with some jQuery in the boolean.HTML … -
HTML Button Not Taking Up Full Width of Parent Div
I have an area on my website where events are listed. I have a parent div for the container and a div for each event section. When the user hovers over the section, an edit and delete button pops up on the left: The problem is the button isn't taking up the full width of the div, but only is as long as the text is. I know other questions have been asked, but none of the answers, such as adding box-sizing: border-box, work for me. HTML code: <div class="col-md-6 inline mb-4"> <h3 class="ml-2">Reminders:</h3> <div class="events-content-section ml-2"> {% for reminder in reminders %} <div class="mb-2" style="display: flex; align-items: center;"> <ul class="reminderUl"> <li> <span class="reminderSpan"> <button type="button" class="update-reminder btn btn-info" data-id="{% url 'update-reminder' reminder.pk %}"> <i class="fas fa-pencil-alt"></i> </button> </span> <span class="reminderSpan"> <button type="button" class="delete-reminder btn btn-danger" data-id="{% url 'delete-reminder' reminder.pk %}"> <i class="fas fa-trash-alt"></i> </button> </span> <button class="view-reminder btn btn-light" data-id="{% url 'view-reminder' reminder.pk %}"> <h4>{{ reminder.title }}</h4> </button> </li> </ul> </div> {% endfor %} </div> </div> -
Calculate next due date based on start date frequency and current date
I apologize if this has already been asked...I saw something for excel but I'm trying to do this in python. I have the following model: Class AccountDetails(models.Model): name = models.CharField(max_length=30, null=True) due_date = models.DateField(auto_now=False, auto_now_add=False, null=True) frequency_choices = [ ('weekly', 'Weekly'), ('bi-weekly', 'Bi-Weekly'), ('twice-monthly', 'Twice Monthly'), ('monthly', 'Monthly'), ('yearly', 'Yearly') ] frequency = models.CharField( max_length=15, choices=frequency_choices, default="weekly", ) I'm creating a plotly-dash datatable using pandas and I need to create a column titled "next_due_date". I want the value to be the next due date based on a start date, the current date, and a frequency. Example: due_date: 12/22/2017 frequency: Bi-Weekly current date: 11/27/2019 next_due_date should be: 12/6/2019 I'm pretty stuck on this one. Any help would be greatly appreciated! -
The for loop inside the school_list.html is not returning the names
the school_list.html file in the project is not displaying the list of school names .it just only prints the heading . I have added the link to complete project files in the linnk.Github link for project -
How to browse a webserver running in a docker container when the container itself is running in an AWS EC2 instance?
I have a Django webserver running in a docker container. When the container is running locally, I can see the server running by using a browser to point to the localhost port mapped with the exposed port of the container. Now I have the same container running in an AWS EC2 instance. The container's exposed port has been mapped to a certain port of the AWS instance. How can I browse the running webserver from local? (I connect to the AWS EC2 using SSH) -
Django Arrayfiled: Annotate queryset with the first item in the arryafield
I have a model that can be represented by something like this. class BackPack(models.Model): person = models.ForeignKey(Person, db_index=True, related_name='back_packs', on_delete=models.CASCADE) candy = ArrayField(models.CharField(max_length=203, null=True)) I want to build a queryset that is all back packs associated with one person and then annotated with the first item in the candy arrayfield. I tried the following; first_candy = BackPack.objects.filter(person__id=200)\ .annotate(first_candy=F('candy__0')) first_candy = BackPack.objects.filter(person__id=200)\ .annotate(first_candy=ExpressionWrapper(F('candy__0'), output_field=CharField())) The output for first_candy includes every item in the arrayfield not just the first one. Any help for the correct way of doing this is much appreciated. -
Redirect user for his first connexion
I want new users to be redirected to a specific web page only when it's their first connexion ever. I looked up online and on SO, but could not find anything. Is there any easy way to do it with django ? -
which directory is unsafe for deployment?
I'm going to deploy a Django web-application, with Nginx as the web server And I wanna deploy it on /opt/ directory. My question is: Does it matter which directory I'm going to upload my application? And are there any security issues for deploying in some specific directories? -
Django - How can I copy fields in same class
I will create some texts with organize that by "subjects" and "school_classes". Initially the "school_class" name will be the same as the "subject" name. So, when I create a text I need that field "subject" was be auto-filled with the field information of "school_class". This is to make it easier and not to err the subject as I already have the text ready and will just copy and paste it. Like a auto copy only when I create the texts, because I will change the "school_class" name in the future. Look to my models.py I try it: from django.db import models class Texts(models.Model): school_class = models.ForeignKey(School_class, on_delete=models.DO_NOTHING) subject = models.CharField(max_length=200, blank=True) body = models.CharField(max_length=200, null=True, blank=True) def statement(self): return self.collection def __str__(self): return self.subject The problem is that when I change the information in "school_class", automatically change in the "subject". Why I need this? In the future I will modify the "school_class" name of all my texts but I want the "subject" to remain the original when it was created. How to do this? -
django-session-timeout: how to disconnect automatically (without user action)
I am newbie in Django and try to implement 'autologout' using a tierce app django-session-timeout It works but I would like to improve behavior the session expire after time set in settings.py but there is no refresh so that it is disconnect and redirect to login page except if user click elsewhere in other word, the user is disconnect (as user session expire) but not automatically redirect to login page -> need a user event is it possible to improve this without writing my own middleware? settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django_session_timeout.middleware.SessionTimeoutMiddleware', ] LOGIN_URL = 'home' LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' SESSION_EXPIRE_SECONDS = 900 # 900 - >15 minutes = 15 * 60 SESSION_EXPIRE_AFTER_LAST_ACTIVITY = True SESSION_EXPIRE_AT_BROWSER_CLOSE = True SESSION_SAVE_EVERY_REQUEST = True -
Celery's pytest fixtures (celery_worker and celery_app) does not work
I'm trying to write a Celery(v. 4.2.1) integration test for my Django(v. 2.2.3) application. There is a bunch of outdated articles about this around, but non of them seem to use stuff from the latest celery testing documentation - https://docs.celeryproject.org/en/v4.2.1/userguide/testing.html#fixtures Seems like Celery comes with two fixtures for testing: celery_app and celery_worker which should allow to actually run worker in the background thread of your tests. As the doc's say I've added @pytest.fixture(scope='session') def celery_config(): return { 'broker_url': 'memory://', 'result_backend': 'rpc' } into my conftest.py I've wrapped my test function with @pytest.mark.celery_app @pytest.mark.celery_worker usually I wrap my celery tasks with from celery import shared_task @shared_task def blabla(...): pass but I've even tried to replace it with from myapp.celery import celery @celery.task def blabla(): pass What else... I run my celery task via apply_async providing eta argument. Tried tons of ways but the celery fixtures do not affect how things work and the task call goes to actual redis instance and is picked by a worker in a separate process (if I run it) and hence my assert_called fails along with my efforts to access the object which are in the testing database. -
Is it possible to initiate daily tasks using django-background-tasks when running using the same codebase scaled across multiple nodes(pods)?
The django extension is a great utility but I am concerned about scaleability. I have a django server running across three different nodes (pods). I have a task that has to run at a given time every day. This is triggered by the same codebase. Does this mean all 3 of my nodes are going to add the same daily task to the queue and it’ll be executed thrice then? -
Django: 'RegisterEmployeeView' object has no attribute 'object'
Am developing using django and i get AttributeError at /employee/register upon executing my runserver. this is the code in my views.py class RegisterEmployerView(CreateView): model = User form_class = EmployerRegistrationForm template_name = 'accounts/employer/register.html' success_url = '/' extra_context = { 'title': 'Register' } def dispatch(self, request, *args, **kwargs): if self.request.user.is_authenticated: return HttpResponseRedirect(self.get_success_url()) return super().dispatch(self.request, *args, **kwargs) def post(self, request, *args, **kwargs): form = self.form_class(data=request.POST) if form.is_valid(): user = form.save(commit=False) password = form.cleaned_data.get("password1") user.set_password(password) user.save() return redirect('accounts:login') else: return render(request, 'accounts/employer/register.html', {'form': form}) -
Unable to access instance variable by name in Django model
I am trying to save the value of a field in an instance variable on my Video model and then use this instance variable in a post_save signal receiver to see if the value of the field has changed. I am going off of this Stack Overflow answer: https://stackoverflow.com/a/36722021/ Here is my Video model: class Video(models.Model): approval = models.BooleanField(default=True) def __init__(self, *args, **kwargs): super(Video, self).__init__(*args, **kwargs) self.__original_approval = self.approval Here is my post_save signal receiver: @receiver(post_save, sender=Video) def handle_video_save(sender, **kwargs): video = kwargs.get('instance') previous_approval = video.__original_approval # check if value has changed... This is the error I'm getting: AttributeError: 'Video' object has no attribute '__original_approval' While debugging, I have found that the instance variable can be accessed this way in my post_save signal receiver: previous_approval = video._Video__original_approval So, using video._Video__original_approval works, but I'm wondering why am I unable to access the instance variable, as I've seen in other answers on Stack Overflow, with video.__original_approval? I'm using Django 1.11.20 and Python 3.6.6. -
'NoneType' object is not iterable in Django project
I am getting "'NoneType' object is not iterable" error while I try to run my django app using " python manage.py runserver ip:port" whereas the same error does not occur if I use " python manage.py runserver 0.0.0.0:8000". I really need to get this work using my ip address. Link to the error page. What am I doing wrong? This is how my settings.py looks like: """ Django settings for SimStudent project. Generated by 'django-admin startproject' using Django 2.2. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/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.2/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 = True #ALLOWED_HOSTS = ['0.0.0.0', '10.153.1.51', '127.0.0.1'] ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'channels', 'chat', 'django_tables2', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'SimStudent' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'SimStudent.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': … -
Django object query filter with multiple conditions
I'm trying to filter my model of travels by applying date and place condition but I can't have it in one query. schematic model class Travel(models.Model): code = models.CharField(max_length=10) company = models.ForeignKey('Company', on_delete=models.CASCADE) bus = models.ForeignKey('Bus', models.SET_NULL, blank=True, null=True,) class Stop(models.Model): travel = models.ForeignKey('Travel', on_delete=models.CASCADE) terminal = models.ForeignKey('Terminal', on_delete=models.CASCADE) arrival_datetime = models.DateTimeField() stay_duration = models.TimeField(default='00:30:00') order = models.IntegerField(verbose_name="Stop order", default=0) # Represent the order in which the bus will pass the stops class Terminal(models.Model): name = models.CharField(max_length=200) address = models.CharField(blank=True, max_length=200) city = models.ForeignKey('city', on_delete=models.CASCADE) class City(models.Model): name = models.CharField(max_length=100) This query should show the available travels depending from the origin and destination and date input by a personn. A travel can have many stops(including origin and destination) related to a terminal. To find out the order of this stops , the field order contains for each stop of a travel a number greater than the ones before. So one condition is to have the couple of {departure;origine} that has the right order. So at result, I should have a list of travels corresponding only to my origin, destination and date. -
Django CASCADE and post_delete interaction
I have the following model: class A(): foriegn_id1 = models.CharField # ref to a database not managed by django foriegn_id2 = models.CharField class B(): a = models.OneToOneField(A, on_delete=models.CASCADE) So I want A to be deleted as well when B is deleted: @receiver(post_delete, sender=B) def post_delete_b(sender, instance, *args, **kwargs): if instance.a: instance.a.delete() And on the deletion of A, I want to delete the objects from the unmanaged databases: @receiver(post_delete, sender=A) def post_delete_b(sender, instance, *args, **kwargs): if instance.foriegn_id1: delete_foriegn_obj_1(instance.foriegn_id1) if instance.foriegn_id2: delete_foriegn_obj_2(instance.foriegn_id2) Now, if I delete object B, it works fine. But if I delete obj A, then obj B is deleted by cascade, and then it emits a post_delete signal, which triggers the deletion of A again. Django knows how to manage that on his end, so it works fine until it reaches delete_foriegn_obj, which is then called twice and returns a failure on the second attempt. I thought about validating that the object exists in delete_foriegn_obj, but it adds 3 more calls to the DB. So the question is: is there a way to know during post_delete_b that object a has been deleted? Both instance.a and A.objects.get(id=instance.a.id) return the object (I guess Django caches the DB update until it finishes … -
Difference between auto_now_add and timezone.now as default value
What is the difference between auto_now_add and timezone.now (as default value) for models in Django? Example: create_date = models.DateTimeField(auto_now_add=True) and create_date = models.DateTimeField(default=timezone.now) ?