Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I create a Django department page model?
I want to create a departmental model. The areas to be here are as follows. departments_name, departments_description, departments_cover_photo, departments_avatar I will assign staff to the department page I created. This department page will also contain message, task, document, file and folder models. Obviously what I want to do is a simple task management system. How can I do that? Is there any project, code or application you can give an example? Thank you. -
Detecting changes in related models in Django Rest Framework
I have a model in django, let's call it product, that is referenced by multiple purchase instances. A purchase can be made for any number of items of the product, subject to the following constraint: The total of all items in all purchases for a given product must be less than a set maximum number of items, which is defined differently for each product. Users may create a purchase for a product, and I want to keep track of the total number of items covered by all purchases at any given time. This is complicated by the fact that users can modify or delete their purchase, thereby changing the total number of items purchased. How would I go about keeping track of this number for each product and updating it every time a purchase is changed? Is there a hook that can listen to the purchases for a product and detect a change? purchase model: class Purchase(models.Model): items = models.IntegerField(blank=False, default=1) delivery_method = models.CharField(max_length=100, blank=False, default='') #... product = models.ForeignKey('product.Product', related_name='purchases', on_delete=models.CASCADE) product model: class Product(models.Model): name = models.CharField(max_length=100, blank=False,) items_offered = models.IntegerField(blank=False, default=2) # Items purchased should be the total number # of items in all purchases for this … -
Django get last record -1 from database
I am doing a Save in every move of my django project (a game actually), and all I am trying to do is to get the LAST data I saved in the database in every new "click". newsave = Save() newsave.user = save.user myList = json.loads(newsave.myField) # Read previous here, here is the problem ... (do some changes on myList) ... newsave.myField = json.dumps(myList) # Save the new move, UPDATED The problem is that I don't know how to read the previous move correctly. -
The view blog.views.add_comment_to_post didn't return an HttpResponse object. It returned None instead
This is my code which is giving error: @login_required def add_comment_to_post(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('post_detail', pk=post.pk) else: form = CommentForm() return render(request, 'blog/comment_form.html', {'form':form}) I am getting this error for the above view: ValueError at /post/3/comment/ The view blog.views.add_comment_to_post didn't return an HttpResponse object. It returned None instead. I searched stackoverflow and was trying to fix. But nothing is working. I can't find where the problem is. -
why we use Django intermediate model?
why we use intermediate model? can't we just use Many to many relationship without intermediate model? -
ModelForm + ModelMultipleChoiceField can't validate populated list of checkboxes
everybody. I'm trying to build some checklist application. Basically, I have list of checkboxes with states stored in db. I need to load and display their initial state, made changes (select/deselect some of them) and store new checkboxes state back to db. First phase is done - I've got a view that load checkboxes and states, but when I'm trying to put it back via calling ModelForm with request.POST data (), it fails due some fields\types incompatibility. I've tried to modify my model and POST results, but no result. Here is my views.py: class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_infinibox_list' def get_queryset(self): return Infinibox.objects.all() def detail(request,infinibox_id): # print(request.GET) if request.POST: print('-=posting data=-',request.POST) form=ChoiceForm(request.POST) print(form.is_valid()) #Here I constanty get False return HttpResponseRedirect(reverse('polls:detail', args=(infinibox_id,))) else: try: infinibox = Infinibox.objects.get(pk=infinibox_id) except Infinibox.DoesNotExist: raise Http404('Infinibox does not exist') choice = Choice.objects.filter(infinibox_id=infinibox_id) votes = [ch.id for ch in choice if ch.votes == 1] choice_text=[ch.choice_text for ch in choice if ch.votes == 1] form = ChoiceForm(initial={'infinibox':infinibox,'votes':votes,'choice_text':choice_text},q_pk=infinibox_id) return render(request, 'polls/detail.html', {'form': form, 'infinibox': infinibox,}) Here is my models.py: from django.db import models from django.utils import timezone import datetime class Infinibox(models.Model): infinibox_name = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.infinibox_name def was_published_recently(self): now = timezone.now() … -
error django.db.utils.ProgrammingError: relation "myApp_audiofile" does not exist when trying to rename Model
I have a model called AudioFile which is used in several ManyToMany and ManyToOne relations. I tried a simple rename migration (as suggested here) looking like this: from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('myApp', '0004_feedback'), ] operations = [ migrations.RenameModel('AudioFile', 'MediaFile') ] But instead of it working a get an error traceback looking like this: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/mac/.virtualenvs/myVenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/Users/mac/.virtualenvs/myVenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/mac/.virtualenvs/myVenv/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/Users/mac/.virtualenvs/myVenv/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/Users/mac/.virtualenvs/myVenv/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/Users/mac/.virtualenvs/myVenv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Users/mac/.virtualenvs/myVenv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/Users/mac/.virtualenvs/myVenv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/Users/mac/.virtualenvs/myVenv/lib/python3.6/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/Users/mac/.virtualenvs/myVenv/lib/python3.6/site-packages/django/db/migrations/operations/models.py", line 369, in database_forwards to_field, File "/Users/mac/.virtualenvs/myVenv/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 515, in alter_field old_db_params, new_db_params, strict) File "/Users/mac/.virtualenvs/myVenv/lib/python3.6/site-packages/django/db/backends/postgresql/schema.py", line 112, in _alter_field new_db_params, strict, File "/Users/mac/.virtualenvs/myVenv/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 773, in _alter_field self.execute(self._create_fk_sql(model, new_field, "_fk_%(to_table)s_%(to_column)s")) File "/Users/mac/.virtualenvs/myVenv/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 120, in execute cursor.execute(sql, params) File … -
Uploading image using mongoengine.Imagefield in Djangorest won't save
I am trying to make an image field using mongoengine in DJango. The form shows up, I upload the image, all other fields are saved except the image but it keeps saying "This field is required" for the thumbnail_new field. Here is my model class VideoMain(Document): """This class represents the Video Meta data model.""" video_id = fields.SequenceField() ytlink = fields.StringField() title = fields.StringField() description =fields.StringField() show = fields.StringField() published_at = forms.DateTimeField() views = fields.IntField() thumbnail = fields.StringField() **thumbnail_new = fields.ImageField(size=600,thumbnail_size=None)** channel_name = fields.StringField() channel_description = fields.StringField() guests = fields.ListField(fields.StringField(max_length=30)) anchors = fields.ListField(fields.StringField(max_length=30)) tags = fields.ListField(fields.StringField(max_length=30)) And here is the Django form from django import forms from .models import * class ShowDetailsForm(forms.Form): shows = Show.objects.all() title = forms.CharField() description = forms.CharField() channel = forms.CharField() publishingdate = forms.CharField() views = forms.IntegerField() thumbnail = forms.CharField() thumbnail_new = forms.ImageField() #show = forms.ChoiceField(shows) class Meta: model = VideoMain fields="__all__" And finally the view function where the form has to be stored def show_video_data(request): """ View function for renewing a specific BookInstance by librarian""" if request.method == 'POST': #print("I am post") form = ShowDetailsForm(request.POST,request.FILES) if form.is_valid(): newfile=FileUploadHandler(title='anything', file=request.FILES['thumbnail_new']) newfile.save() print (form.photo) # do saving # form.save() return HttpResponseRedirect('/fetchvideodata') I am new to django, so please bear … -
Evaluate lookup for known object
I have a filter along these lines: class EventManager(models.Manager): def joinable(self, current_time): query = Q(join_time__lte=current_time) & Q(end_time__gte=current_time) return self.filter(query) So, given a time, return the events that you could join. I'd also like to add a can_join method to events: class Event(models.Model): def is_joinable(self, current_time): return self.join_time <= current_time & self.end_time >= current_time But I'd like to avoid duplicating the logic here (the actual logic is a little more complicated and will likely change). Is there a way in is_joinable to evaluate the query and determine if self would pass it? Or can I write both methods on top of some other method? Obviously I could do something like query = Q(id=self.id) & joinable_query return Event.objects.filter(query).exists() but that seems a pointless extra database query for a record that I already have at my fingertips. -
How to convert Django app to RoR?
I just found out I can't deploy Django on cPanel so I'm converting it to Ruby on Rails. It's a small app where users can sign up for a bronze, silver or gold package for a service. I precisely want to convert this flow from Django to RoR: DJANGO CODE: url: #level is bronze, silver or gold url(r'^signup/(?P<level>[\w\-]+)/$', views.signup, name="signup"), view: # subscribe to gold/silver/bronze package def signup(request, level): """ when users subscribe to a package """ context_dict = {} context_dict['level'] = level return render(request, 'payligent/signup.html', context_dict) template on the index page that links to the signup page with the level (bronze in this case): <a href=" {% url 'payligent:signup' 'bronze'%} "><button class="btn btn-success">Get Started</button></a> This is what I have so far for RoR: routes.rb: get 'pricing/:level', :to => 'welcome2#pricing', as: "package_signup" controller: class Welcome2Controller < ApplicationController def pricing @package_signup = package_signup.find('bronze') end end view: <a href="<%= link_to 'package_signup bronze', package_signup_path(@package_signup) %>"><button class="btn btn-success">Get Started</button></a> However, I receive this error on the RoR server: No route matches {:action=>"pricing", :controller=>"welcome2", :level=>nil} missing required keys: [:level] -
OperationError at /teams/
I have a database file I downloaded online and i am trying to get the contents from that database and display it on a template. Here is the code from my view. "getAllTeams()" is the call to a method that connects to the database and gets the contents and returns a list from django.shortcuts import render_to_response from django.shortcuts import render,HttpResponse from myTest.models import * import pdb import myTest.models databaseFile ="../database.sqlite" def index(request): return render(request,'myTest/home.html') def teams(request): teamsList = getAllTeams(databaseFile) teamsList.sort(key= lambda t: t.team_name) # print(teamsList) context = { 'teamsList':teamsList, } return render(request,'myTest/teams.html',context) Here is the method that gets the data and returns a list of objects def getAllTeams(databaseFile): conn = create_connection(databaseFile) cur = conn.cursor() cur.execute("SELECT * FROM Team t, Team_Attributes ta where t.team_api_id = ta.team_api_id GROUP BY team_long_name") rows = cur.fetchall() teamList = [] for row in rows: team = Team(row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9], row[10], row[11], row[12], row[13], row[14], row[15], row[16], row[17], row[18], row[19], row[20], row[21], row[22], row[23], row[24], row[25], row[26], row[27]) #print(team) teamList.append(team) return teamList This is the error I get when running the template When I run the view in the console, the function works and returns the data -
Django Session counter
I'm making a food order project in Django, and I want to set unique order numbers for quick verification of the user when they come to pick the food up after the order. If I create a random combination of numbers and letters, there can be an issue of two orders having the same order number. Is it possible to make the order number unique to each session? -
Flexible database models for users to define extra columns to database tables in Django
I am trying to build a tool that, at a simple level, tries to analyse how to buy a flat. DB = POSTGRES So the model basically is: class Property(models.Model): address = CharField(max_length = 200) price = IntegerField() user = ForeignKey(User) # user who entered the property in the database #.. #.. # some more fields that are common across all flats #However, users might have their own way of analysing # one user might want to put estimated_price = IntegerField() # his own estimate of the price, different from the zoopla or rightmove listing price time_to_purchase = IntegerField() # his own estimate on how long it will take to purchase # another user might want to put other fields # might be his purchase process requires sorting or filtering based on these two fields number_of_bedrooms = IntegerField() previous_owner_name = CharField() How do I give such flexiblity to users? They should be able to sort , filter and query their own rows (in the Property table) by these custom fields. The only option I can think of now is the JSONField Postgres field Any advice? I am surprised this is not solved readily in Django - I am sure lots … -
Heroku server error (500) when Debug = False
I am getting a Server Error(500) when debug is set to false, But the site works fine when debug=True This is the Heroku log: 2017-07-29T15:22:25.000000+00:00 app[api]: Build started by user ***@gmail.com 2017-07-29T15:22:45.447968+00:00 app[api]: Release v65 created by user ***@gmail.com 2017-07-29T15:22:45.447968+00:00 app[api]: Deploy 325508d0 by user **@gmail.com 2017-07-29T15:22:25.000000+00:00 app[api]: Build succeeded 2017-07-29T15:22:45.949889+00:00 heroku[web.1]: State changed from down to starting 2017-07-29T15:22:50.992213+00:00 heroku[web.1]: Starting process with command `gunicorn techzu.wsgi --log-file -` 2017-07-29T15:22:53.873583+00:00 app[web.1]: [2017-07-29 15:22:53 +0000] [4] [INFO] Listening at: http://0.0.0.0:15611 (4) 2017-07-29T15:22:53.873172+00:00 app[web.1]: [2017-07-29 15:22:53 +0000] [4] [INFO] Starting gunicorn 19.7.1 2017-07-29T15:22:53.873667+00:00 app[web.1]: [2017-07-29 15:22:53 +0000] [4] [INFO] Using worker: sync 2017-07-29T15:22:53.877406+00:00 app[web.1]: [2017-07-29 15:22:53 +0000] [10] [INFO] Booting worker with pid: 10 2017-07-29T15:22:53.913261+00:00 app[web.1]: [2017-07-29 15:22:53 +0000] [11] [INFO] Booting worker with pid: 11 2017-07-29T15:22:54.635686+00:00 heroku[web.1]: State changed from starting to up 2017-07-29T15:23:08.967412+00:00 heroku[router]: at=info method=GET path="/" host=techub.cf request_id=275137b6-be7b-4063-ab4b-b2e2bf6c5592 fwd="49.207.185.28" dyno=web.1 connect=0ms service=342ms status=500 bytes=253 protocol=http 2017-07-29T15:24:27.270506+00:00 app[api]: Starting process with command `python manage.py collectstatic` by user ***@gmail.com 2017-07-29T15:24:33.208722+00:00 heroku[run.2277]: Awaiting client 2017-07-29T15:24:33.259613+00:00 heroku[run.2277]: Starting process with command `python manage.py collectstatic` 2017-07-29T15:24:33.322288+00:00 heroku[run.2277]: State changed from starting to up 2017-07-29T15:25:09.910068+00:00 heroku[run.2277]: State changed from up to complete 2017-07-29T15:25:09.895165+00:00 heroku[run.2277]: Process exited with status 0 2017-07-29T15:25:31.773816+00:00 heroku[router]: at=info method=GET path="/" host=techub.cf request_id=1e0ba0ee-541f-4788-a015-561a2f38a708 … -
Calculating incidence of unique tuples in a list of tuples
For a classifieds Django website project, I have a list of tuples made up of (user_id, ad_id) pairs. This denotes the clicker's user_id, alongwith the relevant ad_id. For example: gross_clicks = [(1, 13),(1, 12), (1, 13), (2, 45), (2, 13), (1, 15), ...(n, m)] The elements in this list are by no means unique - each click gets pushed into this list regardless of whether it's by the same user and/or it's on the same ad. Now I can get all unique clicks by doing: unique_clicks = [] import operator gross_click_ids = map(operator.itemgetter(0), gross_clicks) return len(set(gross_click_ids)) But how do I get unique clicks per ad? I.e. if same user clicked on two different ads, that would be counted as 2 separate clicks. Performance matters too - it's a large data set - so would prefer the most efficient solution, alongwith an illustrative example. -
Django referencing a ManyToManyField within the same model error without quotations
https://docs.djangoproject.com/en/1.11/topics/db/examples/many_to_many/ So I based my code off this document and I hit an error. from django.db import models class Gift(models.Model): name = models.CharField( max_length=120, unique=True, help_text='Enter the gift item name' ) # skipping to the ManyToMany .... genre = models.ManyToManyField(Category) class Category(models.Model): # skipping stuff like CATEGORIES ... type = models.IntegerField( primary_key = True, choices = CATEGORIES, default = EVENT, ) description = models.CharField(max_length=500, null=True, blank=True) I receive this error Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/.../gifting_db/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/.../gifting_db/lib/python3.6/site-packages/django/core/management/__init__.py", line 337, in execute django.setup() File "/.../gifting_db/lib/python3.6/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/.../gifting_db/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/.../gifting_db/lib/python3.6/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/.../gifting_db/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File "/.../gifting_db/gifting/gifts/models.py", line 5, in <module> class Gift(models.Model): File "/.../gifting_db/gifting/gifts/models.py", line 20, in Gift category = models.ManyToManyField(Category) NameError: name 'Category' is not defined But if I add quotations to … -
Django Field.Choices name group
According to the Django documentation for implementing Field.Choices, you can specify naming groups for each choice you create as in the example: MEDIA_CHOICES = ( ('Audio', ( ('vinyl', 'Vinyl'), ('cd', 'CD'), )), ('Video', ( ('vhs', 'VHS Tape'), ('dvd', 'DVD'), )), ('unknown', 'Unknown'), ) The function MODEL.get_FOO_display() returns the second tuple value, such as "VHS Tape" (the first value "vhs" is used as the field's value). What's the best way to return the group name, ie 'Video'? -
Django: How to make an admin account for a school which has many users associated to it?
I am making a webapp and it basically consists of schools and users associated to different schools. Currently I am trying to make it so that the school itself can have a sort of admin panel that will show all the teachers and students that are registered with the school. These are the three models for students, teachers and schools: class StudentProfile(models.Model): user = models.OneToOneField(User, null = True, related_name = 'StudentProfile', on_delete = models.CASCADE) teacher = models.BooleanField(default = False) school = models.CharField(max_length = 50) def username(self): return self.user.username def fullname(self): return (self.user.first_name + " " + self.user.last_name) class TeacherProfile(models.Model): user = models.OneToOneField(User, null = True, related_name = 'TeacherProfile', on_delete = models.CASCADE) teacher = models.BooleanField(default = True) school = models.CharField(max_length = 100) subject = models.CharField(max_length = 100) head_of_subject = models.BooleanField(default = False) headmaster = models.BooleanField(default = False) def username(self): return self.user.username def fullname(self): return (self.user.first_name + " " + self.user.last_name) class SchoolProfile(models.Model): school_name = models.CharField(max_length = 100, default = '', unique = True) identification_code = models.CharField(max_length = 10, unique = True) def id_code(self): return self.identification_code I used the same approach as I did with students and teachers where I just extended the user model, however things like email and name are … -
UnicodeEncodeError when using search_fields in Django admin
I'm very new at Django and have UnicodeEncodeError when using search_fields in admin with cyrillic symbols. Search with ascii symbols works properly. What should I look for? File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 174. response = self.process_exception_by_middleware(e, request) File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 172. response = response.render() File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/template/response.py" in render 160. self.content = self.rendered_content File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/template/response.py" in rendered_content 137. content = template.render(context, self._request) File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/template/backends/django.py" in render 95. return self.template.render(context) File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/template/base.py" in render 204. with context.bind_template(self): File "/usr/lib/python2.7/contextlib.py" in __enter__ 17. return self.gen.next() File "/home/vagrant/venv/local/lib/python2.7/site-packages/debug_toolbar/panels/templates/panel.py" in _request_context_bind_template 79. context = processor(self.request) File "/home/vagrant/venv/local/lib/python2.7/site-packages/url_tools/context_processors.py" in current_url 8. return dict(current_url=UrlHelper(full_path)) File "/home/vagrant/venv/local/lib/python2.7/site-packages/url_tools/helper.py" in __init__ 25. self.query_dict = QueryDict(r.query, mutable=True) File "/home/vagrant/venv/local/lib/python2.7/site-packages/django/http/request.py" in __init__ 385. value = value.decode(encoding) File "/home/vagrant/venv/lib/python2.7/encodings/utf_8.py" in decode 16. return codecs.utf_8_decode(input, errors, True) Exception Type: UnicodeEncodeError at /admin/persons/person/ Exception Value: 'ascii' codec can't encode characters in position 0-11: ordinal not in range(128) -
Django Integrity Error- Unique Constraint Failed
Trying to create a simple launch page for my website to collect email addresses. When the user goes to submit, it is providing the following error (traceback below)--Unique Constraint Failed---accounts.user.username. I figured maybe this has to do with the email address entered overlapping with username, but as you can see in my accounts model--the username is created from the email. (Note the entire User and User Profile models are not being utilized throughout my site yet, but just preparing for future usage). Any help is appreciated. Thanks Traceback (most recent call last): File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 149, in get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 147, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\crstu\PycharmProjects\dealmazing\dealmazing\views.py", line 15, in newsletter_signup instance.save() File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\contrib\auth\base_user.py", line 74, in save super(AbstractBaseUser, self).save(*args, **kwargs) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 708, in save force_update=force_update, update_fields=update_fields) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 736, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 820, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\base.py", line 859, in _do_insert using=using, raw=raw) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\manager.py", line 122, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\query.py", line 1039, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\models\sql\compiler.py", line 1060, in execute_sql cursor.execute(sql, params) File "C:\Users\crstu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\utils.py", … -
form.is_valid always return false
form.is_valid in views.py always return false. I have used Django forms to create a form and html to implement it. I will upload this photo to imgur using imgurpython later but first this should work. help needed urgently. views.py def upload_view(request): usr = check_validation(request) if usr: if request.method == "GET": form = PostForm() return render(request, 'upload.html', {'form': form}) elif request.method == "POST": form = PostForm(request.POST, request.FILES) if form.is_valid(): pic = form.cleaned_data['image'] title = form.cleaned_data['caption'] post = PostForm(caption=title, image=pic, user=usr) post.save() return redirect('feed/') else: return render(request, 'upload.html', {'error_msg' : "Invalid Inputs"}) else: return redirect('/login/') models.py class Post(models.Model): user = models.ForeignKey(User) image = models.FileField(upload_to='user_images') caption = models.CharField(max_length=240) image_url = models.CharField(max_length=255) created_on = models.DateTimeField(auto_now_add=True) forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = ['user', 'image', 'caption'] template - upload.html <form method="post" enctype="multipart/form-data" class="loginbox" style="margin-top:200px;"> {% csrf_token %} <p class="text-16">Upload to aperture.</p> <input type="file" accept="image/*" value="{{ image }}" name="image" class="login-btn"/><br/> <input placeholder="Caption" class="input-default all-curve" rows="3" value="{{ caption }}" name="caption" /> <p class="text-16">{{ error_msg }}</p> <input class="login-btn" type="submit" value="Upload"/> </form> -
Build Docker image from GitHub repository
I'm trying to build docker image from a GitHub repository using docker api python client. Here's what I have tried: From views.py if request.method == 'POST': post_data = request.POST.copy() post_data.update({'user': request.user.pk}) form = TarFromGithubForm(post_data) if form.is_valid(): deployment = gitHubModel() deployment.name = form.cleaned_data['name'] deployment.user = request.user deployment.archive = form.cleaned_data['archive'] dpath = deployment.archive print(deployment.archive) deployment.save() tag = deployment.name.lower() client = docker.from_env() client.images.build(path=dpath, tag=tag) messages.success(request, 'Your deployment from github repository has been created successfully!') return HttpResponseRedirect(reverse('users:deployments:repo')) Here in archive input field user will provide github repository url. it throws an error: APIError at /user/deployment/new/github 500 Server Error: Internal Server Error ("error detecting content type for remote https://github.com/Abdul-Rehman-yousaf/testing: unsupported Content-Type "text/html; charset=utf-8"") Request Method: POST Request URL: http://127.0.0.1:8000/user/deployment/new/github Django Version: 1.11.3 Exception Type: APIError Exception Value: 500 Server Error: Internal Server Error ("error detecting content type for remote https://github.com/Abdul-Rehman-yousaf/testing: unsupported Content-Type "text/html; charset=utf-8"") Exception Location: /Users/abdul/IstioVirEnv/lib/python3.6/site-packages/docker/errors.py in create_api_error_from_http_exception, line 31 Python Executable: /Users/abdul/IstioVirEnv/bin/python Python Version: 3.6.1 -
Server Error (500) ubuntu nginx django how to fix?
i make everything by his tutorial http://michal.karzynski.pl/blog/2013/06/09/django-nginx-gunicorn-virtualenv-supervisor/ but nothing work, but in procces this tutor i have no any errors! if you have some ideas how to fix this piece of shit, pls help me, cause i'm already is burnnnnnnnnn this is NGINX CONFIG upstream new_studio_app_server { # fail_timeout=0 means we always retry an upstream even if it failed # to return a good HTTP response (in case the Unicorn master nukes a # single worker for timing out). server unix:/webapps/new_studio_app/run/gunicorn.sock fail_timeout=0; } server { listen 80; server_name example.com; client_max_body_size 4G; access_log /webapps/new_studio_app/logs/nginx-access.log; error_log /webapps/new_studio_app/logs/nginx-error.log; location /static/ { alias /webapps/new_studio_app/new_studio/static/; } location /media/ { alias /webapps/new_studio_app/new_studio/media/; } location / { # an HTTP header important enough to have its own Wikipedia entry: # http://en.wikipedia.org/wiki/X-Forwarded-For proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # enable this if and only if you use HTTPS, this helps Rack # set the proper protocol for doing redirects: # proxy_set_header X-Forwarded-Proto https; # pass the Host: header from the client right along so redirects # can be set properly within the Rack application proxy_set_header Host $http_host; # we don't want nginx trying to do something clever with # redirects, we set the Host: header above already. proxy_redirect off; # set … -
Customize Json Response in django rest framework
Given below is my serializer class. I have all fields in one model.I would like to change the representation of serializer data in custom format. Tried to_representation method of serializer but could not success. class MyListSerilizer(ModelSerializer): class Meta: model=MyModel fields=['Name','Address_ID','Portal','Address','City','DisplayOrderDateTime','Email','Order_ID','Order_Code','Item_Code','DispatchedOn','Payment_Mode','Shipping_Charge','ShippingMethodCode','ShippingMethodCharges','CashOnDeliveryCharges','CurrencyCode','BillingAddress','GiftWrapCharges','SaleOrderItemCode','Shipping_ref','Cancellable','OnHold','Quantity','Invoice_No''Portal',........] So in my view class defined and output corresponding to them also mentioned over here. class MyListAPIView(ListAPIView): def list(self,request): queryset=MyModel.objects.all() serializer=MyListSerilizer(queryset,many=True) return Response({'Records':serializer.data}) Output :---------->Corresponding to view is "Records": [ { "Name": "abc", "Address_ID": "6819319", "Portal": "amksl", "Address": "", "City": "absjsls", "DisplayOrderDateTime": null, "Email": "abcd@gmail.com", "Order_ID": "", "Order_Code": "", "Item_Code": "", "DispatchedOn": "", "Payment_Mode": "" }, { "Name": "abc", "Address_ID": "6819319", "Portal": "amksl", "Address": "", "City": "absjsls", "DisplayOrderDateTime": null, "Email": "abcd@gmail.com", "Order_ID": "", "Order_Code": "", "Item_Code": "", "DispatchedOn": "", "Payment_Mode": "" }, so on.... so my question is how would i achieve this json format. In short how do i customize my view class "identifiers":{ "email":"abcd@gmai.com", "phone":"123664" }, "activity_type": "purchase", "timestamp": "UNIX TIMESTAMP", "products": [{ "brandName": "abc", "id": "1", "sku": "abcd", "name": "mnis", "price": 12.9, "discount": "", "quantity": "", "currency": "" }] "cart_info":{ "total":"", "revenue":"", "currency":"" }, "Order_info":{ "total":"2121", . . . -
how to change dynamically select option list on the basis of previous selection in django without page loading
I have three field State -> District -> Places. Data should appear in this sequence. Like This Image. How can i achieve this in django. Data should comes from default db