1024programmer Java Does anyone have a Django add, delete, modify, check project? If you have done it, please send it to me.

Does anyone have a Django add, delete, modify, check project? If you have done it, please send it to me.

Who has a Django add, delete, modify, check project? If you have done it, send it to me

update html: urls.pyurlpatterns = patterns(”,(‘^area_update/$’, area_update),)models.pyclass Area(models.Model): val = models.CharField(max_length=255, blank=True, null=True)views.pydef area_update(request): id = request.REQUEST.get(‘id’) val = request.REQUEST.get(‘val’) area = Area.objects.get(id=id) area.val = val area.save() return HttpResponse(“ok”)Python is the language and django is the framework.

How does Django display the contents of the database in admin

How to do it: First, run the python manage.py createsuperuser command to create an administrator account. Then enter /admin in the URL to reach the administrator login page. After logging in, you will find that there are no items to be displayed in the database because we have not registered yet.

Next we register the data model to be managed in admin; register the model in admin.py.

Then refresh the page and you will see the ContactMessage data table. You can add and delete in it for simple addition, deletion, modification and query.

How to create a Django website

This article demonstrates how to create a simple Django website. The Django version used is 1.7. 1. Create a project. Run the following command to create a Django project. The project name is mysite: $ django-admin.py startproject The project directory after mysite is created is as follows: mysite├── manage.py└── mysite ├── __init__.py ├── settings.py ├── urls.py └ ── wsgi.py1 directory, 5 files description: __init__.py: Let Python treat this directory as the files required for a development package (i.e. a set of modules).

This is an empty file, generally you do not need to modify it.

manage.py: A command-line tool that allows you to interact with this Django project in a variety of ways. Type python manage.py help and see what it does. You should not need to edit this file; generating it in this directory is purely for convenience. settings.py : Settings or configuration for this Django project.

urls.py: URL routing settings for Django projects. Currently, it is empty. wsgi.py: Configuration file for the WSGI web application server.

