Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Testing: AttributeError: 'Client' object has no attribute 'get'
I am new to Django framework & I am trying write some tests for my apps in the project.Currently I have two apps hoardings & clients both have same basic CRUD features.For testing purpose I have created a test directory & it looks like this clients - tests -__init__.py - test_views.py That's how I am maintaining my tests for both the apps.My test_views.py has following code, from django.test import TestCase from django.urls import reverse from hoardings.models import State, City from clients.models import Client class ClientManagementTest(TestCase): def setUp(self): self.state = State.objects.create(desc='West Bengal') self.city = City.objects.create(state=self.state, desc='Kolkata') self.client = Client() def test_client_creation_form_can_be_rendered(self): response = self.client.get(reverse('clients:create')) # Check that the response is 200 OK. self.assertEqual(response.status_code, 200) # check if csrf token is present self.assertContains(response, 'csrfmiddlewaretoken') # Check that the response contains a form. self.assertContains(response, '<form') # assert the context values self.assertIn('url', response.context) self.assertIn('heading', response.context) self.assertIn('states', response.context) self.assertIn('client_types', response.context) As you can see in the setup method I am creating an object of Client which is used to send the request.But every time I run the tests I get following errors, ERROR: test_client_creation_form_can_be_rendered (tests.test_views.ClientManagementTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/ropali/Development/PythonWorkspace/hms_venv/hms/clients/tests/test_views.py", line 19, in test_client_creation_form_can_be_rendered response = self.client.get(reverse('clients:create')) AttributeError: 'Client' object has no … -
i got an Error when i customize the model in django
i am using djoser for my rest api authentication when i try to add phone number functionality to the model the following Error occurs OperationalError at /api/users/ no such table: api_user models.py from django.db import models from django.contrib.auth.models import AbstractUser from phonenumber_field.modelfields import PhoneNumberField class User(AbstractUser): email = models.EmailField(verbose_name='email',max_length=50,unique=True) phone = PhoneNumberField(unique=True,blank=False,null=False) REQUIRED_FIELDS = [ 'first_name' 'last_name', 'phone', 'username', ] USERNAME_FIELD = 'email' def get_username(self): return self.email serializers.py from djoser.serializers import UserCreateSerializer,UserSerializer from rest_framework import serializers from .models import * class UserCreateSerializer(UserCreateSerializer): class Meta(UserCreateSerializer.Meta): model = User fields = ( 'id', 'email', 'username', 'password', 'first_name', 'last_name', 'phone' ) settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES':( 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES':( 'rest_framework.permissions.IsAuthenticated', ), } AUTH_USER_MODEL = 'api.User' ## Djoser DJOSER = { 'LOGIN_FIELD':'email', 'SERIALIZERS': { 'user_create':'api.serializers.UserCreateSerializer', 'user': 'api.serializers.UserCreateSerializer', }, } i can't find a solution to this,. And ,is there way to remove username from models.i want only email for authentication..?? -
How to scrape data faster with selenium and django
I am working on a web scraping project. In this project, I have written the necessary code to scrape the required information from a website using python and selenium. All of this code resides in multiple methods in a class. This code is saved as scraper.py. When I execute this code, the program takes sometime between 6 and 10 seconds to extract all the necessary information from the website. I wanted to create a UI for this project. I used django to create the UI. In the webapp, there is a form which when submitted opens a new browser window and starts the scraping process. I access the scraper.py file in django views, where depending on the form inputs, the scraping occurs. While this works fine, the execution is very slow and takes almost 2 minutes to finish running. How do I make the execution of the code faster using django faster? can you point me some tutorial on how to convert the scraper.py code into an api that django can access? will this help in making the code faster? Thanks in advance -
Building a django detailview and listview without using <int:pk>
I'm building a django app that displays a database of employees and their salaries. It uses a postgres database. I'm struggling to figure out how to build a DetailView without using a primary key for the url. I think using a slug may be the solution but I'm not sure how to implement that and haven't had much luck searching online. My Listview for the list of all companies: class AllCompanies(FormMixin, generic.ListView): template_name = 'AllCompanies.html' form_class = SearchForm model = bigdatabase queryset = bigdatabase.objects.order_by().values('company').distinct() context_object_name = 'companies' Example Database snippet, bigdatabase: Company EmployeeName Salary Alpha Jim 100000 Alpha Tim 125000 Beta Bim 90000 My list view displays all unique company names as intended. However, I'm not sure how to proceed and build a detailview to display more info on each unique company. I'd like to show things like number of employees, median salary, etc. I've done something similar by building a detailview for employees, but that relied upon using their primary key in the url since each employee is unique. Since I have many entries for many companies in my database, how would I build a detailview and accompanying url structure to support that? Any advice or pointers as to … -
API Versioning: providing different data formats for a resource
PROBLEM: when you write an API for an SPA, If the the API's json response or data changes, the SPA changes accordingly. so there is no need to version the API. But when you write an API for a mobile app, things are different. take a library mobile app for example: in app version 1.0 people see 5 books that have one image each one. but in version 2.0 because of change in design, different images should be passed for these 5 books. in app version 3.0 some other books are added which shouldn't be shown in previous versions for some reason. in this scenario, we should have three different responses for /books API end-point. the solution that comes to my mind is that I should have different for the /books endpoint: /v1/books /v2/books /v3/books you get the idea. QUESTION: what is the best way to handle "providing different data formats for a resource"? is there any best practice or standard for this? If this challenge is not properly handled, the development gets hard as the app grows, -
Why is my React app not loading correctly in Edge 84 (chromium) but does in chrome?
I have tried a django/react app as well as a base react app made using the create-react-app command. Both end up breaking in one way or another. For instance, the align-items tag does nothing (tried center, right, left). On my django/react app I have a header that loads perfectly on chrome but all I see is a background color on edge. -
HyperSkill Task
Hello I have a problem Hypreskill task.Can you Help me Hyper car service Description When the next client's turn is coming up, the operator should process it pushing the button. It happens when one of the mechanics has finished the work and able to serve the next client. You cannot define in the application the exact time, so leave the task to the operator. When the "Process next" button is pushed the application chooses the next client according to the algorithm's priority: Until the line of customers to change the oil is not empty, they served first If "Change oil" queue is empty the line of customers to inflate tires served next Clients who want to get diagnostics served last. Immediately the number of chosen ticket appears on the screen for all the customers and the length of the appropriate queue become one client less. You need not save the ticket further, the only purpose of it now is to show the number on the screen. Objectives Your task is to make a POST handler for processing the next ticket. After the request is received, remove the appropriate ticket from the queue. The handler should process POST requests at "<base_url>/processing", … -
How to link Django and React URLs to perform actions?
In Django, I have my login URL set to 'api/auth/login'. When given a username and password, it will log that user in. Running 'python manage.py runserver', it will put that URL at 'http://127.0.0.1:8000/api/auth/login' However, my React project, when running 'yarn start' is at 'http://localhost:3000/' and giving it the extension 'api/auth/login', the url it attempts is 'http://localhost:3000/api/auth/login'. This does not work, but if I replace the URL extension with 'http://127.0.0.1:8000/api/auth/login', the login works as expected. How can I have the URLs work with my React app? Or is this not something that necessarily needs to be fixed? I do plan to host this project somewhere and am not yet sure how the URLs will work out.. -
How to update a DateTimeField ONLY WHEN a BooleanField is checked from False to True?
# models.py class Appointment(models.Model): # not including some model fields and instead focusing on the model fields that are of concern records_sent = models.BooleanField(default=False) record_sent_date = models.DateTimeField(blank=True, null=True) records_received = models.BooleanField(default=False) record_received_date = models.DateTimeField(blank=True, null=True) # views.py class AppointmentUpdateView(UpdateView): model = Appointment fields = ['records_sent', 'records_received'] def form_valid(self, form): """ Update sent/received datetimes to current time when sent/received is checked from false to true. """ appointment = self.object if form.instance.records_sent: appointment.records_sent_date = timezone.now() if form.instance.records_received: appointment.records_received_date = timezone.now() return super().form_valid(form) My main concern has to do with my if-statement logic in my Class View's form_valid method. Currently, if my BooleanFields are checked True via POST request, the timezone updates to now(), which is fine. But let's say I set records_sent=True on 2:00 pm. If I set records_received=True on 4:00 pm, records_sent ALSO updates its time to 4:00 pm because the POST request sent records_sent AND records_received = True in the form, subsequently triggering the if-statement again when it should be only applying to records_received. How can I make it so that datetime.now() triggers ONLY when booleanfield is set from False to True, rather than having it also trigger from True to True? -
How to change the version of python run on apache for django
I have base GCP instance running Ubuntu 18.04. Running the python install gave me python 3.6.9. No problem initially. Now, I happen to be developing on 3.7 on my local machine. Until now this has not caused any issues with the Django apps I am developing. However, I am now developing an app that uses the module os.subprocess. It turns out that there are differences between 3.7 and 3.6 for this module. So I have successfully installed 3.7 on the server using sudo add-apt-repository ppa:deadsnakes/ppa sudo apt-get update sudo apt-get install python3.7 I ran sudo update-alternatives --config python3 and made sure it was active on the correct version. Selection Path Priority Status ------------------------------------------------------------ * 0 /usr/bin/python3.7 2 auto mode 1 /usr/bin/python3.6 1 manual mode 2 /usr/bin/python3.7 2 manual mode Now, I can run programs on the command line and it runs 3.7. However, even after restarting appache (indeed, I even restarted the VM). Django is still running with v 3.6. I even ran this command to see what version the user www-data is running. su - www-data -s /bin/bash -c 'python3 --version' and it confirms Python 3.7.9 (as I expect). What am I missing, why is apache still running 3.6.9 … -
Iam getting an error in the windows power shell when iam trying to install MySQL (pip install mysqlclient)
C:\Users\urs az33z\Desktop\fiza\myproject>pip install mysqlclient Traceback (most recent call last): File "c:\users\urs az33z\appdata\local\programs\python\python36\lib\runpy.py", line 193, in run_module_as_main "main", mod_spec) File "c:\users\urs az33z\appdata\local\programs\python\python36\lib\runpy.py", line 85, in run_code exec(code, run_globals) File "C:\Users\urs az33z\AppData\Local\Programs\Python\Python36\Scripts\pip.exe_main.py", line 5, in File "c:\users\urs az33z\appdata\local\programs\python\python36\lib\site-packages\pip_internal_init.py", line 40, in from pip._internal.cli.autocompletion import autocomplete File "c:\users\urs az33z\appdata\local\programs\python\python36\lib\site-packages\pip_internal\cli\autocompletion.py", line 8, in from pip._internal.cli.main_parser import create_main_parser File "c:\users\urs az33z\appdata\local\programs\python\python36\lib\site-packages\pip_internal\cli\main_parser.py", line 8, in from pip._internal.cli import cmdoptions File "c:\users\urs az33z\appdata\local\programs\python\python36\lib\site-packages\pip_internal\cli\cmdoptions.py", line 18, in from pip._internal.models.format_control import FormatControl File "c:\users\urs az33z\appdata\local\programs\python\python36\lib\site-packages\pip_internal\models\format_control.py", line 1, in from pip._vendor.packaging.utils import canonicalize_name ModuleNotFoundError: No module named 'pip._vendor.packaging.utils' C:\Users\urs az33z\Desktop\fiza\myproject>pip install mysqlclient-1.4.6-cp36-cp36m-win_amd64.whl Traceback (most recent call last): File "c:\users\urs az33z\appdata\local\programs\python\python36\lib\runpy.py", line 193, in run_module_as_main "main", mod_spec) File "c:\users\urs az33z\appdata\local\programs\python\python36\lib\runpy.py", line 85, in run_code exec(code, run_globals) File "C:\Users\urs az33z\AppData\Local\Programs\Python\Python36\Scripts\pip.exe_main.py", line 5, in File "c:\users\urs az33z\appdata\local\programs\python\python36\lib\site-packages\pip_internal_init.py", line 40, in from pip._internal.cli.autocompletion import autocomplete File "c:\users\urs az33z\appdata\local\programs\python\python36\lib\site-packages\pip_internal\cli\autocompletion.py", line 8, in from pip._internal.cli.main_parser import create_main_parser File "c:\users\urs az33z\appdata\local\programs\python\python36\lib\site-packages\pip_internal\cli\main_parser.py", line 8, in from pip._internal.cli import cmdoptions File "c:\users\urs az33z\appdata\local\programs\python\python36\lib\site-packages\pip_internal\cli\cmdoptions.py", line 18, in from pip._internal.models.format_control import FormatControl File "c:\users\urs az33z\appdata\local\programs\python\python36\lib\site-packages\pip_internal\models\format_control.py", line 1, in from pip._vendor.packaging.utils import canonicalize_name ModuleNotFoundError: No module named 'pip._vendor.packaging.utils' C:\Users\urs az33z\Desktop\fiza\myproject>python Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more … -
How can I do a on_conflict_replace work in Django batch_create operation?
The field account and month are unique togather. And I'm tring to batch_insert db data by bulk_create with Django to speed up my db operation. below is my base table # my db table class MSpendForMonth(models.Model): created_time = models.DateTimeField(auto_now_add=True) updated_time = models.DateTimeField(auto_now=True) system_value = models.DecimalField(max_digits=16, decimal_places=2) checked_value = models.DecimalField(max_digits=16, decimal_places=2, null=True) account = models.ForeignKey(MAccount, models.DO_NOTHING, related_query_name="account_month", related_name="account_month" ) month = models.IntegerField(blank=True, null=True) class Meta: db_table = 'spend_for_month' unique_together = (('account', 'month'),) # db operation bulk_data = [] try: with transaction.atomic(): for spend_data in spend_month_date_sum_queryset: bulk_data.append( MSpendForMonth( account_id=spend_data["account_id"], month=month, system_value=spend_data["sum_value"], ) ) MSpendForMonth.objects.bulk_create(bulk_data, ignore_conflicts=True ) # MSpendForMonth.objects.bulk_update(bulk_data, fields="system_value") except: import traceback as tb tb.print_exc() And I want to replace system_value with a new value as it sometimes changed. My question is how can I bulk_create data and replace with new value of system_value if there is a conflict on unique key account-month. It should be something like insert_many().on_conflict_replace() -- peewee Great thanks. -
AttributeError type object 'tickets' has no attribute 'USERNAME_FIELD'
I did not se up custom User class at the beggining. Now the application is done. The bug is that I cant post a ticket from the admin panel due to the error above. Any ideas? -
Django RESTFUL + axios and Vue.js frontend
Here goes nothing... I'm busy with a project where I connected Vuejs and Django with Django Restful and Axios and I created a simple get and post to see if everything works (Bit of a noob with API calls, normally I build static stuff, you will see soon enough) and it works! I can input a subject and message and post it to Django to the DB and call the Subject and message back to vue.js and display it. But this is not the final product and not the problem... I created an AI that is currently running separately with its own API calls The API calls are as follow Prefix Lenght Temperature Now that the AI is running on localhost:8080 I'm trying to point Django Restful API to that port and push get and post calls from the frontend via Django to the AI Here is a flow Vuejs - User requests something in a text field Django - Receives the request via Axios, saves it in the DB passes it to port 8080 AI - gets the request via Django and works its magic, when it's done, it passes the data requested back to Django and then Vuejs … -
How to resolve Django Exception happend during processing of request
Hello so I would love to understand what might be causing this error, so I have Django for my API and I have ReactJS for my Front-end. So when I launch React the homepage instantly makes a GET request to the server-side so to get the info from the database, but then now when I switch between pages within my React my API complains with this error: Exception happened during processing of request from ('127.0.0.1'.50368) I get the following Traceback: Traceback (most recent call last): File "C:\Python38\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "C:\Python38\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Python38\lib\socketserver.py", line 720, in __init__ self.handle() File "C:\Users\JUNIOR\Django Projects\uwcLectureApi\project\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "C:\Users\JUNIOR\Django Projects\uwcLectureApi\project\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Python38\lib\socket.py", line 669, in readinto return self._sock.recv_into(b) ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host So I do not understand what Is happening here and how I am to resolve this can I please get some assistance -
Point Django RESTAPI to URL and Port and get API calls from there
I currently have a python application running separately from Django that has its own API calls in JSON format on localhost:8080 that is currently in production and cant be taken offline atm So I'm thinking of a momentary workaround until I can make it a better so here is what I'm trying to do I would like to access the API calls in the above application via Restful API in Django so that I can bind them to fields in a frontend that I created. Django is running on port 8081 The only guides I've found on Restful is within Django 'How to create a restful application IN Django' But nothing on telling Restful to look at a URL and port and get the API calls from there. (yes this sounds like the long way around but I don't have a choice atm, will need to make the application a bit better where the application running on port 8080 is within Django but that's going to be a few thousand emails and calls and PT) if I go into Postman and do calls there and export the code under Python - http.client and import it into my models.py and try … -
Django pre fill a form with data from a selected line in a table
This site has been of great help but now I'm stuck. I have a page (allrmview) where the user can filter a table. Once that is done he can select a line. It opens a form (NewrmForm) page which is pre filled with some informations from the selected line in the table. I don't understand how i can send the datas selected to the new form. As I am a beginner a lot of elements are missing. models.py: class Infomp(models.Model): url = models.CharField(unique=True, max_length=150, blank=True, null=True) name = models.CharField(max_length=37, blank=True, null=True) synonyme = models.CharField(max_length=126, blank=True, null=True) chemname = models.CharField(max_length=100, blank=True, null=True) cas = models.CharField(max_length=15, blank=True, null=True) einecs = models.CharField(max_length=15, blank=True, null=True) mweight = models.FloatField(blank=True, null=True) vappress = models.CharField(max_length=31, blank=True, null=True) solublein = models.CharField(max_length=89, blank=True, null=True) insoluble = models.CharField(max_length=12, blank=True, null=True) odortype = models.CharField(max_length=11, blank=True, null=True) odorstrength = models.CharField(max_length=55, blank=True, null=True) substantivity = models.CharField(max_length=44, blank=True, null=True) odordescript1 = models.CharField(max_length=100, blank=True, null=True) odordescript2 = models.CharField(max_length=100, blank=True, null=True) usagelevel = models.CharField(max_length=39, blank=True, null=True) ifra = models.CharField(max_length=24, blank=True, null=True) risk = models.CharField(max_length=20, blank=True, null=True) cosing = models.CharField(max_length=6, blank=True, null=True) class RmStock(models.Model): id = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') num = models.IntegerField(unique=True) n_tgsc = models.SmallIntegerField(blank=True, null=True) nom_mp = models.CharField(max_length=60) quantite = models.FloatField(blank=True, null=True) fournisseur = models.IntegerField(blank=True, … -
Can't create Super user in Custom Multi User
I was trying to implement registration for 3 types of users: Parent, School and Vendor. from django.db import models from django.contrib.auth.models import (AbstractBaseUser, BaseUserManager) class UserManager(BaseUserManager): def create_user(self, email, password=None, is_staff=False, is_admin=False, is_active=True, is_parent=False, is_school=False, is_vendor=False): if not email: raise ValueError("Users must have an email address") if not password: raise ValueError("Users must have a password") if not parent: raise ValueError("Users must have a role") if not school: raise ValueError("Users must have a role") if not vendor: raise ValueError("Users must have a role") user_obj = self.model( email = self.normalize_email(email) ) user_obj.set_password(password) # change user password user_obj.parent = is_parent user_obj.school = is_school user_obj.vendor = is_vendor user_obj.active = is_active user_obj.staff = is_staff user_obj.admin = is_admin user_obj.save(using=self._db) return user_obj def create_parentuser(self, parent, school, vendor, email, password=None): user = self.create_user( email, parent, school, vendor, password=password, is_parent=True ) return user def create_schooluser(self, email, parent, school, vendor, password=None): user = self.create_user( email, parent, school, vendor, password=password, is_school=True ) return user def create_vendoruser(self, email, parent, school, vendor, password=None): user = self.create_user( email, parent, school, vendor, password=password, is_vendor=True ) return user def create_staffuser(self, parent, school, vendor, email, password=None): user = self.create_user( email, parent, school, vendor, password=password, is_staff=True ) return user def create_superuser(self, email, parent, school, vendor, password=None): user = … -
Getting Attribute Error after adding html file in django
I am trying to build a website on cPanel using django. My models were working fine untill I created my first html page and tried to render it. Now whenever I try to load my site I get "AttributeError at /admin/ module 'artclBlog.views' has no attribute 'home'" pic of error message my views.py from django.shortcuts import render, get_object_or_404 from .models import Blog def home(request): blogs = Blog.objects.order_by('-date') return render(request, 'blog/home.html', {'blogs': blogs}) my urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from artclBlog import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('blog/', include('blog.urls')), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my models.py from django.db import models class Blog(models.Model): title = models.CharField(max_length=200, default='') summary = models.CharField(max_length=200, default='') pageOne = models.TextField(default='') pageTwo = models.TextField(default='') pageThree = models.TextField(default='') pageFour = models.TextField(default='') date = models.DateField(default='') def __str__(self): return self.title -
Unable to fix error DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings
Please help resolving this env issue/error. I did found many posts about resolving that error but I still couldn't fix mine. I guess I am just unable to understand it in the right way. django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I have just one app in my Django project, had created using django-admin startproject. The app is added to settings.py under INSTALLED_APPS, and all other settings are set to default by Django itself which i haven't modified. I have few def in views.py working on models/forms, and those are working well. I also have created a new folder (myscripts) in the project (next to the app-name folder), and in that myscripts folder i have my other py scripts (other than models/forms). Executing those scripts works, I am able to import those models/forms, it does some work and adds a new entry in django db sqlite3 correctly. Further, i want to add/update execution status to the db entry (for a given pk/id) after my other scripts finishes its work. To achieve that, I am trying a new py script which will import models to … -
Syntax Error when migrating django server
I am trying to make a django server for a sociometric badge (https://github.com/HumanDynamics/openbadge-server) for our university's project. The code (and the whole badge) has been done by someone else and I have not myself changed anything. I am able to build the server but when trying to migrate or create a superuser, I get a syntax error. I've been trying to troubleshoot it by myself but I have very limited knowledge of python, django and Ubuntu so I'm probably missing something. I tried asking the original developer but he is busy with other stuff so haven't gotten a reply but as I have to get the project going, I'll try asking here. The error implies an error in the line 44 of /usr/local/lib/python2.7/site-packages/pkgconf/init.py but I cannot find the file so I cannot check it. In fact, the whole site-packages folder is empty so I wonder if I have installed modules in a wrong way? The code is written in python2.7 so I also wonder if the python2.7 being EOL could cause issues? It has already broken some parts, mainly how to get some of the modules. The code used in this project can be found here: https://github.com/HumanDynamics/openbadge-server Also the main … -
TemplateDoesNotExists Django doesn't find existing template
I'm getting the following error: This is my project structure: urls.py code: from django.contrib import admin from django.urls import path from core import views as core_views from portfolio import views as portfolio_views from django.conf import settings urlpatterns = [ path('', core_views.home, name='home'), path('about-me/', core_views.about, name='about'), path('portfolio/', portfolio_views.portfolio, name='portfolio'), path('contact/', core_views.contact, name='contact'), path('admin/', admin.site.urls), ] /project/views.py code: from django.shortcuts import render # Create your views here. def portfolio(request): return render(request, 'portfolio/portfolio.html') There are no migrations to apply, and I already restarted the server. -
Django Project - Online / Offline - Github
I just startet developing with Django / Python. Please be indulgent with me as I am just starting to become a developer :) .. Here is my question. I am using a linux shared hoster with cpanel, actually I am developing on my notebook. Now I would like to know how to work offline and beeing able to push it online. I recently read that there is a way to do that with github. Is this possible and what would be recommendable. Also is there any website offering django projects/templates which can be used which for example also provide already a login area etc.? Many thanks in advanced for any answer. -
Populate media asset files using something like `collectstatic`
How can I use Django's collectstatic to populate “media” (model-managed) asset files? I have a Django app that is using the “media” files support – files managed and associated with Model fields – for assets like product images and icons for specific instances. These (for some fields) need to be populated when the application is deployed; this means collecting the files from various locations and providing them where the “media” storage expects to find them. The web app already successfully serves these “media” files once they are collected. The correct configurations are working. But every time the site is deployed, the media files need to be collected together from the app-model locations that make sense for development, into the central directory tree (MEDIA_ROOT) where the files storage expects them to be served from. This task is very closely implemented by the tool collectstatic, for deploying “static” files (files that are intended not to be associated specifically with any model, but with the site as a whole and served outside the context of model permissions). How can I make use of collectstatic (or its implementation) to collect “media” asset files for deployment? -
Assigning subjects to a student
i am working on a student managment system project and i have a student,subject ,term and class models and i want to assign the subject objects to the student according tom the current term and class class Subject(models.Model): """ Subject """ name = models.CharField(max_length=200) term = models.ForeignKey(AcademicTerm,on_delete=models.CASCADE,related_name="subject-term",null=True,blank=True) student_class = models.ForeignKey('StudentClass',on_delete=models.CASCADE,related_name="subject-class",null=True,blank=True) staff_id = models.ForeignKey(CustomUser,on_delete=models.CASCADE,null=True,blank=True) class AcademicTerm(models.Model): """ Academic Term """ name = models.CharField(max_length=20, unique=True) current = models.BooleanField(default=False, null=True) class StudentClass(models.Model): name = models.CharField(max_length=200, unique=True) term = models.ForeignKey(AcademicTerm,on_delete=models.CASCADE,null=True,blank=True) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='student_profile',null=True,blank=True) group = models.ForeignKey(Group,related_name='student_group',on_delete=models.CASCADE,null=True) teacher = models.ManyToManyField(Teacher,related_name="student_teacher", blank=True) parent = models.ForeignKey('Parent',related_name="parent_sons",on_delete=models.CASCADE,null=True,blank=True) current_class = models.ForeignKey(StudentClass, on_delete=models.SET_NULL, related_name="student_class", null=True) current_term = models.ForeignKey(AcademicTerm, on_delete=models.SET_NULL, related_name="student_term", null=True) session_year = models.ForeignKey(AcademicSession, on_delete=models.CASCADE, related_name="student_seccion", null=True) subjects = models.ManyToManyField(Subject,related_name="student_subject") def subjects(self): term = AcademicTerm.objects.get(current=True) subs = Subject.objects.select_related('term').filter(term=term,student_class=self.current_class) for sub in subs: self.subjects = sub def save(self,*args,**kwargs): self.subjects() session = AcademicSession.objects.get(current=True) self.session_year=session parent = Parent.objects.filter(nationalId=self.parent_NationalId) if parent: self.parent = parent.get() return super(Student,self).save(*args,**kwargs) is creating the subjects method and calling it in the save method wright? or what?