Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Put Django ORM iterations to one request
I have three models: class Box(models.Model): name = models.TextField(blank=True, null=True) class Toy(models.Model): box = models.ForeignKey(Box, related_name='toys') class ToyAttributes(models.Model): toy = models.ForeignKey(Toy) color = models.ForeignKey(Color, related_name='colors') And list: list = [[10, 3], [4, 5], [1, 2]] Where every value is a pair or box and color id's. I need to filter this data and return boxes objects with toys of needed color. Now I do this: box = Box.objects.filter(id=n[0], toys__colors=n[1]) for n in list: if box.exists(): ... But it takes a lot of time for long lists, as I understand because of multiple SQL requests. Can I make it faster? Is it possible to get only needed boxes with one request and how can I make it? Thanks! -
Why I have error message Unknown field for ModelAdmin?
I have created model and admin model In admin editor interface i have error Whats wrong? FieldError at /admin/videos/video/1/change/ Unknown field(s) (name) specified for Video. Check fields/fieldsets/exclude attributes of class VideoAdmin. class Video(models.Model): name = models.CharField(max_length=255) image = models.ImageField(max_length=255, blank=True) video = models.FileField(max_length=255, blank=True) description = models.TextField(blank=True) producer = models.CharField(max_length=255, blank=True) actors = models.TextField(blank=True) duration = models.CharField(max_length=64, blank=True) hit = models.BooleanField(default=False) new = models.BooleanField(default=False) class VideoAdmin(admin.ModelAdmin): fields = ('name',) admin.site.register(Video, VideoAdmin) -
Matplotlib with mpld3: tight_layout works different on Windows and Ubuntu
I use matplotlib and mpld3 to display an interactive figures in Django template. On Windows with python3.5.1 this code with tight_layout works fine and bars in first figure have a correct padding, but in a production server with Ubuntu 16.04.5, with python3.5.2 and same libs I have this warning and there is no padding between two bars: tight_layout.py:181: UserWarning: Tight layout not applied. The bottom and top margins cannot be made large enough to accommodate all axes decorations. warnings.warn('Tight layout not applied. ' views.py: import matplotlib.pyplot as plt from matplotlib import rc from mpld3 import fig_to_html, plugins def graphs(request): ... rc('font', size=16) fig1 = plt.figure() # users profits diagram plt.subplot(121) plt.bar(usernumbers, profits, color='g') for i, v in enumerate(profits): plt.text(i - 0.2, v + 0.3, ' ' + str(v), va='center', fontweight='bold') plt.xticks(usernumbers, usernames) plt.ylabel('$') plt.title('Users profits', fontsize=20) # users orders number diagram plt.subplot(122) plt.bar(usernumbers, ordernumbers, color='b') plt.xticks(usernumbers, usernames) plt.ylabel('Count') plt.title('Users orders', fontsize=20) fig1.tight_layout() ... return render_to_response('graphs.html', {'figure1': fig_to_html(fig1), 'figure2': fig_to_html(fig2), 'user': request.user}) graphs.html: {% extends 'main.html' %} {% block content %} <div class="row"><div class="column"> <center>{{ figure1|safe }}</center><hr/> <center>{{ figure2|safe }}</center> </div></div> {% endblock %} Versions: Django==2.0.7 matplotlib==3.0.2 mpld3==0.3 jinja2==2.10 I also tried plt.tight_layout(), but got the same warning. Maybe exists more … -
docker setting up gdal for django
I'm setting a django project and trying to use docker with it. It has a dependency to gdal likely from using postgis. This is the docker file FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY . /code/ RUN pip install -r requirements.txt and the requirements file Django==2.1.5 psycopg2==2.7.6.1 gdal==2.2.3 when it reaches gdal it throws this error FileNotFoundError: [Errno 2] No such file or directory: 'gdal-config': 'gdal-config' however this is something I've already got working locally (pw) sam@sam-Lenovo-G51-35:~/code/pw$ gdal-config --version 2.2.3 I did try to see if I can make it setup gdal-config using run by editing the docker file to this FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code RUN apt-get install libgdal-dev RUN export CPLUS_INCLUDE_PATH=/usr/include/gdal RUN export C_INCLUDE_PATH=/usr/include/gdal WORKDIR /code COPY . /code/ RUN pip install -r requirements.txt based on the nearest match for error to possible solution but it throws this error Step 4/9 : RUN apt-get install libgdal-dev ---> Running in 8e5e71369e4a Reading package lists... Building dependency tree... Reading state information... E: Unable to locate package libgdal-dev -
Django-import-export accessing fields in file not used by the ModelResource
The original question was posted here: https://github.com/django-import-export/django-import-export/issues/886 Hello everyone, I have an xslx document with the following columns: category | venue | event | question | answer | client | Action The Category, Venue, Event and Client are ForeignKeys. If they do not exist they should be created so I have created custom ForeignKeyWidgets: class ForeignKeyWidgetWithCreation(ForeignKeyWidget): def __init__( self, model, field='pk', create=False, *args, **kwargs): self.model = model self.field = field self.create = create # super(ForeignKeyWidgetWithCreation, self).__init__(*args, **kwargs) def clean(self, value, row=None, *args, **kwargs): val = super(ForeignKeyWidgetWithCreation, self).clean(value) if self.create: instance, new = self.model.objects.get_or_create(**{ self.field: val }) val = getattr(instance, self.field) return self.model.objects.get(**{self.field: val}) if val else None # Event Widget class EventWidget(ForeignKeyWidget): def __init__( self, model, field='pk', create=False, *args, **kwargs): self.model = model self.field = field self.create = create # super(ForeignKeyWidgetWithCreation, self).__init__(*args, **kwargs) def clean(self, value, row=None, *args, **kwargs): val = super(ForeignKeyWidgetWithCreation, self).clean(value) if self.create: instance, new = self.model.objects.get_or_create(**{ self.field: val }) val = getattr(instance, self.field) return self.model.objects.get(**{self.field: val}) if val else None # CLIENT WIDGET class ClientWidget(ForeignKeyWidget): def __init__(self, model, field='client', *args, **kwargs): self.model = Client self.field = field def clean(self, value, row=None, *args, **kwargs): val = super(ClientWidget, self).clean(value) if val: client = Client.objects.get_or_create(name=val) return client # return self.get_queryset(value, … -
DRF: drf-nested-routers: Could not resolve URL for hyperlinked relationship using view name
I'm having trouble displaying the -detail of a model using viewsets. I'm using the drf-nested-routers package for my urls. Here is an example of Courses and a Section related to the course. (code is below) [ { "url": "http://127.0.0.1:8000/courses/CS250/", "course_code": "CS250", "sections_offered": [ "http://127.0.0.1:8000/courses/CS250/sections/01/" ] }, { "url": "http://127.0.0.1:8000/courses/CS150/", "course_code": "CS150", "sections_offered": [] } ] I can navigate to courses/CS250/sections only if there was nothing, but once I create an object there I can no longer visit that endpoint, and I also cannot visit the URL of that object (http://127.0.0.1:8000/courses/CS250/sections/01/) without getting this error: django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "section-detail". You may have failed to include the related model in your API, or incorrectly configured the 'lookup_field' attribute on this field. However, I can perfectly navigate to the url of a course (http://127.0.0.1:8000/courses/CS250/) /models.py from django.db import models class Course(models.Model): course_code = models.CharField(default='', max_length=50, primary_key=True) class Section(models.Model): section_number = models.CharField(default='01', max_length=100, primary_key=True) parent_course = models.ForeignKey(Course, related_name="sections_offered", on_delete=models.CASCADE, blank=True, null=True) /views.py from . import models from . import serializers from rest_framework import viewsets class CourseViewSet(viewsets.ModelViewSet): serializer_class = serializers.CourseSerializer queryset = models.Course.objects.all() class SectionViewSet(viewsets.ModelViewSet): serializer_class = serializers.SectionSerializer queryset = models.Section.objects.all() /serializers.py from rest_framework_nested.relations import NestedHyperlinkedRelatedField from … -
How do I restore access to local Django site using "python manage.py runserver" after upgrading Homebrew?
I upgraded Homebrew in the terminal. After entering my virtual environment with no problem, I typed "python manage.py runserver" as usual, but I got the following error: /usr/local/Cellar/python/3.7.2/Frameworks/Python.framework/Versions/3.7/Resources/Python.app/Contents/MacOS/Python: can't open file 'manage.py': [Errno 2] No such file or directory I assume the upgrade requires me to change something, but I'm not sure what I need to do. Do I need to reinstall Django? -
How can I fix errors in django?
I've tried everything I can, but I can't fix this error. I am a beginner and imitated what was in the book. Give me a hand. Source Code This is my urls.py-fistsite source code. from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('', views.index, name='index'), path('/polls', views.polls, name='polls'), path('/admin', views.admin, name='admin') ] This is my urls.py-polls from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/result/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote') ] But there was an error. enter image description here And this is my project.enter image description here Help me! -
Django Migration errors
im trying to migrate these models and im getting error.I added the field position,manager which were initially not in my model.made project_name a primary key in Project models:i ran python manage.py migrate and i get an error: Below is the models. class Employee(models.Model): position = models.CharField(max_length=200) manager= models.CharField(max_length=200,default="x") employee_number = models.PositiveIntegerField(primary_key=True) class Project(models.Model): project_code=models.CharField(max_length=200) employees=models.ManyToManyField(Employee,through="User_Projects") project_name= models.TextField(primary_key=True) class User_Projects(models.Model): employee_number=models.ForeignKey(Employee,to_field='employee_number',on_delete=models.CASCADE) project_name=models.ForeignKey(Project,to_field="project_name",on_delete=models.CASCADE) The error i am getting is below,i need help: InternalError:(1829,"cannot drop column 'id' : needed in a foreign key constraint 'timeapp_user_projects_projects_id_cf8c73ba_fk_timeapp_project_id' of table 'timesheets.timeapp_user_projects'") -
problems with pip install mod-wsgi
I'm new IT and programming; I been struggling to install mod_wsgi with pip Example in cmd: pip install mod_wsgi I been trying to lunch my django project on my own pc acting as a server I'm using Apcache 24 and my PC is windows 10, 64bits My python is 3.7.1 and Django is 2.1.3 Solution I had try: https://stackoverflow.com/a/42323871/10865416 error: error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/ I had check and and intsall the C++ 14 here the link where I download: https://www.microsoft.com/en-gb/download/details.aspx?id=48145 https://github.com/sammchardy/python-binance/issues/148#issuecomment-374853521 error: C:\Users\user>pip install C:/mod_wsgi-4.5.24+ap24vc14-cp35-cp35m-wind_amd64.whl Requirement 'C:/mod_wsgi-4.5.24+ap24vc14-cp35-cp35m-wind_amd64.whl' looks like a filename, but the file does not exist mod_wsgi-4.5.24+ap24vc14-cp35-cp35m-wind_amd64.whl is not a supported wheel on this platform. https://github.com/GrahamDumpleton/mod_wsgi/blob/develop/win32/README.rst error: error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\BuildTools\\VC\\Tools\\MSVC\\14.16.27023\\bin\\HostX86\\x86\\link.exe' failed with exit status 1120 ---------------------------------------- Command "c:\users\user\appdata\local\programs\python\python37-32\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\user\\AppData\\Local\\Temp\\pip-install-f9igth3o\\mod-wsgi\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\user\AppData\Local\Temp\pip-record-kmcbksbk\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\user\AppData\Local\Temp\pip-install-f9igth3o\mod-wsgi\ and yes hd VC10 install to had this error, here the link https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2017 In advance thank you for your help, apprentice it -
Retrieving a user based on email fails in django
I created a user in django that only has an email and a password. I am trying to obtain the object using that email address. I am doing the following user_obj = User.objects.filter(Q(email=email)) However user_obj is always empty. Then I tried the following. In the following method i got all the users and iterated over them until I came across the user with that email address allusers = User.objects.all() user_obj = User.objects.filter(Q(email=email)) #--->Returns empty Why? for a in allusers: if a.email == email: print("Found") #<---Email Exists #-->Comes in here. So email does exist My question is why is User.objects.filter(Q(email=email)) returning an empty queryset when the object does exist in the db. It just doesnt have a username or anything. It only has email address and a password. -
Multiple Select Foreign Key Field Django Form
I have a form where I want to display multiple select foreign key field. Form.py class ManagerGroupForm(forms.ModelForm): class Meta: model = UserGroup fields = ['usergroup_group'] Models.py class UserGroup(models.Model): usergroup_user = models.ForeignKey(User, on_delete=models.CASCADE) usergroup_group = models.ForeignKey(Groups, on_delete=models.CASCADE) In my form I want to select usergroup_group multiple times. -
django modelform more then one foreign key using exclude
here user i want user and userprofile. useing exclude. when i add userprofile error 'WSGIRequest' object has no attribute 'userprofile' modelform class ProductForm(forms.ModelForm): class Meta: model = Product fields = ('categories', 'title', 'description', 'image', 'price') exclude = ('user','userprofile') view @login_required def productpost(request): form = ProductForm() if request.method == "POST": form = ProductForm(request.POST, request.FILES) if form.is_valid(): form = form.save(commit=False) form.user = request.user form.userprofile = request.userprofile form.save() return success(request) else: print("The Form Is Invalid") return render(request, 'product/postproduct.html', {'form': form}) -
POST http://127.0.0.1:8000/api/users/ 400 (Bad Request)
I was trying to create simple api using django rest framework but stuck in the error. Hoping for the soon response. Thanks in advance. serializers.py from django.contrib.auth.models import User from rest_framework import serializers class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password') extra_kwargs = { 'password' : { 'write_only' : True , 'required':True }} def create(self, validated_data): user = User.objects.create_user(**validated_data) return user views.py from django.contrib.auth.models import User from rest_framework import viewsets from register_api.serializers import UserSerializer class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer register/urls.py(app) from django.urls import path, include from rest_framework import routers from register_api import views # from rest_framework.authtoken.views import ObtainAuthToken router = routers.DefaultRouter() router.register('users', views.UserViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls',namespace='rest_framework')), ] **django_api/url.py** (project) from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('register_api.urls')), ] Backend error Console Error -
nginx access log shows HEAD request every 5 seconds
I have a Django Gunicorn Nginx setup that is working without errors but the nginx access logs contains the following line every 5 seconds: 10.112.113.1 - - [09/Jan/2019:05:02:21 +0100] "HEAD / HTTP/1.1" 302 0 "-" "-" The amount of information in this logging event is quite scarce, but a 302 every 5 seconds has to be something related to the nginx configuration right? My nginx configuration is as follows: http { log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; include /etc/nginx/conf.d/.conf; upstream app_server { server unix:/path_to/gunicorn.sock fail_timeout=0; } server { server_name example.com; listen 80; return 301 https://example.com$request_uri; } server { listen 443; listen [::]:443; server_name example.com; ssl on; ssl_certificate /path/cert.crt; ssl_certificate_key /path/cert.key; keepalive_timeout 5; client_max_body_size 4G; access_log /var/log/nginx/nginx-access.log; error_log /var/log/nginx/nginx-error.log; location /static/ { alias /path_to/static/; } location /media/ { alias /path_to/media/; } include /etc/nginx/mime.types; # checks for static file, if not found proxy to app location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_set_header Host $host; proxy_redirect off; proxy_pass http://app_server; } } } -
Reorder available options in filter_horizontal widget
I use an m2m relation in my Django model and filter_horizontal option to show it in the admin. After moving some items to the "chosen" and then removing them back to the "available" in this widget, the items are shown at the bottom of the "available" list. Is it possible to rearrange them in the order in which they were shown initially? -
Django search result with pagination
There is search field in template that can enter a keyword to search in a model and show the result with pagination. I need to pass this keyword in views.py def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if 'color' in self.request.GET and self.request.GET['color']: context['query'] = self.request.GET.get('color') return context and combine it with pagination to prevent error.( If I don't do this, it will go to next page with raw data) {% if page_obj.has_next %} <a id="next" href="?page={{ page_obj.next_page_number }}{% if query %}&q={{ query }}{% endif %}">next</a> <a id="last" href="?page={{ page_obj.paginator.num_pages }}{% if query %}&q={{ query }}{% endif %}">last &raquo;</a> {% endif %} Is there any good idea to solve this problem? I know this is such a stupid solution... -
django-channels: No route found for path
I have a Django + Vue.js chat application that I'm trying to connect to django-channels. To access any chat room, you simply go to: http://localhost:8080/rooms/"id"/ My javascript connection looks like this: connectToWebSocket () { const chatSocket = new WebSocket( `ws://localhost:8000/ws/rooms/${this.$route.params.id}/` ) chatSocket.onopen = this.onOpen chatSocket.onclose = this.onClose chatSocket.onmessage = this.onMessage chatSocket.onerror = this.onError }, My consumers.py: class ChatConsumer(WebsocketConsumer): def connect(self): self.room_uri = self.scope['url_route']['kwargs']['uri'] self.room_group_name = 'chat_%s' % self.room_uri # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] user = text_data_json['user.username'] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'user': user, 'message': message } ) # Receive message from room group def chat_message(self, event): user = event['user'] message = event['message'] # Send message to WebSocket self.send(text_data=json.dumps({ 'user': user, 'message': message })) and my routing.py: from django.conf.urls import url from core import consumers websocket_urlpatterns = [ url(r'^ws/rooms/<uri>/', consumers.ChatConsumer), ] (it's connected the ProtocolTypeRouter in my main folder). The problem is, I can't connect to the websocket, my django server says: [Failure instance: Traceback: : No route found for path 'ws/rooms/759b9a8262ea4b7/'. What's wrong in my … -
Django template render html links does not works
In my django project i have to rendere a var ina template as html. I do this in my view: con_stat = "<div id='overlay_demo' style='display:block'><div id='text-demo'><div class='login-box-body'><p class='login-box-msg'><strong><font color='red'>MY TITLE HERE</font></strong></p><br>My text here<br><br><div><form><button onclick='location.href=https://mywebsite.com/contact;' class='btn btn-block btn-danger btn-lg'>REPORT THE PROBLEM</button><br><a href='/register/retry'><button class='btn btn-block btn-success btn-lg'>RETRY THE REGISTRATION PROCES</button></a></form></div></div></div></div>" context_dict = {'all_case': test_case, 'all_set': sg, 'the_stat': con_stat} response = render(request, b_temp, context_dict, context) well, at this point in my html template: {% autoescape off %}{{ the_stat }}{% endautoescape %} or also i try: {{ the_stat|safe }} template now display html correctly but the problem is the link, not my first button (with onclick= function) nor second one (with a href link) works. In every case when i click the behaviour is to reload the same page. Someone had experienced some problem related to link,javascript call in django template render like that above? So many thanks in advance -
Problems in Django
I don't know why this problem happened.enter image description here These errors occur when you read a book and follow it. I don't know what to do. Give me a hand. Source Code views.py in polls from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from polls.models import Question, Choice # Create your views here. def index(request): latest_question_list = Question.objects.all().order_by('-pub_date')[:5] context = {'latest_question_list':latest_question_list} return render(request, 'polls/index.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice.set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html',{ 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) def results(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/result.html', {'question': question}) models.py in polls from django.db import models # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text -
Upload unknown numbers (dynamically decided) of files under Django framework
I encountered an issue: if I want to apply this dynamically rows adding bootstrap code(ref here bootstrap) , I won't be knowing how many files user will upload in advance.(Although I define a maximum of numbers of files allowed to be uploaded:10) I am using Django 2.1.5. I have tried to write something like UploadFileForm in form.py, but in that way, I needed to write exactly 10 form.Charfield inside the class, which I am not willing to see. <form action="" method="post" enctype="multipart/form-data" id="bookform"> {% csrf_token %} <table id="createBookTable" class=" table order-list"> <thead> <tr> <td>book title(in original lang.)</td> <td>author(in original lang.)</td> <td>book title(in Eng.)</td> <td>author(in Eng.)</td> <td>book image</td> </tr> </thead> <tbody> <tr style="display:none"> <td colspan="5" style="text-align: left;" > <input type="text" id="counter" name="counter" value=""/> </td> </tr> <tr class="bookTr" id="bookTr-0"> <td class="col-sm-3"> <input type="text" name="orginBookname0" class="form-control" /> </td> <td class="col-sm-3"> <input type="mail" name="originAuthor0" class="form-control"/> </td> <td class="col-sm-3"> <input type="text" name="engBookname0" class="form-control"/> </td> <td class="col-sm-3"> <input type="text" name="engAuthor0" class="form-control"/> </td> <td> <input type="file" name="bookimg0"> </td> <td class="col-sm-1"><a class="deleteRow"></a> </td> </tr> </tbody> <tfoot> <tr> <td colspan="5" style="text-align: left;"> <input type="button" class="btn btn-lg btn-block " id="addrow" value="Add Row" /> </td> </tr> <tr> <td colspan="5" style="text-align: left;"> <input type="submit" name="button" id="bookSubmitBtn" class="btn btn-lg btn-block btn-beautiful" value="Submit"> </td> … -
Vue-Bootstrap doesn't work with Django. How can I start with it correctly?
I'm really new to VueJS. I'm trying to use vue-bootstrap instead of usual bootstrap (including jquery). But it doesn't work at all even though there's no error. All files are loaded. base.html {% load static %} <!DOCTYPE html> <html> <head> <link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css"/> <link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.css"/> </head> <body> {% block content %} {% endblock content %} <script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script> <script src="//unpkg.com/babel-polyfill@latest/dist/polyfill.min.js"></script> <script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.js"></script> </body> and I copied this from the example of vue-bootstrap doc https://bootstrap-vue.js.org/docs/components/navbar/ index.html {% extends 'base.html' %} {% block content %} <b-navbar toggleable="md" type="dark" variant="info"> <b-navbar-toggle target="nav_collapse"></b-navbar-toggle> <b-navbar-brand href="#">NavBar</b-navbar-brand> <b-collapse is-nav id="nav_collapse"> <b-navbar-nav> <b-nav-item href="#">Link</b-nav-item> <b-nav-item href="#" disabled>Disabled</b-nav-item> </b-navbar-nav> <!-- Right aligned nav items --> <b-navbar-nav class="ml-auto"> <b-nav-form> <b-form-input size="sm" class="mr-sm-2" type="text" placeholder="Search"/> <b-button size="sm" class="my-2 my-sm-0" type="submit">Search</b-button> </b-nav-form> <b-nav-item-dropdown text="Lang" right> <b-dropdown-item href="#">EN</b-dropdown-item> <b-dropdown-item href="#">ES</b-dropdown-item> <b-dropdown-item href="#">RU</b-dropdown-item> <b-dropdown-item href="#">FA</b-dropdown-item> </b-nav-item-dropdown> <b-nav-item-dropdown right> <!-- Using button-content slot --> <template slot="button-content"> <em>User</em> </template> <b-dropdown-item href="#">Profile</b-dropdown-item> <b-dropdown-item href="#">Signout</b-dropdown-item> </b-nav-item-dropdown> </b-navbar-nav> </b-collapse> </b-navbar> {% endblock content %} But it shows like this What am I wrong with it? -
django connec mysql --_mysql_exceptions.OperationalError: (2006, <NULL>)
In fact, I learn the django from the website:https://docs.djangoproject.com/zh-hans/2.1/intro/tutorial02/ The next is my settting.py DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # } 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django_01', 'USER': 'root', 'PASSWORD': '9940', 'HOST': 'localhost', # Or an IP Address that your DB is hosted on 'PORT': '3306', } } mysql : enter image description here I want to know how to solve this problem,or I don't know what's the problem? Thank you very much! I think DATABASES is right, I want to connect mysql to django program named mysite, but I run 'python manage.py migrate': Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0000000003B31D08> Traceback (most recent call last): File "D:\Tools\Anaconda3\envs\test-django\lib\site-packages\django\db\backends\base\base.py", line 216, in ensure_connection self.connect() File "D:\Tools\Anaconda3\envs\test-django\lib\site-packages\django\db\backends\base\base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "D:\Tools\Anaconda3\envs\test-django\lib\site-packages\django\db\backends\mysql\base.py", line 227, in get_new_connection return Database.connect(**conn_params) File "D:\Tools\Anaconda3\envs\test-django\lib\site-packages\MySQLdb\__init__.py", line 85, in Connect return Connection(*args, **kwargs) File "D:\Tools\Anaconda3\envs\test-django\lib\site-packages\MySQLdb\connections.py", line 208, in __init__ super(Connection, self).__init__(*args, **kwargs2) _mysql_exceptions.OperationalError: (2006, <NULL>) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\Tools\Anaconda3\envs\test-django\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "D:\Tools\Anaconda3\envs\test-django\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run self.check_migrations() File "D:\Tools\Anaconda3\envs\test-django\lib\site-packages\django\core\management\base.py", line 442, in check_migrations executor … -
How to write the view of saving a model which having foreign key
I am new in Django developing and I have a model Customers that is in a relationship with a ZipCode model. So from the model Customers, I want to get the zipCode in the ZipCode model. This, the ZipCode model has 4 attributes such as pk which is an aut_increment, zipCode which is unique, city and state. Therefore, my issues are: How to get the zipCode attribute as a foreign key in the Customer model and how the view of saving the customer object can be written? Below is are the Customers and the ZipCode models: class Customers(models.Model): customerID = models.CharField(max_length=15, unique=True) firstName = models.CharField(max_length=20) lastName = models.CharField(max_length=25) phoneNumber = models.CharField(max_length=14) zipCode = models.ForeignKey(ZipCode, on_delete=models.CASCADE) address = models.TextField() class ZipCode(models.Model): zipCode = models.CharField(max_length=10, unique=True) city = models.CharField(max_length=30) state = models.CharField(max_length=25) def __str__(self): return self.zipCode + ' ' + self.city + ' ' + self.state Here also the view add_customers which is not working: def add_Custmers(request): # try: # zipCode=ZipCode.objects.get(slug=zipcode_slug) # except ZipCode.DoesNotExist: # zipCode=None form=CustomersForm(request.POST or None) if form.is_valid(): form.save() context = {'form': form} return render(request, 'customers.html', context I attached the add customer form for more details -
Connecting to Could SQL from local machine via proxy
I am following these instructions to deploy a Django app on Google App Engine: https://cloud.google.com/python/django/appengine I have got as far as downloading the proxy .exe file (I am on a Windows machine) and connecting to it: 2019/01/08 16:14:08 Listening on 127.0.0.1:3306 for [INSTANCE-NAME] 2019/01/08 16:14:08 Ready for new connections When I try and create the Django migrations by running python manage.py createmigrations I see the connection received by the proxy file: 2019/01/08 16:15:06 New connection for "[INSTANCE-NAME]" However, after a couple of seconds pause I get this error: 2019/01/08 16:15:28 couldn't connect to "[INSTANCE-NAME]": dial tcp 35.205.185.133:3307: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. I have tried disabling my local firewall in case this was causing any issues, but the result is the same. I've also checked the username, password and Cloud SQL instance name, they are all correct. What could be causing this error?