Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to connect MySQL with django in windows
I am trying to connect MySQL with django. After creating a workbench model in MySQL i tried to connect it with django using the command, pip install django mysqlclient when i run this script i am getting the error code, Collecting django Using cached https://files.pythonhosted.org/packages/ab/15/cfde97943f0db45e4f999c60b696fbb4df59e82bbccc686770f4e44c9094/Django-2.0.7-py3-none-any.whl Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/ec/fd/83329b9d3e14f7344d1cb31f128e6dbba70c5975c9e57896815dbb1988ad/mysqlclient-1.3.13.tar.gz Requirement already satisfied: pytz in c:\users\ashfak.ka\appdata\local\programs\python\python36\lib\site-packages (from django) (2018.4) Building wheels for collected packages: mysqlclient Running setup.py bdist_wheel for mysqlclient ... error Complete output from command c:\users\ashfak.ka\appdata\local\programs\python\python36\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\ashfak.ka\\AppData\\Local\\Temp\\pip-install-ipkxke0a\\mysqlclient\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d C:\Users\ashfak.ka\AppData\Local\Temp\pip-wheel-43ti3_ny --python-tag cp36: c:\users\ashfak.ka\appdata\local\programs\python\python36\lib\distutils\dist.py:261: UserWarning: Unknown distribution option: 'long_description_content_type' warnings.warn(msg) running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.6 copying _mysql_exceptions.py -> build\lib.win-amd64-3.6 creating build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\__init__.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\compat.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\connections.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\converters.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\cursors.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\release.py -> build\lib.win-amd64-3.6\MySQLdb copying MySQLdb\times.py -> build\lib.win-amd64-3.6\MySQLdb creating build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win-amd64-3.6\MySQLdb\constants copying MySQLdb\constants\REFRESH.py -> build\lib.win-amd64-3.6\MySQLdb\constants running build_ext building '_mysql' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools ---------------------------------------- Failed building wheel for mysqlclient … -
Restful CRUD API for wagtail
In wagtail, it provides some good Restful API for fetch contents via HTTP GET method. See document: http://docs.wagtail.io/en/v2.0/advanced_topics/api/v2/configuration.html However, when I want to Update/Add/Remove the contents, I cannot find any Restful API to do this. And in its document, it doesn't mention anything about this. So what should I do to implement the Update/Add/Remove Restful API for wagtail? -
Adding Progress bar in Django by fetching percent from a URL
I am trying to implement a progress bar that shows the percentage completed of a task. The percentage completed can be fetched by a POST request. The URL is http://127.0.0.1:8000/checkScanStatus and the parameter contains csrfmiddlewaretoken and a userInstance. This return a JSON response in the form {"Spider":20}. I want to continuously trigger this URL, get the response and display it in progress bar. I have completed the Django part, I need help on how to implement the progress bar for this in HTML, JS, JQuery or AJAX . Here is the HTML code I am trying <script type="text/javascript"> $(document).on('submit','#scanForm', function(e){ e.preventDefault(); // This AJAX request is for my main task submission $.ajax({ type: 'POST', url: '/scanner/', data: { email: $('#email').val(), context: $('#context').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), uniqueUserInstance:$('input[name=uniqueUserInstance]').val(), }, success:function(response){ alert('Scan Completed'); location.reload(); } }); //Here I want the AJAX call to fetch response and display it in progress bar $.ajax({ type: 'POST', url: '/scanner/checkScanStatus', data: { userInstance : $('input[name=uniqueUserInstance]').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, success:function(response){ //What to code here. I want this function to trigger continuously until response is 100% } }); }); Thanks -
Django test parallel AppRegistryNotReady
I am trying to understand how I can run django tests in parallel. I have django app with that structure: gbook order ... tests __init__.py test_a1.py test_b1.py utils.py test_a1.py and test_b1.py contains same code: import time from order import models from .utils import BackendTestCase class ATestCase(BackendTestCase): def test_a(self): time.sleep(1) a = models.City.objects.count() self.assertEqual(a, a) class BTestCase(BackendTestCase): def test_b(self): time.sleep(1) a = models.City.objects.count() self.assertEqual(a, a) utils.py is: from django.test import TestCase, Client from order import models from django.conf import settings from order.utils import to_hash class BackendTestCase(TestCase): fixtures = ['City.json', 'Agency.json'] def setUp(self): self.client = Client() self.lang_codes = (i[0] for i in settings.LANGUAGES) ... settings_test.py: from .settings import * DEBUG = False TEMPLATE_DEBUG = False STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' PASSWORD_HASHERS = ['django.contrib.auth.hashers.MD5PasswordHasher',] # faster DATABASES['default'] = { 'ENGINE': 'django.db.backends.sqlite3', } When I run test in single process, all goes well (about 4 sec): python.exe manage.py test order --settings=gbook.settings_test Then I trying to run tests in parallel: python.exe manage.py test order --settings=gbook.settings_test --parallel=2 I get this trace: Creating test database for alias 'default'... Cloning test database for alias 'default'... Cloning test database for alias 'default'... System check identified no issues (0 silenced). Process SpawnPoolWorker-2: Process SpawnPoolWorker-1: Traceback (most recent call last): Traceback (most recent … -
ImageField not working for Django version 2.0.4
I am using Django version 2.0.4 but I am facing a problem with models.ImageField. Whenever I try to update an existing image with a new one, nothing happens. Also when I try to clear the image, nothing happens. I have all the dependencies installed like Pillow. I have declared my ImageField as usual like - class Community(models.Model): image = models.ImageField( upload_to=upload_location, null=True, blank=True, width_field="width_field", height_field="height_field", help_text="A image representing the Community") height_field = models.IntegerField(null=True, blank=True) width_field = models.IntegerField(null=True, blank=True) def __str__(self): return str(self.id) I have used ImageField before, but haven't ever faced such an issue ever. Is this a problem with the Django version? Should I consider upgrading my Django version? Thanks in advance -
Python 3.6 mysqlclient can't install
On installing mysqlclient, the error is follows; error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools I downloaded and installed Visual C++ and C++ build tools but mysqlclient still can't install and the error message is showing again as mentioned above. Does it need to configure something in computer? -
Django Attribute error in request object
I have a view function in views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from .utils import handler, add_to_template, get_template from django.http import JsonResponse import json @login_required def save_template(request): if 'template' in request.POST: temp = get_template(request.POST['template'],request.user.id) if temp is not None: obj = handler() table = json.loads(request.POST["table"]) for item in table: add_to_template(temp,item['item']) return JsonResponse({"message": "Template " + temp.name + " created!","type": "success"}); return JsonResponse({"message": "Uknown error occured!","type": "danger"}); The two utility functions get_template and add_template are defined in utils.py in the same folder. def get_template(template_name,cur_user): temp = None user = User.objects.get(id=cur_user) if template_name != '': if template.objects.filter(name=template_name).exists(): num = 1 new_name = template_name + '(' + str(num) + ')' while template.objects.filter(name=new_name).exists(): num = num + 1 new_name = template_name + '(' + str(num) + ')' temp = template(name=new_name,user=user) else: temp = template(name=template_name,user=user) temp.save() return temp def add_to_template(temp,cpe_id): if component.objects.filter(cpe_id=cpe_id).exists(): cpe = component.objects.get(cpe_id=cpe_id) elif component.objects.filter(wfs=cpe_id).exists(): cpe = component.objects.get(wfs=cpe_id) else: return -1 if not template_to_cpe.objects.filter(template=temp,cpe=cpe).exists(): t2c = template_to_cpe(template=temp,cpe=cpe) t2c.save() return 1 But when I run it I get the error : AttributeError: 'str' object has no attribute 'user' The stack trace is : Internal Server Error: /components/save_template Traceback (most recent call last): File "/root/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) … -
Trouble migrating to ElephantSQL
For my Django 2.0 project, I recently decided to switch from the default SQLite3 database to a more professional PostgreSQL database (hosted on ElephantSQL because I could not get it to work on my local server). I have been following along with this video to accomplish this. Changing the settings.py and then running migrate using manage.py seemed to work, but I cannot log users in or access the Django admin panel afterwards without getting "DataError at / ... invalid input syntax for integer:" I suspect this might be because I use a randomly generated 6-character string for all my models' primary keys after I read that PostgreSQL is strongly typed, since at one point I also got a type cast error from PostgreSQL. I have tried flushing my database and recreating the superuser to no avail. Listed below are the associated models I have in my project: class Profile(AbstractUser): id = models.CharField(max_length=6, primary_key=True, default=pkgen) GENDERS = (('M', 'Male'), ('F', 'Female'), ('O', 'Other')) gender = models.CharField(max_length=1, choices=GENDERS, default='M') userClubs = models.ManyToManyField(Club)` class Club(models.Model): id = models.CharField(max_length=6, primary_key=True, default=pkgen) title = models.CharField(max_length=100, default="foo") affiliation = models.CharField(max_length=100, default="foo") creator = models.CharField(max_length=61, default="foo") about = models.CharField(max_length=1000, default="foo") I have tried this post's solution and … -
Django form.errors not showing up in template
I have refrenced this stackoverflow page and tried to display my forms error on the html template. I did: {% if form.error %} {% for field in form %} {% for error in field.errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endfor %} {% for error in form.non_field_errors %} <div class="alert alert-danger"> <strong>{{ error|escape }}</strong> </div> {% endfor %} {% endif %} as said in the stackoverflow question I also tried simply doing: {% if form.error %} This should pop up if there is an error {% endif %} Nothing comes up regardless: Heres my view.py code: def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password2') user = authenticate(username=username, password=password) login(request, user) return HttpResponseRedirect('/') else: print(form.errors) form = UserCreationForm() return render(request, 'registration/register.html', {'form': form}) I am able to get the form errors onto the django console but it refuses to show up on the template. -
csrf token for ajax in django2
I am learning Django2,and try to make a login page with csrf_token and ajax. I hope that if user hasn't lgoin,that will turn to the login page and send a variable next as a tag of the page before login.If user login successfully that I can turn to the homepage or page marked by next. I read the docs of Django2, and try to code like below,however,when I click "LOGIN" button,it just refresh the login page and get an error AttributeError: 'NoneType' object has no attribute 'split' I am confused and have no idea already.Please help. login views: def login(request): if request.is_ajax(): uf = UserForm(request.POST) if uf.is_valid(): # get info from form username = uf.cleaned_data['username'] password = uf.cleaned_data['password'] user = auth.authenticate(request, username=username, password=password) if user is not None: # user match auth.login(request, user) if request.GET.get('next'): next_url = request.GET.get('next') return JsonResponse({'redirect_url': next_url}) # return redirect(request.GET.get('next')) else: return JsonResponse({'redirect_url': 'home'}) else: # user not match error_msg = ["username or pwd mistake"] return JsonResponse({'error_msg': error_msg}) else: uf = UserForm() return render(request, 'login.html', {'uf': uf}) html : <form> {% csrf_token %} {{ uf.username }} {{ uf.password }} <div id="errorMsg"></div> <button type="submit" class="btn btn-default" id="loginButton">login</button> <input type="hidden" name="next" id="redirect-next" value="{{ next|escape }}"/> </form> JQuery: $("#loginButton").click(function … -
ConnectionError at /test/DEF230548/
ConnectionError at /test/DEF230548/ HTTPConnectionPool(host=‘test’, port=80): Max retries exceeded with url: /test/DEF230548/ (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known',)) Error happens I am making Django app.Django version is 1.8 . I wrote in urls.py from django.conf.urls import url from app import views urlpatterns = [ url(r'^$', views.home, name=‘home’), url(‘test/(?P<id>[\w.-]+)/', views.test, name=‘test’), ] in views.py def home(request): ・ ・ ・ test(request,id) template = loader.get_template('top.html') return HttpResponse(template.render(request)) def test(request,id): try: dir_path = "static/data/“ print("HERE1") if not os.path.exists(dir_path): os.makedirs(dir_path) except requests.ConnectionError as e: print("HERE2") print(e) template = loader.get_template('data.html') return HttpResponse(template.render(request)) When I access http://127.0.0.1:8000/test/DEF230548/, the error happens. print("HERE1") is shown in terminal, but static/data/ is not made.Can’t I call 2 8000ports url?How should I fix this? -
Django rest framework- calling another class-based view
I have pored over several similar posts, but some are older and none quite work for me. Here's my setup (using Django==2.0.6, djangorestframework==3.8.2) I have a basic model (simplified here): from django.db import models class Resource(models.Model): name = models.CharField(max_length=100, null=False) I have a basic endpoint where I can list and create Resource instances: from rest_framework import generics, permissions from myapp.models import Resource from myapp.serializers import ResourceSerializer class ListAndCreateResource(generics.ListCreateAPIView): queryset = Resource.objects.all() serializer_class = ResourceSerializer permission_classes = (permissions.IsAuthenticated,) (afaik, the details of the serializer are not relevant, so that is left out). Anyway, in addition to that basic endpoint, I have another API endpoint which performs some actions, but also creates some Resource objects in the process. Of course, I would like to make use of the functionality encapsulated in the ListAndCreateResource class so I only have to maintain one place where Resources are created. I have tried: Attempt 1: class SomeOtherView(generics.CreateAPIView): def post(self, request, *args, **kwargs): # ... some other functionality... # ... response = ListAndCreateResource().post(request, *args, **kwargs) # ... more functionality... return Response({'message': 'ok'}) Unfortunately, that does not work for me. In my trace, I get: File "/home/projects/venv/lib/python3.5/site-packages/rest_framework/generics.py", line 111, in get_serializer kwargs['context'] = self.get_serializer_context() File "/home/projects/venv/lib/python3.5/site-packages/rest_framework/generics.py", line 137, … -
What is an effective method to get a Django class reference when there are duplicated class names in different modules?
I have a function that takes a class reference to create an SQL string. I can get the class reference from globals() as long as the class name is unique. Example call. module_name_a.models.get_insert_string(globals()['DriverShiftPreference']) If there are duplicate class names in different modules then I get collisions. For example, if there is module_name_a.models.Driver and module_name_b.models.Driver then module_name_a.models.get_insert_string(globals()['Driver']) returns a result from module_name_b.models.Driver. What is an effective method to get a Django class reference when there are duplicated class names in different modules? -
Creating JSON data from Django model spanning foreign key
I'm using D3 within my Django 2 templates to create plots and I'm not sure how best to create a JSON object which contains data from both a parent and child model. For example, these are my models: class Properties(models.Model): house_size = models.IntegerField(blank=True, null=True) class Prices(models.Model): price = models.IntegerField(default=0) house =models.ForeignKey(Properties,on_delete=models.CASCADE,default=0) I know that to create a JSON object from Prices I can do the following: statdump = json.dumps(list(Prices.objects.all()), cls=DjangoJSONEncoder) However what if I want to create a JSON object containing price and house_size. I can think of inefficient ways to solve this, for example iterating through the observations in the template and creating the JSON data there, but that doesn't seem very efficient. Is there a way that I could pass a JSON object from the view that contains house_size and price? Thanks in advance -
Djnago authenticate and Log into your own website
I have been having great difficulties understanding how to log into my own website. I have users registered in my database, I have created another ModelForm aside from the registration form. I just do not understand how the login view will check to see if the (email) & (password) is in the database and actually log the user in the main website area. Could someone give me a better explanation on how to check the database to see if the information is correct and log into your own website? NOTE: I am not looking for anything to do with admin.py or the admin page, this is what I seem to find a lot of information on. **********************************VIEWS.PY*********************************************** from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import redirect from django.views.generic.base import TemplateView from django.views.generic.edit import FormView from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.conf import settings from App1.models import RegisterForm, SignInForm, ModelRegister # Create your views here. class LoginView(FormView): template_name = 'App1//login.html' form_class_signin = SignInForm() success_url = '/Main-name/' login_url = '/login/' def get(self, request): form_class_signin = SignInForm() return render(request, 'App1/login.html', {'form_class_signin': form_class_signin}) def post(self, request): form_class_signin = SignInForm() return render(request, 'App1/login.html', {'form_class_signin': form_class_signin}) def … -
Create user in Django : User, Staff, SuperUser
I want to create and save a user with the given username, password, first name, last name and email such as simple user, staff and superuser in models.py and in the front end user can select whether it is simple user, staff or superuser because of some restrictions. Here is my code in models.py. After this code I get some System Check Error. class CustomUserManager(UserManager): def _create_user(self, username, email, password, **extra_fileds): if not username: raise ValueError('The given username must be set') email = self.normalize_email(email) username = self.model.normalize_username(username) user = self.model(username=username, email=email, **extra_fileds) user.set_password(password) user.save(using=self._db) return user def create_user(self, username, email=None, password=None, **extra_fileds): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(username, email, password, **extra_fileds) def create_superuser(self, username, email, password, **extra_fileds): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(username, email, password, **extra_fileds) class CustomUser(AbstractUser): username = models.CharField( _('username'), max_length=150, unique=True, help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'), # validators=[username_validator], error_messages={ 'unique': _("A user with that username already exists."), }, ) password = models.CharField(_('password'), max_length=128) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=150, blank=True) email = models.EmailField(_('email address'), blank=True) is_staff = … -
My update form submits and redirects to success view, but the model does not update - why is this?
I want to make it so players are able to RSVP for games. So far I can create an RSVP successfully, but when a player goes to edit their RSVP the form updates and redirects to success page, but the RSVP model does not update with it. Here are my RSVP and Game models: # RSVP class Rsvp(models.Model): rsvp_choices = RSVP_CHOICES user = models.ForeignKey('team.User', on_delete=models.CASCADE) game = models.ForeignKey(Game, on_delete=models.CASCADE) rsvp = models.CharField(max_length=100, choices= rsvp_choices, null=True, blank=True) comment = models.TextField(max_length=300, null=True, blank=True) plus_one = models.PositiveSmallIntegerField(null=True, blank=True, default=0) class Meta: ordering = ['rsvp', 'comment', 'plus_one'] def __str__(self): return str(self.rsvp) # Game class Game(models.Model): field_choices = FIELD_CHOICES team_choices = TEAM_CHOICES season = models.ForeignKey(Season, on_delete=models.CASCADE) team = models.CharField(max_length=100, null=True, blank=True, choices=team_choices, default='Flying Hellfish') opponent = models.CharField(max_length=100, null=True, blank=True, choices=team_choices) field = models.CharField(max_length=100, choices=field_choices, null=True) date = models.DateField(null=True, blank=True) time = models.TimeField(null=True, blank=True, default=datetime.time(9, 30)) team_score = models.PositiveSmallIntegerField(null=True, blank=True, default=0) opponent_score = models.PositiveSmallIntegerField(null=True, blank=True, default=0) tbd = 'TBD' win = 'W' draw = 'D' loss = 'L' result_choices = ( (tbd, 'TBD'), (win, 'W'), (draw, 'D'), (loss, 'L'), ) result = models.CharField( max_length=3, choices=result_choices, default=tbd, ) class Meta: ordering = ['team', 'opponent', 'field','team_score', 'opponent_score', 'result'] def __str__(self): return str(self.team) + ' vs. ' + str(self.opponent) … -
Taking *ANY csv column format into Django form
My code is currently hard coded to only accept csv files in the column format: first_name,last_name,phone,email,address,company However I would like users to be able to upload csv files that are in any* format order and correctly populate our forms. For example: Email,LastName,FirstName,Company,Phone,Address would be a valid column format. How would I go about doing that? Relevant code as follows: dr = csv.reader(open(tmp_file,'r')) data_dict = {} headers = next(dr) print (headers) #skips over first line in csv iterlines = iter(dr) next(iterlines) for row in iterlines: data_dict["first_name"] = row[0] #print(data_dict["first_name"]) data_dict["last_name"] = row[1] #print(data_dict["last_name"]) data_dict["phone"] = row[2] #print(data_dict["phone"]) data_dict["email"] = row[3] #print(data_dict["email"]) data_dict["address"] = row[4] #print(data_dict["address"]) data_dict["company"] = row[5] #print(data_dict["company"]) #adds to form try: form = AddContactForm(data_dict) if form.is_valid(): obj = form.save(commit=False) obj.owner = request.user.username first_name = form.cleaned_data.get(data_dict["first_name"]) last_name = form.cleaned_data.get(data_dict["last_name"]) phone = form.cleaned_data.get(data_dict["phone"]) email = form.cleaned_data.get(data_dict["email"]) address = form.cleaned_data.get(data_dict["address"]) company = form.cleaned_data.get(data_dict["company"]) obj.save() else: logging.getLogger("error_logger").error(form.errors.as_json()) except Exception as e: logging.getLogger("error_logger").error(repr(e)) pass -
AttributeError 'User' object has no attribute 'userStripe'
Using the Stripe API to create a credit card checkout form on my website. I am trying to test the following line in my view.py of the app checkout. print (request.user.userStripe.stripe_id) It could be the way my Users is set up.. I tried importing the models from the user app. I just don't understand why it can't see it. I have two apps: users and checkout I am the following error in the debug page AttributeError at /checkout/ 'User' object has no attribute 'userStripe' Request Method: GET Request URL: http://127.0.0.1:8000/checkout/ Django Version: 1.11 Exception Type: AttributeError Exception Value: 'User' object has no attribute 'userStripe' Exception Location: /home/dominic/Desktop/Projects/decentraland/website/manaland/manaland/env/lib/python3.4/site-packages/django/utils/functional.py in inner, line 239 Python Executable: /home/dominic/Desktop/Projects/decentraland/website/manaland/manaland/env/bin/python Python Version: 3.4.3 Python Path: ['/home/dominic/Desktop/Projects/decentraland/website/manaland/manaland', '/home/dominic/Desktop/Projects/decentraland/website/manaland/manaland/env/lib/python3.4', '/home/dominic/Desktop/Projects/decentraland/website/manaland/manaland/env/lib/python3.4/plat-x86_64-linux-gnu', '/home/dominic/Desktop/Projects/decentraland/website/manaland/manaland/env/lib/python3.4/lib-dynload', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/home/dominic/Desktop/Projects/decentraland/website/manaland/manaland/env/lib/python3.4/site-packages'] Server time: Mon, 2 Jul 2018 22:38:35 +0000 checkout.views.py from django.conf import settings from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.decorators import login_required from django.shortcuts import render from users.models import User, profile, userStripe from django.views import generic from django.views.generic import CreateView #TODO UPDATE WITH LIVE VERISON FOR STRIPE API KEYS import stripe stripe.api_key = settings.STRIPE_SECRET_KEY # Create your views here. @login_required def checkout(request): publishKey = settings.STRIPE_PUBLISHABLE_KEY print (request.user.userStripe.stripe_id) if request.method == 'POST': token = request.POST['stripeToken'] # … -
Django Rest Framework why is ModelSerializer creating objects with all null fields?
I have a model called Package. I am trying to save new instances and update existing instances of it in my database by using a ModelSerializer from Django Rest Framework. I want to make a GET request of all Packages from the API server, and save them as new objects or update existing ones in my database. I am successfully creating new objects of Package in my database, however all fields are empty. view.py def pckgs(request): result = {} message = "" save_message = "" endpoint = "removed for stack overflow" response = requests.get(endpoint, auth=auth, params=params) if response.status_code == 200: # SUCCESS result = response.json() s = PackageSerializer(data=result, many=True) if s.is_valid(): s.save() else: save_message = s.errors else: message = response.status_code + " there was an error" context = {'result': result, 'message': message, 'response_url': response.url, 'save_message': save_message} return render(request, 'core/pckgs-active.html', context) serializers.py class PackageSerializer(serializers.ModelSerializer): class Meta: model = Package fields = '__all__' def create(self, validated_data): return Package.objects.create(**validated_data) def update(self, instance, validated_data): instance.label = validated_data.get('label', instance.label) instance.package_type = validated_data.get('package_type', instance.package_type) # ---snip--- there are 32 fields instance.save() return instance I receive no errors from s.errors. On my first try of this method, I did get a few errors that certain fields couldn't … -
Django OneToOneField show up on ModelForm of other entity?
I have the following classes: class Account(models.Model): instance = models.OneToOneField(Instance, blank=True, null=True) class Instance(models.Model): is_ready = models.BooleanField(default=False, verbose_name=_('Ready?')) Right now the relationship between Account and Instance is set by a ModelForm for Account via Account.instance. I would like to be able to set Account.instance via a ModelForm on Instance. Is that possible? -
Custom management commands not executing in django with cookiecutter
I have just hit an issues with executing custom management's commands when using cookiecutter. I have got custom commands to work in Django projects without cookie cutter no problem. I have debugged the issue to the what I think is the cause but unsure how to resolve. First off: On the python shell I can import the management command I created with no errors so I have commands setup correctly. > $ python manage.py shell > >>> from sample.usersExample.management.commands import yourcommand All good. Secondly: I am using the cookiecutter pattern of adding installed app in the following manner. LOCAL_APPS = [ 'sample.users.apps.UsersConfig', 'sample.usersExample.apps.UsersexampleConfig ] Third: The management command location is like so: sample/ manage.py sample/ users/ usersExample/ __init__.py models.py management/ __init__.py commands/ __init__.py myapp_task.py views.py Fourth: I have tried placing the management/commands in mutiple locations all to no avail but still able to access through shell. Root Cause: I believe the root cause of the issue is slightly unqiue setup of the cookiecutter projects and its manage.py file. Manage.py: # This allows easy placement of apps within the interior # gaa directory. current_path = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(current_path, "sample")) execute_from_command_line(sys.argv) Is there a default location when using cookiecutter to place commands. Or … -
TemplateDoesNotExist Error in Pythonanywhere
Erorr I wanna know where django search for index.html Setting.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['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', ], }, }, ] views.py def index(request): return render(request, 'index.html', {}) -
django ManyToMany show related objects
Searched everywhere but couldn't find anything even though it feels so simple. So basically i have two classes in my models.py class Restaurant(models.Model): restaurant_title = models.CharField(max_length=30) location = CountryField(null=True, blank_label='(select country)') first_purchase_discount = models.BooleanField(default=False) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.shop_title class Pizza(models.Model): pizza_title = models.CharField(max_length=20) restaurants = models.ManyToManyField('Restaurant', blank=True) def __str__(self): return self.pizza_title now what i did, was register the models in my admin.py. There i created let's say Restaurant Toni and Restaurant Pappo. On the other hand i created the Pizzas: A, B, C and D. Through the ManyToMany relationship i connected Pizza A,B and C to Toni and B, C and D to Pappo. In my views.py i created a Listview which functions as the Homepage to show where all the Restaurants are being displayed through: restaurants = Restaurant.objects.all() To list the Pizzas i created a DetailView. I've created a link in my restaurant_list.html (which functions as the homepage) to access the Pizzas {% for restaurant in restaurants %} <h2><a href="{% url 'pizza_detail' %}">{{ restaurant.restaurant_title }}</a></h2> {% endfor%} I get the restaurants and each links me to the the Pizzas i associated them to or at least i wish that to happen. here a clear view at … -
Django why does view not go to detail url when detail view specified?
When I go to the following path, a form is presented: path('employee/<str:uid>/boss/new', views.employee_boss_add, name='employee_boss_add') The form data ultimately gets handled by a view that ends with the following statement: return employee_detail(request, employee.uid) So I'm expecting the URI to look like this: path('employee/detail/<str:uid>', views.employee_detail, name='employee_detail'), But instead it looks like this: http://localhost:8000/employee/a6c86326e08e4281b02d319f29ec78ef/direct-report/new Which looks nothing like what is specified by the detail view. It's even showing the wrong data and if input the parameters incorrectly it triggers errors against my update view...