For more details, see How to deploy with WSGI. Next, you can modify the settings.py file, for example: modify LANGUAGE_CODE, set time zone TIME_ZONESITE_ID = 1LANGUAGE_CODE = ‘zh_CN’TIME_ZOnE= ‘Asia/Shanghai’USE_TZ = True The [Time zone](https://docs.djangoproject.com/en/1.7/topics/i18n/timezones/) feature is enabled above, and pytz needs to be installed: $ sudo pip install pytz2. Before running the project, We need to create the database and table structure, here I am using the default database: $ python manage.py migrateOperations to perform: Apply all migrations: admin, contenttypes, auth, sessionsRunning migrations: Applying contenttypes.0001_initial… OK Applying auth.0001_initial. .. OK Applying admin.0001_initial… OK Applying sessions.0001_initial… OK Then start the service: $ python manage.py runserver You will see the following output: Performing system checks…System check identified no issues (0 silenced).January 28, 2015 – 02:08:33Django version 1.7.1, using settings ‘mysite.settings’Starting development server at http://127.0.0.1:8000/Quit the server with CONTROL-C. This will Start a local server on port 8000, and it can only be connected and accessed from this computer of yours. Now that the server is running, use your web browser to visit http://127.0.0.1:8000/. You should see a nice light blue Django welcome page now working.

You can also specify the startup port: $ python manage.py runserver 8080 and specify the ip: $ python manage.py runserver 0.0.0.0:80003. Before creating the app, a project was created and ran successfully. Now come Create an app, which is equivalent to a submodule of the project. Create an app in the project directory: $ python manage.py startapp polls If the operation is successful, you will see an additional folder called polls under the mysite folder. The directory structure is as follows: polls├── __init__.py├ ── admin.py├── migrations│ └── __init__.py├── models.py├── tests.py└── views.py1 directory, 6 files4. Create a model Every Django Model inherits from django. In db.models.Model, each attribute in the Model represents a database field. Through the Django Model API, you can perform database additions, deletions, modifications, and queries without writing some database query statements. Open the models.py file in the polls folder. Create two models: import datetimefrom django.db import modelsfrom django.utils import timezoneclass Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField(‘date published’) def was_published_recently(self) : return self.pub_date >= timezone.now() – datetime.timedelta(days=1)class Choice(models.Model): question = models.ForeignKey(Question) choice_text = models.CharField(max_length=200) votes = models .IntegerField(default=0) then in mysite/sModify INSTALLED_APPS in ettings.py and add polls: INSTALLED_APPS = ( ‘django.contrib.admin’, ‘django.contrib.auth’, ‘django.contrib.contenttypes’, ‘django.contrib.sessions’, ‘django.contrib.messages ‘, ‘django.contrib.staticfiles’, ‘polls’,) After adding the new app, we need to run the following command to tell Django that your model has changed and the database needs to be migrated: $ python manage.py makemigrations polls you will See the following output log: Migrations for ‘polls’: 0001_initial.py: – Create model Choice – Create model Question – Add field question to choice You can view the migration statements from polls/migrations/0001_initial.py.

Run the following statement, you can view the migrated sql statement: $ python manage.py sqlmigrate polls 0001 Output result: BEGIN;CREATE TABLE “polls_choice” (“id” integer NOT NULL PRIMARY KEY AUTOINCREMENT, “choice_text ” varchar(200) NOT NULL, “votes” integer NOT NULL);CREATE TABLE “polls_question” (“id” integer NOT NULL PRIMARY KEY AUTOINCREMENT, “question_text” varchar(200) NOT NULL, “pub_date” datetime NOT NULL); CREATE TABLE “polls_choice__new” (“id” integer NOT NULL PRIMARY KEY AUTOINCREMENT, “choice_text” varchar(200) NOT NULL, “votes” integer NOT NULL, “question_id” integer NOT NULL REFERENCES “polls_question” (“id”)); INSERT INTO “polls_choice__new” (“choice_text”, “votes”, “id”) SELECT “choice_text”, “votes”, “id” FROM “polls_choice”;DROP TABLE “polls_choice”;ALTER TABLE “polls_choice__new” RENAME TO “polls_choice” “;CREATE INDEX polls_choice_7aa0f6ee ON “polls_choice” (“question_id”);COMMIT;You can run the following command to check if there is a problem with the database: $ python manage.py check Run the following command again to create the newly added model: $ python manage.py migrateOperations to perform: Apply all migrations: admin, contenttypes, polls, auth, sessionsRunning migrations: Applying polls.0001_initial… OK To summarize, when modifying a model, you need to do the following steps: modify models. py file, run python manage.py makemigrations to create a migration statement and run python manage.py migrate to migrate the model changes to the database. You can read the django-admin.py documentation to see more usage of manage.py. After creating the model, we can test it through the API provided by Django. Run the following command to enter the interactive mode of python shell: $ python manage.py shell Here are some tests: >>> from polls.models import Question, Choice # Import the model classes we just wrote. # No questions are in the system yet.>>> Question.objects.all()[]# Create a new Question.# Support for time zones is enabled in the default settings file, so# Django expects a datetime with tzinfo for pub_date. Use timezone.now() # instead of datetime.datetime.now() and it will do the right thing.>>> from django.utils import timezone>>> q = Question(question_text=”What’s new?”, pub_date=timezone.now()) # Save the object into the database. You have to call save() explicitly.>>> q.save()# Now it has an ID. Note that this might say “1L” instead of “1”, depending# on which database you’re using. That’s no biggie; it just means your# database backend prefers to return integers as Python long integer# objects.>>> q.id1# Access model field values ​​via Python attributes.>>> q.question_text” What’s new?”>>> q.pub_datedatetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=)# Change values ​​by changing the attributes, then calling save().>>> q.question_text = “What’s up?”>>> q.save()# objects.all() displays all the questions in the database.>>> Question.objects.all()[] print For all Questions, the output result is []. We can modify the model class to make it output a more understandable description. Modify the model class: from django.db import modelsclass Question(models.Model): # … def __str__(self): # __unicode__ on Python 2 return self.question_textclass Choice(models.Model): # … def __str__( self): # __unicode__ on Python 2 return self.choice_text Next, continue testing: >>> from polls.models import Question, Choice# Make sure our __str__() addition worked.>>> Question.objects.all()[]# Django provides a rich database lookup API that’s entirely driven by# keyword arguments.>>> Question.objects.filter(id=1)[]>>> Question. objects.filter(question_text__startswith=’What’)[]# Get the question that was published this year.>>> from django.utils import timezone>>> current_year = timezone.now().year >>> Question.objects.get(pub_date__year=current_year)# Request an ID that doesn’t exist, this will raise an exception.>>> Question.objects.get(id=2)Traceback (most recent call last): …DoesNotExist: Question matching query does not exist.# Lookup by a primary key is the most common case, so Django provides a# shortcut for primary-key exact lookups.# The following is identical to Question .objects.get(id=1).>>> Question.objects.get(pk=1)# Make sure our custom method worked.>>> q = Question.objects.get(pk =1)# Give the Question a couple of Choices. The create call constructs a new# Choice object, does the INSERT statement, adds the choice to the set# of available choices and returns the new Choice object. Django creates# a set to hold the “other side” of a ForeignKey relation# (e.g. a question’s choice) which can be accessed via the API.>>> q = Question.objects.get(pk=1)# Display any choices from the related object set – – none so far.>>> q.choice_set.all()[]# Create three choices.>>> q.choice_set.create(choice_text=’Not much’, votes=0)>> > q.choice_set.create(choice_text=’The sky’, votes=0)>>> c = q.choice_set.create(choice_text=’Just hacking again’, votes=0)# Choice objects have API access to their related Question objects.>>> c.question# And vice versa: Question objects get access to Choice objects.>>> q.choice_set.all()[, , ]>>> q.choice_set.count()3# The API automatically follows relationships as far as you need.# Use double underscores to separate relationships.# This works as many levels deep as you want; there’s no limit.# Find all Choices for any question whose pub_date is in this year# (reusing the ‘current_year’ variable we created above).>>> Choice.objects.filter(question__pub_date__year =current_year)[, , ]# Let’s delete one of the choices. Use delete() for that.>>> c = q.choice_set. filter(choice_text__startswith=’Just hacking’)>>> c.delete()>>>> The above part of the test involves knowledge related to Django ORM. For detailed instructions, please refer to the ORM in Django.

5. Management adminDjango has an excellent feature. It has a built-in Django admin background management interface, which is convenient for managers to add and delete website content. The newly created project system has already set up the background management function for us. See mysite/settings.py: INSTALLED_APPS = ( ‘django.contrib.admin’, #Add background management functions by default ‘django.contrib.auth’, ‘django.contrib.contenttypes’, ‘django.contrib.sessions’, ‘django .contrib.messages’, ‘django.contrib.staticfiles’, ‘mysite’,) At the same time, the url to enter the background management has been added, which can be viewed in mysite/urls.py: url(r’^admin/’, include (admin.site.urls)), #You can use the set url to enter the website backend. Next we need to create a management user to log in to the admin backend management interface: $ python manage.py createsuperuserUsername (leave blank to use ‘june’): adminEmail address:Password:Password (again):Superuser created successfully. To summarize, let’s look at the project directory structure: mysite├── db.sqlite3├── manage.py├── mysite│ ├── __init__.py│ ├─ ─ settings.py│ ├── urls.py│ ├── wsgi.py├── polls│ ├── __init__.py│ ├── admin.py│ ├── migrations│ │ ├── 0001_initial.py│ │ ├── __init__.py│ ├── models.py│ ├── templates│ │ └── polls│ │ ├── detail.html│ │ ├── index.html│ │ └── results.html│ ├── tests.py│ ├── urls.py│ ├── views.py└── templates └── admin └── base_site.htm Through the above introduction, you can install and run django and how to create views and Once you have a clear understanding of the model, you can then learn in depth about Django’s automated testing, persistence, middleware, internationalization and other knowledge.

.get(pk=1)# Make sure our custom method worked.>>> q = Question.objects.get(pk=1)# Give the Question a couple of Choices. The create call constructs a new# Choice object, does the INSERT statement, adds the choice to the set# of available choices and returns the new Choice object. Django creates# a set to hold the “other side” of a ForeignKey relation# (e.g. a question’s choice ) which can be accessed via the API.>>> q = Question.objects.get(pk=1)# Display any choices from the related object set — none so far.>>> q.choice_set.all()[ ]# Create three choices.>>> q.choice_set.create(choice_text=’Not much’, votes=0)>>> q.choice_set.create(choice_text=’The sky’, votes= 0)>>> c = q.choice_set.create(choice_text=’Just hacking again’, votes=0)# Choice objects have API access to their related Question objects.>>>> c.question# And vice versa: Question objects get access to Choice objects.>>> q.choice_set.all()[, , ]>>> q.choice_set.count()3# The API automatically follows relationships as far as you need.# Use double underscores to separate relationships.# This works as many levels deep as you want; there’s no limit.# Find all Choices for any question whose pub_date is in this year# (reusing the ‘current_year’ variable we created above).>>> Choice.objects.filter(question__pub_date__year=current_year)[, , ]# Let’s delete one of the choices. Use delete() for that.>>> c = q.choice_set.filter(choice_text__startswith=’Just hacking’)>>> c.delete( )>>> The above part of the test involves knowledge related to Django ORM. For detailed instructions, please refer to the ORM in Django.

5. Management adminDjango has an excellent feature. It has a built-in Django admin background management interface, which is convenient for managers to add and delete website content. The newly created project system has already set up the background management function for us. See mysite/settings.py: INSTALLED_APPS = ( ‘django.contrib.admin’, #Add background management functions by default ‘django.contrib.auth’, ‘django.contrib.contenttypes’, ‘django.contrib.sessions’, ‘django .contrib.messages’, ‘django.contrib.staticfiles’, ‘mysite’,) At the same time, the url to enter the background management has been added, which can be viewed in mysite/urls.py: url(r’^admin/’, include (admin.site.urls)), #You can use the set url to enter the website backend. Next we need to create a management user to log in to the admin backend management interface: $ python manage.py createsuperuserUsername (leave blank to use ‘june’): adminEmail address:Password:Password (again):Superuser created successfully. To summarize, let’s look at the project directory structure: mysite├── db.sqlite3├── manage.py├── mysite│ ├── __init__.py│ ├─ ─ settings.py│ ├── urls.py│ ├── wsgi.py├── polls│ ├── __init__.py│ ├── admin.py│ ├── migrations│ │ ├── 0001_initial.py│ │ ├── __init__.py│ ├── models.py│ ├── templates│ │ └── polls│ │ ├── detail.html│ │ ├── index.html│ │ └── results.html│ ├── tests.py│ ├── urls.py│ ├── views.py└── templates └── admin └── base_site.htm Through the above introduction, you can install and run django and how to create views and Once you have a clear understanding of the model, you can then learn in depth about Django’s automated testing, persistence, middleware, internationalization and other knowledge.

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/does-anyone-have-a-django-add-delete-modify-check-project-if-you-have-done-it-please-send-it-to-me/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: 34331943@QQ.com

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索