Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python django manage.py runserver hangs without error
I am try run a project with virtualenv and django Intried before python manage.py runserver Its stuck same line witout error,output or traceback On ctrl-c quiting without error If i try with python manage.py runserver --noreload Same stuck same line but if i use ctrl-c server begin work Second ctrl-c quiting What can be problem? Pls help -
How to deploy Django + Channels + Vuejs + Websocket, with Nginx and Gunicorn?
I'm new to deployment app. I deployed a Django app with Vue as frontend-framework using Nginx and Gunicorn, as there are a lot of online tutorials. For deployment, I simply created configurations files for both Nginx(in path/to/site-enable/) and Gunicorn(a shell script to start the service). I added Django Channels to the app (connected to a localhost redis server), and am able to run it on Django's development server. But then I ran into another issue, how to modify those corresponding files for deployment? Appreciate any help. -
NoReverseMatch at /cart/remove/5/
This is my code. when i am not write path('remove/<int:product_id>/', views.cart_detail, name='cart_remove'),in urls.py it work fine but when i write this above code it gives me error like this Reverse for 'cart_add' with arguments '('',)' not found. 1 pattern(s) tried: ['cart\/(?P[0-9]+)\/$'] urls.py from django.urls import path from . import views app_name = 'cart' urlpatterns = [ path('<int:id>/', views.cart_add, name='cart_add'), path('remove/<int:product_id>/', views.cart_detail, name='cart_remove'), path('detail/', views.cart_detail, name='cart_detail'), ] views..py def cart_add(request, id): if request.method == 'POST': cart_form = CartAddProductForm(request.POST) if cart_form.is_valid(): if not cart_form.cleaned_data['update']: product_id = str(id) session = request.session cart = session.get(settings.CART_SESSION_ID) if not cart: cart = request.session[settings.CART_SESSION_ID]={} if product_id in cart: cart[product_id]['quantity'] = cart_form.cleaned_data['quantity'] else: cart[product_id] = {'quantity': cart_form.cleaned_data['quantity']} session[settings.CART_SESSION_ID] = cart session.modified = True else: pass return redirect('shop:product_list') def cart_detail(request, product_id=None): cart_item = request.session.get(settings.CART_SESSION_ID) total_price = 0 if not product_id: add = [k for k in cart_item.keys()] for key in add: product_id = int(key) product = get_object_or_404(Product, id=product_id) total_price_per_item = cart_item[key]['quantity'] * product.price cart_item[key]['product'] = product cart_item[key]['total_price_per_item'] = total_price_per_item cart_item[key]['update_quantity_form'] = CartAddProductForm( initial={'quantity': cart_item[key]['quantity'], 'update': True}) total_price += total_price_per_item else: if product_id in cart_item: del cart_item[product_id] return render(request, 'cart/detail.html', {'cart': cart_item, 'total_price': total_price}) detail.html <td> <form action="{% url 'cart:cart_add' product.id %}" method="post"> {{ item.update_quantity_form.quantity }} {{ item.update_quantity_form.update }} <input … -
How to edit following Django Moellform
new to django. I am building a form for user to save to the database. the save to database part is working. However, I want to be able to view and edit the data on two separate template. let's call them view_self_eval.html and edit_self_eval.html. I am stuck. following is my could for Models.py, Forms.py and View.py for the particular form Models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.forms import ModelForm class self_eval(models.Model): Owner = models.OneToOneField(User, on_delete=models.CASCADE, default=None) First_Name = models.CharField(max_length=100, default=None) Last_Name = models.CharField(max_length=100, default=None) Current_Role = models.CharField(max_length=100) My_Strengths = models.CharField(max_length=1000) Improvement = models.CharField(max_length=4000) Goals = models.CharField(max_length=4000) Profesional_Certification = models.CharField(max_length=4000) Important_discussion = models.CharField(max_length=4000) def __str__(self): return self.Owner.username def create_self_eval(sender, **kwargs): if kwargs['created']: self_eval = self_eval.objects.create(user=kwargs['instance']) post_save.connect(create_self_eval, sender=User) Forms.Py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm, UserChangeForm from accounts.models import self_eval class SelfEvalForm(forms.ModelForm): class Meta: model = self_eval fields=( 'First_Name', 'Last_Name', 'Current_Role', 'My_Strengths', 'Improvement', 'Goals', 'Profesional_Certification', 'Important_discussion' ) def save(self, commit=True): self_eval = super(SelfEvalForm, self).save(commit=False) self_eval.First_Name = self.cleaned_data['First_Name'] self_eval.Last_Name = self.cleaned_data['Last_Name'] self_eval.Current_Role = self.cleaned_data['Current_Role'] self_eval.My_Strengths = self.cleaned_data['My_Strengths'] self_eval.Improvement = self.cleaned_data['Improvement'] self_eval.Goals = self.cleaned_data['Goals'] self_eval.Profesional_Certification = self.cleaned_data['Profesional_Certification'] self_eval.Important_discussion = self.cleaned_data['Important_discussion'] if commit: self_eval.save() return self_eval Views.py from django.shortcuts import render, … -
Django post_delete: count all objects which have one matching attribute with deleted object
I have a custom function which is called when deleting an object of the Model Orders, I use post_delete for this. An instance of the model "Orders" always have the ForeignKey "user". When deleting an object of the model "Orders", I want to check whether there are other instances of the model "Orders" with the same "user". def delete_reverse(sender, **kwargs): try: if Orders.objects.filter(user__equal=kwargs['instance'].user).count() == 1: kwargs['instance'].user.delete() else: ... except: pass post_delete.connect(delete_reverse, sender=Orders) Unfortunately, the if condition is not working, i.e. it is not true even when the count of according entries should be 1. Do you see any issue with my count() function? -
Undefined name in function
undefined name 'cleaned_data' what am I doing wrong here? code: def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.first_name = cleaned_data['first_name'] user.last_name = cleaned_data['last_name'] user.email = cleaned_data['email'] if commit: user.save() return user -
Django; widget-tweaks does't show error as expected
I'm creating form using widget-tweaks but it doesn't show error messages as expected. My form template is like this <div class="form-group"> {{ form.description.errors }} <label>{{ form.description.label }}</label> {{ form.description|add_class:'form-control' }} </div> But the error message doesn't show up on the form. Instead it shows up like this picture What am I wrong with it? -
Displaying a text field along with radio through Django form
Lets say I have a model with 2 fields. With one field being a choice field of radio button Choice1, Choice2 and Other, the next being Other which is a textfield I want the "other" textbox to appar / enabled only when "Other" is selected in the radio button. -
Django - Object of type Decimal is not JSON serializable
rows = fetchall() resultList = [] resultModel = [] resultDict = [] for row in rows: resultModel.append(ResultModel(*row)) # Object of type ResultModel is not JSON serializable resultList.append(list(row)) # Rows returned by pyodbc are not JSON serializable resultDict.append(dict(zip(columns, row))) # Object of type Decimal is not JSON serializable I need to get a json version of the data in the view. For this, I am trying to get the JSON dump of the data. Using json.dumps(resultDict) throws the error. The errors trying different results from the model is commented out for reference. The dict(zip()) option is the closest to what I want resultDict gives me a JSON (key, value) pairing that I can use. But it gives me an error on the resulting data that includes 'DecimalField' Is there a way to have decimal places without erroring on the data returned back? It seems that this would be a simple thing Django would support, so I'm not sure if I am missing something! https://github.com/pyeve/eve-sqlalchemy/issues/50 -
How to configure nginx to properly serve mp4 videos to Safari?
I'm attempting to use a video tag to display video in safari. Here is my snippet of html: <video autoplay="" muted="" loop="" preload="auto" poster="http://my.ip.add.ress/static/my_video_image.jpg"> <source src="http://my.ip.add.ress/static/my_video.mp4" type="video/mp4" /> <source src="http://my.ip.add.ress/static/my_video.webm" type="video/webm" /> </video> The static files (css, js, images) are being served up properly. The problem I run into is when safari requests the video, nginx is supposed to return a 206 partial content response. However, it returns a 200 OK with the whole video (I think the whole file is returned). But safari didn't request the whole video, it requested a range of the video using the range header. So this causes the video to not play in Safari. As it sits, my current setup works in Chrome and Firefox. I'm using nginx to serve the video content. I'd like to avoid using a 3rd party server as this is for a small project :). My question is how do I properly setup nginx to serve videos to safari? I know that nginx is ignoring the range header in the request. Is there a way to tell nginx to pay attention to that header? Here is my nginx config in /etc/nginx/sites-available/myproject: server { listen 80; server_name my.ip.add.ress; location = … -
Django Rest Framework failing to patch Serializer.data in view test
I'm unit testing a view and I am attempting to patch the .data property on my serializer but it looks like it behaves differently when the many=True kwarg is passed to the serializer constructor and thus not properly patching. Here is a generalized example of my code. # myapp/serializers.py class MySerializer(serializers.Serializers): some_field = serializers.CharField() # myapp/views.py class MyView(View): def get(self, request): # ..stuff some_data = [] serializer = MySerializer(some_data, many=True) print(type(serializer)) # <class 'rest_framework.serializers.ListSerializer'> print(type(serializer.data)) # <class 'rest_framework.utils.serializer_helpers.ReturnList'> return Response({"data": seralizer.data, status=200}) # in tests def test_view_case_one(mocker): # setup other mocks serialized_data = mocker.patch("myapp.views.MySerializer.data", new_callable=mocker.PropertyMock) # invoke view response = MyView().get(fake_request) # run assertions serialized_data.assert_called_once() # this says it's never called -
relation "auth_user" does not exist in django with multiple database migrate working but not script
So here is may settings.py : DATABASE_ROUTERS = ['AdminNotationIngredient.dbRouters.AuthRouter'] DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql", "NAME": "Sledge1", "USER": "Orson", "PASSWORD": "RoseBud", "HOST": "192.168.1.1915", # Or an IP Address that your DB is hosted on #"OPTIONS": {"sslmode": "require"}, }, 'auth_db': { "ENGINE": "django.db.backends.postgresql", "NAME": "Sledge2", "USER": "Orson", "PASSWORD": "RoseBud", "HOST": "192.168.1.1915", # Or an IP Address that your DB is hosted on #"OPTIONS": {"sslmode": "require"}, }, } here is my router : class AuthRouter: """ A router to control all database operations on models in the auth application. """ def db_for_read(self, model, **hints): """ Attempts to read auth models go to auth_db. """ label = ['auth','admin'] if model._meta.app_label in label : return 'auth_db' return 'default' def db_for_write(self, model, **hints): """ Attempts to write auth models go to auth_db. """ label = ['auth', 'admin'] if model._meta.app_label in label : return 'auth_db' return 'default' def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the auth app is involved. """ label = ['auth', 'admin'] if obj1._meta.app_label in label or \ obj2._meta.app_label in label : return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): """ Make sure the auth app only appears in the 'auth_db' database. """ label = ['auth', … -
Troubleshooting HTTP request and JSON message on Django
Okay, so I have been going at this for a while and it doesn't seem like I am getting anywhere. I am running a Django app with Nginx and uwsgi. I have an http.post and I am trying to even read the items which I keep getting errors for. This is what my JS code looks like : $scope.receipt_pay_update = function(items) { response = confirm("Do you want to continue with the changes?"); if(!response){ return; } var data = { 'items': items, 'time_now': moment().format("YYYY-MM-DD") }; items.showmessage = true; console.log(data) $http.post("/foodhub/dashboard/receipt_pay_modal_update", data,{ data: JSON }). success(function(data,status,headers,config){ $scope.alertclass = 'alert-success'; $scope.save_message_farmer = "Succcessfully update payment" console.log("SAVED!") }). error(function(data,status,headers,config){ $scope.alertclass = 'alert-danger'; $scope.save_message_farmer= "Failed to update inventory, please try again" }) } This is what my views.py looks like: @login_required def receipt_pay_modal_update(request): import sys reload(sys) sys.setdefaultencoding('utf8') data = json.loads(request.body)['items'] print data rec = ReceiverActions.objets.get(identifier = data[0]['identifier']) rec['paid_check'] = data[0]['paid_status'] rec['date_paid'] = data[0]['paid_date'] rec.save() return HttpResponse(status=status.HTTP_200_OK) I got an error of unable to decode JSON. So I tried `data = request.body[0] which also didn't work. Is there any other way I could be testing small changes on my server without having to do the Git push, Git Pull, Python -m compileall ., etc? The reason … -
csrf token verification error (403) when I try to login as admin since I upgraded django from 1.11 to 2.1.1?
I guess I have to make some changes in the settings file regarding csrf_tokens but where ? Please help. Here is my code for urls.py in the main application from django.contrib import admin from django.conf.urls import url, include urlpatterns = [ #Admin section url url('^admin/', admin.site.urls), #Music section url url('^music/', include('music.urls')), ] And the code for settings.py file in the main application """ Django settings for TestMe_App project. Generated by 'django-admin startproject' using Django 2.1.1. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '1d!vux17gbzi_ux75mu4h1r+*bd+**b6bjpk9^twk0$z)1z57i' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'music', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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 = 'TestMe_App.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', … -
Database System Solutions
What are the best programming languages or tools to design database system that let group of employees work in one database and finally could generate reports of excel file contains all data provided by them. I need solution for all MVC layers, no matter if it is web-based or desktop application. -
rendere form with select django
I have a django form generated by a model. class Manager(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) gender = models.CharField(max_length=50) birth_date = models.DateField() phone_number = models.CharField(max_length=10) region_of_residence = models.CharField(max_length=50) city_of_residence = models.CharField(max_length=50) common_of_redidence = models.CharField(max_length=50) address_of_residence = models.CharField(max_length=50) zip_of_residence = models.CharField(max_length=50) username = models.CharField(max_length=20) email = models.CharField(max_length=200) password = models.CharField(max_length=100) def __str__(self): return self.username i've created a form to overwrite some fields and add other one in this way: class ManagerForm(forms.ModelForm): gender = forms.ChoiceField(choices=GENDER_CHOICES) password = forms.CharField(widget=forms.PasswordInput()) verify_password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = Manager fields = ('first_name', 'last_name', 'gender', 'birth_date', 'phone_number', 'region_of_residence', 'city_of_residence', 'common_of_redidence', 'address_of_residence', 'zip_of_residence', 'username', 'email', 'password',) def clean(self): cleaned_data = super(ManagerForm, self).clean() password = cleaned_data.get("password") verify_password = cleaned_data.get("verify_password") if password != verify_password: raise forms.ValidationError( "password and verify_password does not match" ) I've put my choice into an external file and they are: GENDER_CHOICES = [ _('Non specificato'), _('Uomo'), _('Donna') ] now i've would like to render my form with a simple for statement {% for field in form %}{{% render_field field class="form-control" %}. But i receive the follow error: ValueError: too many values to unpack (expected 2) how can i render correctly these fields? -
Django; redirect doesn't work as expected when using ajax
I'm creating delete function using ajax. redirect doesn't work as expected. js function deleteEntry(entry) { var id = $entry.data('id') $.ajax({ url:'/blog/delete/' + id, method: 'DELETE', beforeSend: function(xhr) { xhr.setRequestHeader('X-CSRFToken', csrf_token) } }) } } views.py def delete_entry(request, pk): if request.method == 'DELETE': entry = get_object_or_404(Entry, id=pk) entry.delete() messages.success(request, 'Your post has been deleted successfully.') return HttpResponseRedirect(reverse_lazy('blog:list_entry')) command line is like this when doing the function [13/Sep/2018 16:06:02] "DELETE /blog/delete/14 HTTP/1.1" 302 0 [13/Sep/2018 16:06:02] "DELETE /blog/list HTTP/1.1" 200 9878 [13/Sep/2018 16:06:02] "GET / HTTP/1.1" 200 10605 I want to make the page redirect to blog/list but the page redirects to /. How can I fix this? -
No module found 'corsheaders' django/heroku deploy
None of the other answers have worked for me. Ive done pipenv install django-cors-headers, pipenv install psycopg2-binary, etc. until my fingers have blisters to no avail... This is going to be a bit long if you don't mind looking; thanks in advance... *settings.py* # Application definition INSTALLED_APPS = [ 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'quizzes', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] This is the Pipfile on the proper level... [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [requires] python_version = "3.6" [packages] python-decouple = "*" "psycopg2" = "*" django-dotenv = "*" gunicorn = "*" whitenoise = "*" dj-database-url = "*" djangorestframework = "*" django = "*" django-cors-headers = "*" "psycopg2-binary" = "*" [dev-packages] But I am still getting traceback line 17 from ./manage.py and ultimately No module named 'corsheaders'... I've uninstalled/reinstalled and everything. Anyone got any ideas? -
This was likely an oversight when migrating to django.urls.path()
I wrote this code on pycharme in file urls.py : from teams.views import HomePageView urlpatterns = [ path('admin/', admin.site.urls), path(r'^$',HomePageView.as_view(), name='home page'), ] and when I opened the cmd and wrote "python manage.py runserver" ,appeared this: WARNINGS: ?: (2_0.W001) Your URL pattern '^$' [name='home page'] has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path(). -
Connecting Django to Postgres: django.db.utils.OperationalError: FATAL: database "DATABASENAME" does not exist
I have just started learning Django after I took some tutorials for Python. I am trying to connect my POSTGRES database to the Django project I have just created. However, I am experiencing this problem: django.db.utils.OperationalError: FATAL: database "producthuntdb" does not exist I followed these steps: 1) Opened postgress by clicking its icon 2) Clicked on the database "postgress". The terminal opened and I wrote: CREATE DATABASE producthuntdb; The database has been created because I see it if I open postgress via its icon. 3) Went to my Django project in "settings" and change the SQLITE database to the following: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'producthuntdb', 'USER': 'postgres', 'PASSWORD': 'mypassword', 'HOST': 'localhost', 'PORT': '5432', } } 4) Run the code python3 manage.py migrate However, I am getting the error: django.db.utils.OperationalError: FATAL: database "producthuntdb" does not exist What am I doing wrong? I tried to look other answers to this problem and most of the issues are from misspelling the database name OR not creating it. However, the name of my database is correct and I can see the database producthuntdb if I open postgres. Many thanks for your help. -
I'm trying to setup django on my system and had a problem with DB migration using XAMP
The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in execute_from_command_line(sys.argv) File "/home/vishal/anaconda3/lib/python3.6/site-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/home/vishal/anaconda3/lib/python3.6/site-packages/django/core/management/init.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/vishal/anaconda3/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/home/vishal/anaconda3/lib/python3.6/site-packages/django/core/management/base.py", line 350, in execute self.check() File "/home/vishal/anaconda3/lib/python3.6/site-packages/django/core/management/base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "/home/vishal/anaconda3/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 59, in _run_checks issues = run_checks(tags=[Tags.database]) File "/home/vishal/anaconda3/lib/python3.6/site-packages/django/core/checks/registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "/home/vishal/anaconda3/lib/python3.6/site-packages/django/core/checks/database.py", line 10, in check_database_backends issues.extend(conn.validation.check(**kwargs)) File "/home/vishal/anaconda3/lib/python3.6/site-packages/django/db/backends/mysql/validation.py", line 9, in check issues.extend(self._check_sql_mode(**kwargs)) File "/home/vishal/anaconda3/lib/python3.6/site-packages/django/db/backends/mysql/validation.py", line 13, in _check_sql_mode with self.connection.cursor() as cursor: File "/home/vishal/anaconda3/lib/python3.6/site-packages/django/db/backends/base/base.py", line 255, in cursor return self._cursor() File "/home/vishal/anaconda3/lib/python3.6/site-packages/django/db/backends/base/base.py", line 232, in _cursor self.ensure_connection() File "/home/vishal/anaconda3/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/home/vishal/anaconda3/lib/python3.6/site-packages/django/db/utils.py", line 89, in exit raise dj_exc_value.with_traceback(traceback) from exc_value File "/home/vishal/anaconda3/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/home/vishal/anaconda3/lib/python3.6/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/home/vishal/anaconda3/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 227, in get_new_connection return Database.connect(**conn_params) File "/home/vishal/anaconda3/lib/python3.6/site-packages/pymysql/init.py", line 94, in Connect return Connection(*args, **kwargs) File "/home/vishal/anaconda3/lib/python3.6/site-packages/pymysql/connections.py", line 327, in init self.connect() File "/home/vishal/anaconda3/lib/python3.6/site-packages/pymysql/connections.py", line 598, in connect self._request_authentication() File "/home/vishal/anaconda3/lib/python3.6/site-packages/pymysql/connections.py", line 862, in _request_authentication auth_packet = self._process_auth(plugin_name, auth_packet) File "/home/vishal/anaconda3/lib/python3.6/site-packages/pymysql/connections.py", line 933, in _process_auth pkt = self._read_packet() File "/home/vishal/anaconda3/lib/python3.6/site-packages/pymysql/connections.py", … -
I need help in using populartime as django REST api to use in ionic
I'm new in python & Django and i need to use Populartime repo https://github.com/m-wrzr/populartimes as API to work with in my ionic application put i didn't found the way yet? i tried to create Django $project and create $app put how to include Populartime and use it as API this is the project i have create and i tried to use the Populartime as a module put didn't no how to use it later -
Django - Adding fields to a ModelForm that inherits from a parent modelform?
ex. model = Foo Foo.fields(a,b,c,d) FooModelForm1(forms.Modelform): fields = [a, b, c] etc. FooModelForm2(FooModelForm1): fields = [d] As you can see all 4 fields exist in the model but FooModelForm1 is using only 3 fields while i want FooModelForm2 to include field [d] as well as the others. In the documentation it explains you can exclude fields so I know one option would be to flip my forms and include field [d] initially but I was curious if the opposite was possible. I have seen responses that modifies the Meta data from FooModelForm2 but that doesnt seem to be working for me such as: class Meta(FooModelForm1.Meta): fields = ReqLineForm.Meta.fields + ('d',) -
didn't return an HttpResponse object. It returned None instead
The view accounts.views.register didn't return an HttpResponse object. It returned None instead. The code: views.py def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() return 'redirect' ('account') else: form = UserCreationForm() args = {'form': form} return render(request, 'accounts/reg_form.html', args) urls.py url(r'^register$', views.register, name='register') -
Django Template : Combine 2 loops over different lists
I'm wondering how I can combine these 2 querysets in my template in order to loop over them. requests = Download.objects.values('pub__edqm_id').annotate(count=Count('pub__edqm_id')) max_download_number = Download.objects.values('pub__edqm_id').annotate(max_usage=Max('usage')) context = {'requests': requests, 'max_download_number': max_download_number} In my template : {% for item in requests %} {% for element in max_download_number %} <tr> <td>{{ item.pub__edqm_id }}</td> <td><span class="badge alert-info">{{ item.count }}</span></td> <td>{{ element.max_usage }}</td> <td>Something</td> </tr> {% endfor %} {% endfor %} It displays wrong loops :